focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public String defaultRemoteUrl() {
final String sanitizedUrl = sanitizeUrl();
try {
URI uri = new URI(sanitizedUrl);
if (uri.getUserInfo() != null) {
uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri... | @Test
void shouldNotModifyWindowsFileSystemPath() {
assertThat(new HgUrlArgument("c:\\foobar").defaultRemoteUrl(), is("c:\\foobar"));
} |
public boolean commitOffsetsSync(Map<TopicPartition, OffsetAndMetadata> offsets, Timer timer) {
invokeCompletedOffsetCommitCallbacks();
if (offsets.isEmpty()) {
// We guarantee that the callbacks for all commitAsync() will be invoked when
// commitSync() completes, even if the u... | @Test
public void testCommitOffsetSyncNotCoordinator() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
// sync commit with coordinator disconnected (should connect, get metadata, and then submit the commi... |
@Override
public boolean isWriteable(Class<?> type,
@Nullable Type genericType,
@Nullable Annotation[] annotations,
@Nullable MediaType mediaType) {
return isProvidable(type) && super.isWriteable(type, genericType, ... | @Test
void doesNotWriteIgnoredTypes() {
assertThat(provider.isWriteable(Ignorable.class, null, null, null))
.isFalse();
} |
public static List<ClientMessage> getFragments(int maxFrameSize, ClientMessage clientMessage) {
if (clientMessage.getFrameLength() <= maxFrameSize) {
return Collections.singletonList(clientMessage);
}
long fragmentId = FRAGMENT_ID_SEQUENCE.next();
LinkedList<ClientMessage> fr... | @Test
@RequireAssertEnabled
public void testGetSubFrame_whenFrameSizeGreaterThanFrameLength_thenReturnOriginalMessage() {
List<ClientMessage> fragments = getFragments(4000, clientMessage);
ClientMessage.ForwardFrameIterator originalIterator = clientMessage.frameIterator();
assertFragmen... |
@Override
public double mean() {
return n * p;
} | @Test
public void testMean() {
System.out.println("mean");
BinomialDistribution instance = new BinomialDistribution(100, 0.3);
instance.rand();
assertEquals(30.0, instance.mean(), 1E-7);
} |
public static void extractJoinConditions(final Collection<BinaryOperationExpression> joinConditions, final Collection<WhereSegment> whereSegments) {
for (WhereSegment each : whereSegments) {
if (each.getExpr() instanceof BinaryOperationExpression && ((BinaryOperationExpression) each.getExpr()).getLe... | @Test
void assertExtractJoinConditions() {
Collection<BinaryOperationExpression> actual = new LinkedList<>();
BinaryOperationExpression binaryExpression =
new BinaryOperationExpression(0, 0, new ColumnSegment(0, 0, new IdentifierValue("order_id")), new ColumnSegment(0, 0, new Identif... |
public static RocksDbIndexedTimeOrderedWindowBytesStoreSupplier create(final String name,
final Duration retentionPeriod,
final Duration windowSize,
... | @Test
public void shouldThrowIfStoreNameIsNull() {
final Exception e = assertThrows(NullPointerException.class, () -> RocksDbIndexedTimeOrderedWindowBytesStoreSupplier.create(null, ZERO, ZERO, false, false));
assertEquals("name cannot be null", e.getMessage());
} |
@Override
public synchronized ScheduleResult schedule()
{
dropListenersFromWhenFinishedOrNewLifespansAdded();
int overallSplitAssignmentCount = 0;
ImmutableSet.Builder<RemoteTask> overallNewTasks = ImmutableSet.builder();
List<ListenableFuture<?>> overallBlockedFutures = new Arr... | @Test
public void testBlockCausesFullSchedule()
{
NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService);
// Schedule 60 splits - filling up all nodes
SubPlan firstPlan = createPlan();
SqlStageExecution firstStage = createSqlStageExecution(firstPlan, nodeTaskMap);
S... |
@Override
public boolean isSupported() {
return true;
} | @Test
public void isSupported() {
MeizuImpl meizu = new MeizuImpl(mApplication);
Assert.assertTrue(meizu.isSupported());
} |
static KiePMMLDiscretize getKiePMMLDiscretize(final Discretize discretize) {
List<KiePMMLDiscretizeBin> discretizeBins = discretize.hasDiscretizeBins() ?
getKiePMMLDiscretizeBins(discretize.getDiscretizeBins()) : Collections.emptyList();
String mapMissingTo = discretize.getMapMissingTo()... | @Test
void getKiePMMLDiscretize() {
Discretize toConvert = getRandomDiscretize();
KiePMMLDiscretize retrieved = KiePMMLDiscretizeInstanceFactory.getKiePMMLDiscretize(toConvert);
commonVerifyKiePMMLDiscretize(retrieved, toConvert);
} |
public void processTable() {
String entityName = entity.getNameConvert().entityNameConvert(this);
this.setEntityName(entity.getConverterFileName().convert(entityName));
this.mapperName = strategyConfig.mapper().getConverterMapperFileName().convert(entityName);
this.xmlName = strategyConf... | @Test
void processTableTest() {
StrategyConfig strategyConfig = GeneratorBuilder.strategyConfig();
TableInfo tableInfo = new TableInfo(new ConfigBuilder(GeneratorBuilder.packageConfig(), dataSourceConfig, strategyConfig, null, GeneratorBuilder.globalConfig(), null), "user");
tableInfo.proces... |
@Override
protected List<MatchResult> match(List<String> specs) {
List<AzfsResourceId> paths =
specs.stream().map(AzfsResourceId::fromUri).collect(Collectors.toList());
List<AzfsResourceId> globs = new ArrayList<>();
List<AzfsResourceId> nonGlobs = new ArrayList<>();
List<Boolean> isGlobBoolea... | @Test
@Ignore
public void testMatch() throws Exception {
// TODO: Write this test with mocks - see GcsFileSystemTest
String container = "test-container" + randomUUID();
BlobContainerClient blobContainerClient =
azureBlobStoreFileSystem.getClient().createBlobContainer(container);
// Create f... |
@Override
public boolean enable(String pluginId) {
return false;
} | @Test
public void testEnable() {
ThreadPoolPlugin plugin = new TestPlugin();
Assert.assertFalse(manager.enable(plugin.getId()));
manager.register(plugin);
Assert.assertFalse(manager.enable(plugin.getId()));
manager.disable(plugin.getId());
Assert.assertFalse(manager.e... |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldCleanMigrationsStreamEvenIfTableDoesntExist() throws Exception {
// Given:
givenMigrationsTableDoesNotExist();
// When:
final int status = command.command(config, cfg -> client);
// Then:
assertThat(status, is(0));
verify(client).executeStatement("DROP STREAM " +... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
final Region region = regionService.lookup(file);
try {
if(containerService.isContainer(f... | @Test
public void testFindPlaceholder() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final String name = UUID.randomUUID().toString();
final Path file = new Path(co... |
@Override
public Map<String, String> requestHeaders() {
return unmodifiableMap(requestHeaders);
} | @Test
public void shouldReturnUnmodifiableRequestHeaders() throws Exception {
DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest("extension", "1.0", "request-name");
Map<String, String> requestHeaders = request.requestHeaders();
try {
requestHeaders.put("new-key", ... |
@Path("batch")
@POST
public Response batchReplication(ReplicationList replicationList) {
try {
ReplicationListResponse batchResponse = new ReplicationListResponse();
for (ReplicationInstance instanceInfo : replicationList.getReplicationList()) {
try {
... | @Test
public void testRegisterBatching() throws Exception {
ReplicationList replicationList = new ReplicationList(newReplicationInstanceOf(Action.Register, instanceInfo));
Response response = peerReplicationResource.batchReplication(replicationList);
assertStatusOkReply(response);
v... |
@Override
public boolean matches(T objectUnderTest) {
boolean matches = super.matches(objectUnderTest);
describedAs(buildVerboseDescription(objectUnderTest, matches));
return matches;
} | @Test
public void should_succeed_and_display_description_without_actual() {
assertThat(VERBOSE_CONDITION.matches("foo")).isTrue();
assertThat(VERBOSE_CONDITION).hasToString("shorter than 4");
} |
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final SelectionParameters other = (SelectionParamet... | @Test
public void testDifferentResultTypes() {
List<String> qualifyingNames = Arrays.asList( "language", "german" );
TypeMirror resultType = new TestTypeMirror( "resultType" );
List<TypeMirror> qualifiers = new ArrayList<>();
qualifiers.add( new TestTypeMirror( "org.mapstruct.test.So... |
public static Function<Component, String> toComponentUuid() {
return ToComponentUuid.INSTANCE;
} | @Test
public void toComponentUuid_returns_the_ref_of_the_Component() {
assertThat(toComponentUuid().apply(ReportComponent.builder(PROJECT, SOME_INT).setUuid("uuid_" + SOME_INT).build())).isEqualTo("uuid_" + SOME_INT);
} |
@Override
public void unbindSocialUser(Long userId, Integer userType, Integer socialType, String openid) {
// 获得 openid 对应的 SocialUserDO 社交用户
SocialUserDO socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, openid);
if (socialUser == null) {
throw exception(SOCIAL_USE... | @Test
public void testUnbindSocialUser_success() {
// 准备参数
Long userId = 1L;
Integer userType = UserTypeEnum.ADMIN.getValue();
Integer type = SocialTypeEnum.GITEE.getType();
String openid = "test_openid";
// mock 数据:社交用户
SocialUserDO socialUser = randomPojo(So... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testKarateCallThatReturnsJson() {
run(
"def res = karate.call('called3.js')"
);
matchVar("res", "{ varA: '2', varB: '3' }");
} |
static String getStreamFromOpenElement(String openElement) {
String streamElement = openElement.replaceFirst("\\A<open ", "<stream:stream ")
.replace("urn:ietf:params:xml:ns:xmpp-framing", "jabber:client")
.replaceFirst("/>\\s*\... | @Test
public void getStreamFromOpenElementTest() {
assertEquals(OPEN_STREAM, AbstractWebSocket.getStreamFromOpenElement(OPEN_ELEMENT));
assertEquals(OPEN_STREAM, AbstractWebSocket.getStreamFromOpenElement(OPEN_ELEMENT_EXPANDED));
} |
@Nullable static String getPropertyIfString(Message message, String name) {
try {
Object o = message.getObjectProperty(name);
if (o instanceof String) return o.toString();
return null;
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting property {0} from message {1}"... | @Test void getPropertyIfString_null() {
assertThat(MessageProperties.getPropertyIfString(message, "b3")).isNull();
} |
protected RouteStatistic recalculate(final Route route, final RouteStatistic routeStatistic) {
AtomicInteger totalEips = new AtomicInteger(routeStatistic.getTotalEips());
AtomicInteger totalEipsTested = new AtomicInteger(routeStatistic.getTotalEipsTested());
AtomicInteger totalProcessingTime = ... | @Test
public void testRecalculate() {
} |
@Override
public Optional<WorkItem> getWorkItem() throws IOException {
List<String> workItemTypes =
ImmutableList.of(
WORK_ITEM_TYPE_MAP_TASK,
WORK_ITEM_TYPE_SEQ_MAP_TASK,
WORK_ITEM_TYPE_REMOTE_SOURCE_TASK);
// All remote sources require the "remote_source" capabili... | @Test
public void testCloudServiceCallMapTaskStagePropagation() throws Exception {
// Publish and acquire a map task work item, and verify we're now processing that stage.
final String stageName = "test_stage_name";
MapTask mapTask = new MapTask();
mapTask.setStageName(stageName);
WorkItem workIte... |
private String getEnv(String envName, InterpreterLaunchContext context) {
String env = context.getProperties().getProperty(envName);
if (StringUtils.isBlank(env)) {
env = System.getenv(envName);
}
if (StringUtils.isBlank(env)) {
LOGGER.warn("environment variable: {} is empty", envName);
... | @Test
void testYarnClientMode_2() throws IOException {
SparkInterpreterLauncher launcher = new SparkInterpreterLauncher(zConf, null);
Properties properties = new Properties();
properties.setProperty("SPARK_HOME", sparkHome);
properties.setProperty("property_1", "value_1");
properties.setProperty("... |
public static String join(List<PdlParser.IdentifierContext> identifiers)
{
StringBuilder stringBuilder = new StringBuilder();
Iterator<PdlParser.IdentifierContext> iter = identifiers.iterator();
while (iter.hasNext())
{
stringBuilder.append(iter.next().value);
if (iter.hasNext())
{
... | @Test
public void testJoin()
{
PdlParser.IdentifierContext a = new PdlParser.IdentifierContext(null, 0);
a.value = "a";
PdlParser.IdentifierContext b = new PdlParser.IdentifierContext(null, 0);
b.value = "b";
assertEquals(PdlParseUtils.join(Arrays.asList(a, b)), "a.b");
} |
@Override
public String[] getOutputMetricKeys() {
return new String[] {metricKey};
} | @Test
public void check_output_metric_key_is_function_complexity_distribution() {
assertThat(BASIC_DISTRIBUTION_FORMULA.getOutputMetricKeys()).containsOnly(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY);
} |
public String getToken() throws IOException {
LOGGER.debug("[Agent Registration] Using URL {} to get a token.", tokenURL);
HttpRequestBase getTokenRequest = (HttpRequestBase) RequestBuilder.get(tokenURL)
.addParameter("uuid", agentRegistry.uuid())
.build();
try ... | @Test
void shouldGetTokenFromServer() throws Exception {
final ArgumentCaptor<HttpRequestBase> argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
when(agentRegistry.uuid()).thenReturn("agent-uuid");
... |
@Override
public Reiterator<ShuffleEntry> read(
@Nullable ShufflePosition startPosition, @Nullable ShufflePosition endPosition) {
return new ShuffleReadIterator(startPosition, endPosition);
} | @Test
public void readerShouldMergeMultipleBatchResultsIncludingEmptyShards() throws Exception {
List<ShuffleEntry> e1s = new ArrayList<>();
List<ShuffleEntry> e2s = new ArrayList<>();
ShuffleEntry e3 = newShuffleEntry(KEY, SKEY, VALUE);
List<ShuffleEntry> e3s = Collections.singletonList(e3);
when... |
@Override
public InputStream getInputStream(final int columnIndex, final String type) throws SQLException {
return mergedResult.getInputStream(columnIndex, type);
} | @Test
void assertGetInputStream() throws SQLException {
InputStream inputStream = mock(InputStream.class);
when(mergedResult.getInputStream(1, "asc")).thenReturn(inputStream);
assertThat(new EncryptMergedResult(database, encryptRule, selectStatementContext, mergedResult).getInputStream(1, "a... |
public <T> Gauge<T> registerGauge(String name, Gauge<T> metric) throws IllegalArgumentException {
return register(name, metric);
} | @Test
public void infersGaugeType() {
Gauge<Long> gauge = registry.registerGauge("gauge", () -> 10_000_000_000L);
assertThat(gauge.getValue()).isEqualTo(10_000_000_000L);
} |
@Override
public void persist(final String key, final String value) {
try {
if (isExisted(key)) {
update(key, value);
return;
}
String tempPrefix = "";
String parent = SEPARATOR;
String[] paths = Arrays.stream(key.sp... | @Test
void assertPersistForDirectory() throws SQLException {
final String key = "/parent/child/test1";
final String value = "test1_content";
when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByKeySQL())).thenReturn(mockPreparedStatement);
when(mockJdbcConnection.prepare... |
@Override
public boolean isIn(String ipAddress) {
if (ipAddress == null || addressList == null) {
return false;
}
return addressList.includes(ipAddress);
} | @Test
public void testNullIP() throws IOException {
String[] ips = {"10.119.103.112", "10.221.102.0/23"};
createFileWithEntries ("ips.txt", ips);
IPList ipList = new FileBasedIPList("ips.txt");
assertFalse ("Null Ip is in the list",
ipList.isIn(null));
} |
public boolean hasConfig(String resource) {
if (resource == null) {
return false;
}
return !getRules(resource).isEmpty();
} | @Test
public void testHasConfig() {
// Setup
final Map<String, List<FlowRule>> rulesMap = generateFlowRules(true);
// Run the test and verify the results
ruleManager.updateRules(rulesMap);
assertTrue(ruleManager.hasConfig("rule1"));
assertFalse(ruleManager.hasConfig(... |
@Override
protected String ruleHandler() {
return "";
} | @Test
public void testRuleHandler() {
assertEquals(StringUtils.EMPTY, shenyuClientRegisterTarsService.ruleHandler());
} |
public AnnotatedLargeText obtainLog() {
WeakReference<AnnotatedLargeText> l = log;
if (l == null) return null;
return l.get();
} | @Test
public void annotatedText() throws Exception {
MyTaskAction action = new MyTaskAction();
action.start();
AnnotatedLargeText annotatedText = action.obtainLog();
while (!annotatedText.isComplete()) {
Thread.sleep(10);
}
ByteArrayOutputStream os = new B... |
public static String getUnresolvedSchemaName(final Schema schema) {
if (!isUnresolvedSchema(schema)) {
throw new IllegalArgumentException("Not a unresolved schema: " + schema);
}
return schema.getProp(UR_SCHEMA_ATTR);
} | @Test(expected = IllegalArgumentException.class)
public void testIsUnresolvedSchemaError2() {
// No "UnresolvedSchema" property
Schema s = SchemaBuilder.record("R").prop("org.apache.avro.idl.unresolved.name", "x").fields().endRecord();
SchemaResolver.getUnresolvedSchemaName(s);
} |
public static int pageSize() {
return PAGE_SIZE;
} | @Test
public void test_pageSize() {
assertEquals(UnsafeLocator.UNSAFE.pageSize(), OS.pageSize());
} |
@Deprecated
@Override
public AuthData authenticate(AuthData authData) throws AuthenticationException {
// This method is not expected to be called and is subject to removal.
throw new AuthenticationException("Not supported");
} | @SuppressWarnings("deprecation")
@Test
void authenticateShouldThrowNotImplementedException() {
AuthenticationStateOpenID state = new AuthenticationStateOpenID(null, null, null);
try {
state.authenticate(null);
fail("Expected AuthenticationException to be thrown");
... |
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
this.status = FactMappingValueStatus.FAILED_WITH_EXCEPTION;
} | @Test
public void setExceptionMessage() {
String exceptionValue = "Exception";
value.setExceptionMessage(exceptionValue);
assertThat(value.getStatus()).isEqualTo(FactMappingValueStatus.FAILED_WITH_EXCEPTION);
assertThat(value.getExceptionMessage()).isEqualTo(excepti... |
@Override
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch) {
return offsetsForTimes(timestampsToSearch, Duration.ofMillis(defaultApiTimeoutMs));
} | @Test
public void testOffsetsForTimesOnNullPartitions() {
consumer = newConsumer();
assertThrows(NullPointerException.class, () -> consumer.offsetsForTimes(null,
Duration.ofMillis(1)));
} |
public boolean hasReadPermissionForWholeCollection(final Subject subject,
final String collection) {
return readPermissionForCollection(collection)
.map(rp -> rp.equals(DbEntity.ALL_ALLOWED) || subject.isPermitted(rp + ":*"))
... | @Test
void hasReadPermissionForWholeCollectionReturnsFalseWhenSubjectMissesPermission() {
doReturn(Optional.of(
new DbEntityCatalogEntry("streams", "title", StreamImpl.class, "streams:read"))
).when(catalog)
.getByCollectionName("streams");
doReturn(false).wh... |
public static void readFully(InputStream stream, byte[] bytes, int offset, int length)
throws IOException {
int bytesRead = readRemaining(stream, bytes, offset, length);
if (bytesRead < length) {
throw new EOFException(
"Reached the end of stream with " + (length - bytesRead) + " bytes lef... | @Test
public void testReadFullySmallReadsWithStartAndLength() throws IOException {
byte[] buffer = new byte[10];
MockInputStream stream = new MockInputStream(2, 2, 3);
IOUtil.readFully(stream, buffer, 2, 5);
assertThat(Arrays.copyOfRange(buffer, 2, 7))
.as("Byte array contents should match")... |
@Override
public void writeMine(NodeHealth nodeHealth) {
requireNonNull(nodeHealth, "nodeHealth can't be null");
Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap();
if (LOG.isTraceEnabled()) {
LOG.trace("Reading {} and adding {}", new HashMap<>(sqHealthState), nodeHealth);
}
... | @Test
public void write_fails_with_NPE_if_arg_is_null() {
assertThatThrownBy(() -> underTest.writeMine(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("nodeHealth can't be null");
} |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeMetadataColumns() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.columnByMetadata("two", DataTypes.INT(), false)
.columnByExpression("c", "ABS(two)")
... |
@Override
public void onEvent(Event event) {
if (EnvUtil.getStandaloneMode()) {
return;
}
if (event instanceof ClientEvent.ClientVerifyFailedEvent) {
syncToVerifyFailedServer((ClientEvent.ClientVerifyFailedEvent) event);
} else {
syncToAllServer((C... | @Test
void testOnClientDisconnectEventSuccess() {
distroClientDataProcessor.onEvent(new ClientEvent.ClientDisconnectEvent(client, true));
verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong());
verify(distroProtocol).sync(any(), eq(DataOperation.DELETE));
} |
@Override
public String name() {
return name;
} | @Test
public void testSetNamespaceOwnershipNoop() throws TException, IOException {
setNamespaceOwnershipAndVerify(
"set_ownership_noop_1",
ImmutableMap.of(HiveCatalog.HMS_DB_OWNER, "some_individual_owner"),
ImmutableMap.of(
HiveCatalog.HMS_DB_OWNER,
"some_individual... |
@Override
public <T> List<SearchResult<T>> search(SearchRequest request, Class<T> typeFilter) {
SearchSession<T> session = new SearchSession<>(request, Collections.singleton(typeFilter));
if (request.inParallel()) {
ForkJoinPool commonPool = ForkJoinPool.commonPool();
getPro... | @Test
public void testUniqueNode() {
GraphGenerator generator = GraphGenerator.build().generateTinyGraph();
generator.getGraph().getNode(GraphGenerator.FIRST_NODE).setLabel(GraphGenerator.FIRST_NODE);
SearchRequest request = buildRequest(GraphGenerator.FIRST_NODE, generator);
Colle... |
public DoubleArrayAsIterable usingExactEquality() {
return new DoubleArrayAsIterable(EXACT_EQUALITY_CORRESPONDENCE, iterableSubject());
} | @Test
public void usingExactEquality_contains_successWithNaN() {
assertThat(array(1.1, NaN, 3.3)).usingExactEquality().contains(NaN);
} |
@Override
@PublicAPI(usage = ACCESS)
public boolean isAnnotatedWith(Class<? extends Annotation> annotationType) {
return isAnnotatedWith(annotationType.getName());
} | @Test
public void isAnnotatedWith_type_on_resolved_target() {
JavaCall<?> call = simulateCall().from(Origin.class, "call").to(Target.class, "called");
assertThat(call.getTarget().isAnnotatedWith(QueriedAnnotation.class))
.as("target is annotated with @" + QueriedAnnotation.class.get... |
@Override
public TokenIdent cancelToken(Token<TokenIdent> token,
String canceller) throws IOException {
ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier());
DataInputStream in = new DataInputStream(buf);
TokenIdent id = createIdentifier();
id.readFields(in);
syncLocal... | @SuppressWarnings("unchecked")
@Test
public void testCancelTokenSingleManager() throws Exception {
for (int i = 0; i < TEST_RETRIES; i++) {
DelegationTokenManager tm1 = null;
String connectString = zkServer.getConnectString();
Configuration conf = getSecretConf(connectString);
tm1 = new ... |
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline p = socketChannel.pipeline();
p.addLast(new HttpRequestDecoder());
p.addLast(new HttpObjectAggregator(1024 * 1024));
p.addLast(new HttpResponseEncoder());
p.addLast(new Http... | @Test
public void testInitChannel() throws Exception {
// Mock Objects
HttpServerInitializer httpServerInitializer = mock(HttpServerInitializer.class);
SocketChannel socketChannel = mock(SocketChannel.class);
ChannelPipeline channelPipeline = mock(ChannelPipeline.class);
// ... |
@Override
public boolean matchesType(Type t) {
if (t.isPseudoType()) {
return t.matchesType(this);
}
if (!t.isStructType()) {
return false;
}
StructType rhsType = (StructType) t;
if (fields.size() != rhsType.fields.size()) {
return... | @Test
public void testStructMatchType() throws Exception {
// "struct<struct_test:int,c1:struct<c1:int,cc1:string>>"
StructType c1 = new StructType(Lists.newArrayList(
new StructField("c1", ScalarType.createType(PrimitiveType.INT)),
new StructField("cc1", ScalarType.c... |
@Override
public List<TransferItem> normalize(final List<TransferItem> roots) {
final List<TransferItem> normalized = new ArrayList<>();
for(TransferItem upload : roots) {
boolean duplicate = false;
for(Iterator<TransferItem> iter = normalized.iterator(); iter.hasNext(); ) {
... | @Test
public void testNormalize() {
UploadRootPathsNormalizer n = new UploadRootPathsNormalizer();
final List<TransferItem> list = new ArrayList<>();
list.add(new TransferItem(new Path("/a", EnumSet.of(Path.Type.directory)), new NullLocal(System.getProperty("java.io.tmpdir"), "a") {
... |
public static void checkState(boolean isValid, String message) throws IllegalStateException {
if (!isValid) {
throw new IllegalStateException(message);
}
} | @Test
public void testCheckState() {
try {
Preconditions.checkState(true, "Test message: %s %s", 12, null);
} catch (IllegalStateException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkState(false, "Test message: %s %s", 12, null);
... |
@Override
protected double maintain() {
if (!nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0; // Not relevant in zones with static capacity
if (nodeRepository().zone().environment().isTest()) return 1.0; // Short-lived deployments
if (!nodeRepository().nodes().isWorking()) ... | @Test
public void maintain() {
String flavor0 = "host";
String flavor1 = "host2";
NodeFlavors flavors = FlavorConfigBuilder.createDummies(flavor0, flavor1);
MockHostProvisioner hostProvisioner = new MockHostProvisioner(flavors.getFlavors());
ProvisioningTester tester = new Pr... |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
for (String pool : POOLS) {
for (int i = 0; i < ATTRIBUTES.length; i++) {
final String attribute = ATTRIBUTES[i];
final String name = NAMES[i];
... | @Test
public void includesGaugesForDirectAndMappedPools() {
assertThat(buffers.getMetrics().keySet())
.containsOnly("direct.count",
"mapped.used",
"mapped.capacity",
"direct.capacity",
"mapped.cou... |
@SuppressWarnings("unchecked")
public void isEquivalentAccordingToCompareTo(@Nullable T expected) {
if (checkNotNull((Comparable<Object>) actual).compareTo(checkNotNull(expected)) != 0) {
failWithActual("expected value that sorts equal to", expected);
}
} | @Test
public void isEquivalentAccordingToCompareTo() {
assertThat(new StringComparedByLength("abc"))
.isEquivalentAccordingToCompareTo(new StringComparedByLength("xyz"));
expectFailureWhenTestingThat(new StringComparedByLength("abc"))
.isEquivalentAccordingToCompareTo(new StringComparedByLeng... |
public static MetadataCoder of() {
return INSTANCE;
} | @Test
public void testEncodeDecodeWithDefaultLastModifiedMills() throws Exception {
Path filePath = tmpFolder.newFile("somefile").toPath();
Metadata metadata =
Metadata.builder()
.setResourceId(
FileSystems.matchNewResource(filePath.toString(), false /* isDirectory */))
... |
final boolean consumeBytes(int streamId, int bytes) throws Http2Exception {
Http2Stream stream = connection().stream(streamId);
// Upgraded requests are ineligible for stream control. We add the null check
// in case the stream has been deregistered.
if (stream != null && streamId == Htt... | @Test
public void flowControlShouldBeResilientToMissingStreams() throws Http2Exception {
Http2Connection conn = new DefaultHttp2Connection(true);
Http2ConnectionEncoder enc = new DefaultHttp2ConnectionEncoder(conn, new DefaultHttp2FrameWriter());
Http2ConnectionDecoder dec = new DefaultHttp2... |
@Override
public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback) throws BackgroundException {
if(containerService.isContainer(source)) {
if(new SimplePathPredicate(sourc... | @Test
public void testMoveToDifferentParentAndRename() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.direc... |
public static VerificationMode between(final int min, final int max) {
checkArgument(min >= 0, "Min should be greater than or equal to 0");
checkArgument(max > min, "Max should be greater than min");
return new BetweenVerification(min, max);
} | @Test
public void should_verify_expected_request_for_between() throws Exception {
final HttpServer server = httpServer(port(), hit);
server.get(by(uri("/foo"))).response("bar");
running(server, () -> {
assertThat(helper.get(remoteUrl("/foo")), is("bar"));
assertThat(... |
@VisibleForTesting
@SuppressWarnings("deprecation")
public static boolean isOnlyDictionaryEncodingPages(ColumnChunkMetaData columnMetaData)
{
// Files written with newer versions of Parquet libraries (e.g. parquet-mr 1.9.0) will have EncodingStats available
// Otherwise, fallback to v1 logic... | @Test
@SuppressWarnings("deprecation")
public void testDictionaryEncodingV2()
{
assertTrue(isOnlyDictionaryEncodingPages(createColumnMetaDataV2(RLE_DICTIONARY)));
assertTrue(isOnlyDictionaryEncodingPages(createColumnMetaDataV2(PLAIN_DICTIONARY)));
assertFalse(isOnlyDictionaryEncoding... |
public static Optional<Constructor<?>> findConstructor(Class<?> clazz, Class<?>[] paramsTypes) {
if (clazz == null) {
return Optional.empty();
}
// Add to constructor cache
return CONSTRUCTOR_CACHE.computeIfAbsent(buildMethodKey(clazz, "<init>", paramsTypes), key -> {
... | @Test
public void findConstructor() {
final Optional<Constructor<?>> constructor = ReflectUtils.findConstructor(TestReflect.class, null);
Assert.assertTrue(constructor.isPresent());
final Optional<Constructor<?>> paramsCons = ReflectUtils.findConstructor(TestReflect.class,
ne... |
public List<Exception> errors() {
return Collections.unmodifiableList(this.errors);
} | @Test
void errors() {
final var e = new BusinessException("unhandled");
final var retry = new Retry<String>(
() -> {
throw e;
},
2,
0
);
try {
retry.perform();
} catch (BusinessException ex) {
//ignore
}
assertThat(retry.errors(), hasI... |
@Override
public EurekaHttpClient newClient(EurekaEndpoint endpoint) {
// we want a copy to modify. Don't change the original
WebClient.Builder builder = this.builderSupplier.get().clone();
setUrl(builder, endpoint.getServiceUrl());
setCodecs(builder);
builder.filter(http4XxErrorExchangeFilterFunction());
... | @Test
void testUserInfoWithEncodedCharacters() {
String encodedBasicAuth = HttpHeaders.encodeBasicAuth("test", "MyPassword@", null);
String expectedAuthHeader = "Basic " + encodedBasicAuth;
String expectedUrl = "http://localhost:8761";
WebClientEurekaHttpClient client = (WebClientEurekaHttpClient) transportCl... |
@Override
protected Mono<Void> handleRuleIfNull(final String pluginName, final ServerWebExchange exchange, final ShenyuPluginChain chain) {
return WebFluxResultUtils.noRuleResult(pluginName, exchange);
} | @Test
public void handleRuleIfNullTest() {
assertNotNull(dividePlugin.handleRuleIfNull(PluginEnum.DIVIDE.getName(), exchange, chain));
} |
public static SocketAddress updatePort(@Nullable Supplier<? extends SocketAddress> address, int port) {
if (address == null) {
return createUnresolved(NetUtil.LOCALHOST.getHostAddress(), port);
}
SocketAddress socketAddress = address.get();
if (socketAddress instanceof DomainSocketAddress) {
throw new Il... | @Test
void updatePortBadValues() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> AddressUtils.updatePort(null, -1))
.withMessage("port out of range:-1");
} |
public RunList<R> byTimestamp(final long start, final long end) {
return
limit(new CountingPredicate<>() {
@Override
public boolean apply(int index, R r) {
return start <= r.getTimeInMillis();
}
}).filter((Predicate<R>) r -> r.getTimeInMillis()... | @Test
public void byTimestampAllRuns() {
setUpByTimestampRuns();
RunList<Run> tested = rlist.byTimestamp(0, 400);
assertEquals(2, tested.toArray().length);
} |
@NonNull
public Data toData() {
return new Data(buffer.toByteArray());
} | @Test
public void toData() {
final DataStream stream = new DataStream();
stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6});
final Data data = stream.toData();
assertEquals(0x100, Objects.requireNonNull(data.getIntValue(Data.FORMAT_UINT16_LE, 0)).intValue());
} |
public static void run(String resolverPath,
String optionalDefault,
String typeRefPropertiesExcludeList,
boolean overrideNamespace,
String targetDirectoryPath,
String[] sources) throws IOExceptio... | @Test(dataProvider = "toAvroSchemaData")
public void testFullNameAsArgsWithJarInPath(Map<String, String> testSchemas, Map<String, String> expectedAvroSchemas, List<String> paths, boolean override) throws IOException
{
Map<File, Map.Entry<String,String>> files = TestUtil.createSchemaFiles(_testDir, testSchemas,... |
public void updateContextPath() {
if (StringUtils.isNoneBlank(this.path)) {
this.contextPath = StringUtils.indexOf(path, "/", 1) > -1
? this.path.substring(0, StringUtils.indexOf(path, "/", 1)) : path;
}
} | @Test
public void testUpdateContextPath() {
MetaData metaData = new MetaData("id", "appName", "contextPath", "path", "rpcType",
"serviceName", "methodName", "parameterTypes", "rpcExt", true);
metaData.setPath(PATH);
metaData.updateContextPath();
assertEquals(metaData.... |
@Override
public Map<K, V> getAll(Set<K> keys) {
Map<K, V> result = createHashMap(keys.size());
for (K key : keys) {
result.put(key, map.get(key));
}
return result;
} | @Test
public void testGetAll() {
map.put(23, "value-23");
map.put(42, "value-42");
Map<Integer, String> expectedResult = new HashMap<>();
expectedResult.put(23, "value-23");
expectedResult.put(42, "value-42");
Map<Integer, String> result = adapter.getAll(expectedRes... |
public static LatLong interpolateLatLong(LatLong p1, LatLong p2, double fraction) {
double maxLat = max(p1.latitude(), p2.latitude());
double minLat = min(p1.latitude(), p2.latitude());
checkArgument(maxLat - minLat <= 90.0, "Interpolation is unsafe at this distance (latitude)");
doubl... | @Test
public void testUnsafeInterpolateLatLongFails() {
LatLong p1 = new LatLong(89.0, 0.0);
LatLong p2 = new LatLong(-89.0, 0.0);
try {
interpolateLatLong(p1, p2, 0.5);
fail("This call should fail until the implementation is improved");
} catch (IllegalArgu... |
@Override
public List<IncomingMessage> pull(
long requestTimeMsSinceEpoch,
SubscriptionPath subscription,
int batchSize,
boolean returnImmediately)
throws IOException {
PullRequest request =
PullRequest.newBuilder()
.setSubscription(subscription.getPath())
... | @Test
public void pullOneMessage() throws IOException {
initializeClient(null, null);
String expectedSubscription = SUBSCRIPTION.getPath();
final PullRequest expectedRequest =
PullRequest.newBuilder()
.setSubscription(expectedSubscription)
.setReturnImmediately(true)
... |
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new NacosSerializationException(obj.getClass(), e);
}
} | @Test
void testToJson2() {
assertThrows(NacosSerializationException.class, () -> {
// object without field will throw exceptions
JacksonUtils.toJson(new Object());
});
} |
public static String getLocalMacAddress() {
return getMacAddress(getLocalhost());
} | @Test
@Disabled
public void getLocalMacAddressTest() {
final String macAddress = NetUtil.getLocalMacAddress();
assertNotNull(macAddress);
// 验证MAC地址正确
final boolean match = ReUtil.isMatch(PatternPool.MAC_ADDRESS, macAddress);
assertTrue(match);
} |
@Override
public V put(K key, V value) {
// will throw UnsupportedOperationException; delegate anyway for testability
return underlying().put(key, value);
} | @Test
public void testDelegationOfUnsupportedFunctionPut() {
new PCollectionsHashMapWrapperDelegationChecker<>()
.defineMockConfigurationForUnsupportedFunction(mock -> mock.put(eq(this), eq(this)))
.defineWrapperUnsupportedFunctionInvocation(wrapper -> wrapper.put(this, this))
... |
@Override
public Set<Long> calculateUsers(DelegateExecution execution, String param) {
Set<Long> groupIds = StrUtils.splitToLongSet(param);
List<BpmUserGroupDO> groups = userGroupService.getUserGroupList(groupIds);
return convertSetByFlatMap(groups, BpmUserGroupDO::getUserIds, Collection::st... | @Test
public void testCalculateUsers() {
// 准备参数
String param = "1,2";
// mock 方法
BpmUserGroupDO userGroup1 = randomPojo(BpmUserGroupDO.class, o -> o.setUserIds(asSet(11L, 12L)));
BpmUserGroupDO userGroup2 = randomPojo(BpmUserGroupDO.class, o -> o.setUserIds(asSet(21L, 22L)))... |
Bootstrap getBootstrap() {
return bootstrap;
} | @Test
void testSetKeepaliveOptionWithEpoll() throws Exception {
assumeThat(Epoll.isAvailable()).isTrue();
final Configuration config = new Configuration();
config.set(NettyShuffleEnvironmentOptions.TRANSPORT_TYPE, "epoll");
config.set(NettyShuffleEnvironmentOptions.CLIENT_TCP_KEEP_I... |
@Override
public void upgrade() {
if (hasBeenRunSuccessfully()) {
LOG.debug("Migration already completed.");
return;
}
final Set<String> dashboardIdToViewId = new HashSet<>();
final Consumer<String> recordMigratedDashboardIds = dashboardIdToViewId::add;
... | @Test
@MongoDBFixtures("dashboard_with_no_widget_positions.json")
public void migratesADashboardWithNoWidgetPositions() {
this.migration.upgrade();
final MigrationCompleted migrationCompleted = captureMigrationCompleted();
assertThat(migrationCompleted.migratedDashboardIds()).containsEx... |
public static LookupDefaultMultiValue create(String valueString, LookupDefaultValue.Type valueType) {
requireNonNull(valueString, "valueString cannot be null");
requireNonNull(valueType, "valueType cannot be null");
Map<Object, Object> value;
try {
switch (valueType) {
... | @Test
public void createSingleString() throws Exception {
expectedException.expect(IllegalArgumentException.class);
LookupDefaultMultiValue.create("foo", LookupDefaultMultiValue.Type.STRING);
} |
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updatePort(@PathParam("id") String id, InputStream input) throws IOException {
log.trace(String.format(MESSAGE, "UPDATE " + id));
String inputStr = IOUtils.toString(input, REST... | @Test
public void testUpdatePortWithUpdatingOperation() {
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
mockOpenstackNetworkAdminService.updatePort(anyObject());
replay(mockOpenstackNetworkAdminService);
final WebTarget... |
@Override
public boolean equals(Object other) {
if (!(other instanceof Tenant)) {
return false;
}
Tenant that = (Tenant) other;
return name.equals(that.name);
} | @Test
public void equals() {
assertEquals(t1, t2);
assertNotEquals(t1, t3);
assertNotEquals(t1, t4);
assertNotEquals(t3, t4);
} |
public static String namespaceFilePrefix(String namespace) {
return String.format(PREFIX_FORMAT_NAMESPACE_FILE, namespace.replace(".", "/"));
} | @Test
void shouldGetNamespaceFilePrefix() {
assertThat(StorageContext.namespaceFilePrefix("io.namespace"), is("/io/namespace/_files"));
} |
public static byte[] getValue(byte[] raw) {
try (final Asn1InputStream is = new Asn1InputStream(raw)) {
is.readTag();
return is.read(is.readLength());
}
} | @Test
public void getValueShouldSkipTagAndExtendedLength() {
final byte[] data = new byte[0x81];
new SecureRandom().nextBytes(data);
final byte[] obj = Arrays.concatenate(new byte[] { 0x10, (byte) 0x81, (byte) 0x81 }, data);
assertArrayEquals(data, Asn1Utils.getValue(obj));
} |
@Override
public void setConf(Configuration conf) {
this.conf = conf;
uid = conf.getInt(UID, 0);
user = conf.get(USER);
if (null == user) {
try {
user = UserGroupInformation.getCurrentUser().getShortUserName();
} catch (IOException e) {
user = "hadoop";
}
}
gi... | @Test(expected=IllegalStateException.class)
public void testDuplicateIds() {
Configuration conf = new Configuration(false);
conf.setInt(SingleUGIResolver.UID, 4344);
conf.setInt(SingleUGIResolver.GID, 4344);
conf.set(SingleUGIResolver.USER, TESTUSER);
conf.set(SingleUGIResolver.GROUP, TESTGROUP);
... |
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());
... | @SuppressWarnings("unchecked")
@Test
public void testCollidingSimpleAlias() {
SortedSet<PluginDesc<Converter>> converters = new TreeSet<>();
converters.add(new PluginDesc<>(CollidingConverter.class, null, PluginType.CONVERTER, CollidingConverter.class.getClassLoader()));
SortedSet<Plugin... |
@Override
public Map<String, String> getAllVariables() {
return internalGetAllVariables(0, Collections.emptySet());
} | @Test
void testGetAllVariables() throws Exception {
MetricRegistryImpl registry =
new MetricRegistryImpl(
MetricRegistryTestUtils.defaultMetricRegistryConfiguration());
AbstractMetricGroup group =
new AbstractMetricGroup<AbstractMetricGroup<?>... |
public static RelDataType toCalciteRowType(Schema schema, RelDataTypeFactory dataTypeFactory) {
RelDataTypeFactory.Builder builder = new RelDataTypeFactory.Builder(dataTypeFactory);
IntStream.range(0, schema.getFieldCount())
.forEach(
idx ->
builder.add(
... | @Test
public void testToCalciteRowType() {
final Schema schema =
Schema.builder()
.addField("f1", Schema.FieldType.BYTE)
.addField("f2", Schema.FieldType.INT16)
.addField("f3", Schema.FieldType.INT32)
.addField("f4", Schema.FieldType.INT64)
.addF... |
@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);
} |
@Bean("ScmChangedFiles")
public ScmChangedFiles provide(ScmConfiguration scmConfiguration, BranchConfiguration branchConfiguration, DefaultInputProject project) {
Path rootBaseDir = project.getBaseDir();
Set<ChangedFile> changedFiles = loadChangedFilesIfNeeded(scmConfiguration, branchConfiguration, rootBaseDi... | @Test
public void testGitScmProvider(){
GitScmProvider gitScmProvider = mock(GitScmProvider.class);
when(scmConfiguration.provider()).thenReturn(gitScmProvider);
when(branchConfiguration.isPullRequest()).thenReturn(true);
when(branchConfiguration.targetBranchName()).thenReturn("target");
ScmChan... |
private Function<KsqlConfig, Kudf> getUdfFactory(
final Method method,
final UdfDescription udfDescriptionAnnotation,
final String functionName,
final FunctionInvoker invoker,
final String sensorName
) {
return ksqlConfig -> {
final Object actualUdf = FunctionLoaderUtils.instan... | @Test
public void shouldLoadFunctionWithSchemaProvider() {
// Given:
final UdfFactory returnDecimal = FUNC_REG.getUdfFactory(FunctionName.of("returndecimal"));
// When:
final SqlDecimal decimal = SqlTypes.decimal(2, 1);
final List<SqlArgument> args = Collections.singletonList(SqlArgument.of(decim... |
@Override
public SuspensionReasons verifyGroupGoingDownIsFine(ClusterApi clusterApi) throws HostStateChangeDeniedException {
return verifyGroupGoingDownIsFine(clusterApi, false);
} | @Test
public void verifyGroupGoingDownIsFine_noServicesOutsideGroupIsDownIsFine() throws HostStateChangeDeniedException {
verifyGroupGoingDownIsFine(true, Optional.empty(), 13, true);
} |
public long getLastModified() {
return last_modified;
} | @Test
public void getLastModified() {
assertEquals(TestParameters.VP_LAST_MODIFIED, chmItsfHeader.getLastModified());
} |
@Override
public void loadConfiguration(NacosLoggingProperties loggingProperties) {
String location = loggingProperties.getLocation();
configurator.setLoggingProperties(loggingProperties);
LoggerContext loggerContext = loadConfigurationOnStart(location);
if (hasNoListener(loggerConte... | @Test
void testLoadConfigurationReload() {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.putObject(CoreConstants.RECONFIGURE_ON_CHANGE_TASK, new ReconfigureOnChangeTask());
logbackNacosLoggingAdapter.loadConfiguration(loggingProperties);
... |
public static ExpressionTree parseFilterTree(String filter) throws MetaException {
return PartFilterParser.parseFilter(filter);
} | @Test
public void testParseFilterWithInvalidDateWithoutTypeNorQuoted() {
MetaException exception = assertThrows(MetaException.class,
() -> PartFilterExprUtil.parseFilterTree("(j = 2023-06-32)"));
assertTrue(exception.getMessage().contains("Error parsing partition filter"));
} |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public void updateTenantPackage(TenantPackageSaveReqVO updateReqVO) {
// 校验存在
TenantPackageDO tenantPackage = validateTenantPackageExists(updateReqVO.getId());
// 更新
TenantPackageDO updateObj = BeanUtils.toBea... | @Test
public void testUpdateTenantPackage_notExists() {
// 准备参数
TenantPackageSaveReqVO reqVO = randomPojo(TenantPackageSaveReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> tenantPackageService.updateTenantPackage(reqVO), TENANT_PACKAGE_NOT_EXISTS);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.