focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean persistent() {
return store.persistent();
} | @Test
public void shouldReturnPersistentForVersionedStore() {
givenWrapperWithVersionedStore();
// test "persistent = true"
when(versionedStore.persistent()).thenReturn(true);
assertThat(wrapper.persistent(), equalTo(true));
// test "persistent = false"
when(version... |
@Override
public OptionalLong apply(OptionalLong previousSendTimeNs) {
long delayNs;
if (previousGlobalFailures > 0) {
// If there were global failures (like a response timeout), we want to wait for the
// full backoff period.
delayNs = backoff.backoff(previousGlo... | @Test
public void applyAfterDispatchIntervalWithExistingEarlierDeadline() {
assertEquals(OptionalLong.of(BACKOFF.initialInterval() / 2),
new AssignmentsManagerDeadlineFunction(BACKOFF, 0, 0, false, 12).
apply(OptionalLong.of(BACKOFF.initialInterval() / 2)));
} |
public String redirectWithCorrectAttributesForAd(HttpServletRequest httpRequest, AuthenticationRequest authenticationRequest) throws UnsupportedEncodingException, SamlSessionException {
SamlSession samlSession = authenticationRequest.getSamlSession();
if (samlSession.getValidationStatus() != null && sa... | @Test
public void redirectWithCorrectAttributesForAdTest() throws UnsupportedEncodingException, SamlSessionException {
AuthenticationRequest authenticationRequest = new AuthenticationRequest();
authenticationRequest.setRequest(httpServletRequestMock);
SamlSession samlSession = new SamlSessio... |
public static GlobalConfig readConfig() throws IOException, InvalidGlobalConfigException {
return readConfig(getConfigDir());
} | @Test
public void testReadConfig_emptyFile() throws IOException {
temporaryFolder.newFile("config.json");
IOException exception =
assertThrows(IOException.class, () -> GlobalConfig.readConfig(configDir));
assertThat(exception)
.hasMessageThat()
.startsWith(
"Failed to c... |
Dependency newDependency(MavenProject prj) {
final File pom = new File(prj.getBasedir(), "pom.xml");
if (pom.isFile()) {
getLog().debug("Adding virtual dependency from pom.xml");
return new Dependency(pom, true);
} else if (prj.getFile().isFile()) {
getLog().... | @Test
public void should_newDependency_get_pom_from_base_dir() {
// Given
BaseDependencyCheckMojo instance = new BaseDependencyCheckMojoImpl();
new MockUp<MavenProject>() {
@Mock
public File getBasedir() {
return new File("src/test/resources/maven_pro... |
public void createUser(String username, String password, String realm, Encryption encryption, List<String> userGroups, List<String> algorithms) {
if (users.containsKey(username)) {
throw MSG.userToolUserExists(username);
}
realm = checkRealm(realm);
users.put(username, Encryption.CLEAR.... | @Test
public void testUserToolEncrypted() throws Exception {
UserTool userTool = new UserTool(serverDirectory.getAbsolutePath());
userTool.createUser("user", "password", UserTool.DEFAULT_REALM_NAME, UserTool.Encryption.ENCRYPTED, Collections.singletonList("admin"), null);
Properties users = loadPro... |
public static void main(String[] args) {
// Square frame buffer
Parameters.SQUARE_FRAME_BUFFER = false;
HillsRenderConfig hillsCfg = null;
File demFolder = getDemFolder(args);
if (demFolder != null) {
MemoryCachingHgtReaderTileSource tileSource = new MemoryCachingHgt... | @Test
public void mainTest() {
String[] args = new String[]{};
verifyInvalidArguments(args);
/*args = new String[]{"file/not/found.map"};
verifyInvalidArguments(args);*/
} |
public JsonNode resolve(JsonNode tree, String path, String refFragmentPathDelimiters) {
return resolve(tree, new ArrayList<>(asList(split(path, refFragmentPathDelimiters))));
} | @Test
public void hashResolvesToRoot() {
ObjectNode root = new ObjectMapper().createObjectNode();
root.set("child1", root.objectNode());
root.set("child2", root.objectNode());
root.set("child3", root.objectNode());
assertThat((ObjectNode) resolver.resolve(root, "#", "#/.")... |
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof CounterCell) {
CounterCell counterCell = (CounterCell) object;
return Objects.equals(dirty, counterCell.dirty)
&& value.get() == counterCell.value.get()
&& Objects.equals(name, counterCell.name);
}... | @Test
public void testEquals() {
CounterCell counterCell = new CounterCell(MetricName.named("namespace", "name"));
CounterCell equal = new CounterCell(MetricName.named("namespace", "name"));
Assert.assertEquals(counterCell, equal);
Assert.assertEquals(counterCell.hashCode(), equal.hashCode());
} |
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 shouldAllowClassesWithSameFQCNInDifferentUDFJars() throws Exception {
final File pluginDir = tempFolder.newFolder();
Files.copy(Paths.get("src/test/resources/udf-example.jar"),
new File(pluginDir, "udf-example.jar").toPath());
Files.copy(Paths.get("src/test/resources/udf-isolated... |
public static synchronized TransformServiceLauncher forProject(
@Nullable String projectName, int port, @Nullable String pythonRequirementsFile)
throws IOException {
if (projectName == null || projectName.isEmpty()) {
projectName = DEFAULT_PROJECT_NAME;
}
if (!launchers.containsKey(project... | @Test
public void testLauncherInstallsLocalDependencies() throws IOException {
String projectName = UUID.randomUUID().toString();
Path expectedTempDir = Paths.get(System.getProperty("java.io.tmpdir"), projectName);
File file = expectedTempDir.toFile();
file.deleteOnExit();
String dependency1FileN... |
static FEELFnResult<Boolean> matchFunctionWithFlags(String input, String pattern, String flags) {
log.debug("Input: {} , Pattern: {}, Flags: {}", input, pattern, flags);
if ( input == null ) {
throw new InvalidParameterException("input");
}
if ( pattern == null ) {
... | @Test
void invokeNull() {
assertThrows(InvalidParameterException.class, () -> MatchesFunction.matchFunctionWithFlags(null, null, null));
assertThrows(InvalidParameterException.class, () -> MatchesFunction.matchFunctionWithFlags(null, "test",null));
assertThrows(InvalidParameterException.clas... |
@Override
public Repository getRepository() {
//Repository may be null if executing remotely in Pentaho Server
Repository repository = super.getRepository();
return repository != null ? repository : getTransMeta().getRepository();
} | @Test
public void getRepositoryNullTest() {
metaInject.getRepository();
//If repository is not set in the base step (Remote Executions/Scheduling) Need to get the repository from TransMeta
verify( metaInject, times( 1 ) ).getTransMeta();
} |
public Query generateChecksumQuery(QualifiedName tableName, List<Column> columns, Optional<Expression> partitionPredicate)
{
ImmutableList.Builder<SelectItem> selectItems = ImmutableList.builder();
selectItems.add(new SingleColumn(new FunctionCall(QualifiedName.of("count"), ImmutableList.of())));
... | @Test
public void testChecksumQuery()
{
Query checksumQuery = checksumValidator.generateChecksumQuery(
QualifiedName.of("test:di"),
ImmutableList.of(
BIGINT_COLUMN,
VARCHAR_COLUMN,
DOUBLE_COLUMN,
... |
Plugin create(Options.Plugin plugin) {
try {
return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument());
} catch (IOException | URISyntaxException e) {
throw new CucumberException(e);
}
} | @Test
void instantiates_pretty_plugin_with_file_arg() throws IOException {
PluginOption option = parse("pretty:" + tmp.resolve("out.txt").toUri().toURL());
plugin = fc.create(option);
assertThat(plugin.getClass(), is(equalTo(PrettyFormatter.class)));
} |
@Entrance
public final void combine(@SourceFrom long count) {
if (count > this.value) {
this.value = count;
}
} | @Test
public void testSelfCombine() {
MaxLongMetricsImpl impl = new MaxLongMetricsImpl();
impl.combine(10);
impl.combine(5);
MaxLongMetricsImpl impl2 = new MaxLongMetricsImpl();
impl2.combine(2);
impl2.combine(6);
impl.combine(impl2);
Assertions.asse... |
@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 shouldThrowIfCanNotCoerceToBoolean() {
// Given:
final KsqlJsonDeserializer<Boolean> deserializer =
givenDeserializerForSchema(Schema.OPTIONAL_BOOLEAN_SCHEMA, Boolean.class);
final byte[] bytes = serializeJson(IntNode.valueOf(23));
// When:
final Exception e = assertTh... |
@Override
public void error(String msg) {
logger.error(msg);
} | @Test
public void testErrorWithException() {
Logger mockLogger = mock(Logger.class);
when(mockLogger.getName()).thenReturn("foo");
InternalLogger logger = new Slf4JLogger(mockLogger);
logger.error("a", e);
verify(mockLogger).getName();
verify(mockLogger).error("a",... |
static void checkValidTableId(String idToCheck) {
if (idToCheck.length() < MIN_TABLE_ID_LENGTH) {
throw new IllegalArgumentException("Table ID cannot be empty. ");
}
if (idToCheck.length() > MAX_TABLE_ID_LENGTH) {
throw new IllegalArgumentException(
"Table ID "
+ idToChec... | @Test
public void testCheckValidTableIdWhenIdIsTooShort() {
assertThrows(IllegalArgumentException.class, () -> checkValidTableId(""));
} |
@Override
public ChannelStateWriteResult getAndRemoveWriteResult(long checkpointId) {
LOG.debug("{} requested write result, checkpoint {}", taskName, checkpointId);
ChannelStateWriteResult result = results.remove(checkpointId);
Preconditions.checkArgument(
result != null,
... | @Test
void testResultCompletion() throws IOException {
ChannelStateWriteResult result;
try (ChannelStateWriterImpl writer = openWriter()) {
callStart(writer);
result = writer.getAndRemoveWriteResult(CHECKPOINT_ID);
assertThat(result.resultSubpartitionStateHandles)... |
DateRange getRange(String dateRangeString) throws ParseException {
if (dateRangeString == null || dateRangeString.isEmpty())
return null;
String[] dateArr = dateRangeString.split("-");
if (dateArr.length > 2 || dateArr.length < 1)
return null;
// throw new Illega... | @Test
public void testParseSingleDateRange() throws ParseException {
DateRange dateRange = dateRangeParser.getRange("2014 Sep 1");
assertFalse(dateRange.isInRange(getCalendar(2014, Calendar.AUGUST, 31)));
assertTrue(dateRange.isInRange(getCalendar(2014, Calendar.SEPTEMBER, 1)));
asse... |
@Override
public void accept(Props props) {
if (isClusterEnabled(props)) {
checkClusterProperties(props);
}
} | @Test
@UseDataProvider("validIPv4andIPv6Addresses")
public void accept_throws_MessageException_on_application_node_if_default_jdbc_url(String host) {
TestAppSettings settings = newSettingsForAppNode(host);
settings.clearProperty(JDBC_URL.getKey());
ClusterSettings clusterSettings = new ClusterSettings(n... |
private synchronized boolean validateClientAcknowledgement(long h) {
if (h < 0) {
throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h);
}
if (h > MASK) {
throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa... | @Test
public void testValidateClientAcknowledgement_rollover_edgecase4_unsent() throws Exception
{
// Setup test fixture.
final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1;
final long h = 0;
final long oldH = MAX;
final Long lastUnackedX = null;
//... |
@Override
public UrlPattern doGetPattern() {
return UrlPattern.create(composeUrlPattern(SAML_VALIDATION_CONTROLLER, VALIDATION_CALLBACK_KEY));
} | @Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern().matches("/saml/validation")).isTrue();
assertThat(underTest.doGetPattern().matches("/saml/validation2")).isFalse();
assertThat(underTest.doGetPattern().matches("/api/saml/validation")).isFalse();
assertThat(underTest.doGetPattern... |
public abstract boolean compare(A actual, E expected); | @Test
public void testTransforming_actual_compare_nullActualValue() {
try {
HYPHEN_INDEXES.compare(null, 7);
fail("Expected NullPointerException to be thrown but wasn't");
} catch (NullPointerException expected) {
}
} |
public static <T extends Throwable> void checkNotNull(final Object reference, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (null == reference) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckNotNullToNotThrowException() {
assertDoesNotThrow(() -> ShardingSpherePreconditions.checkNotNull(new Object(), SQLException::new));
} |
@Override
public Connection getConnection() throws SQLException {
if (null == currentPhysicalConnection) {
currentPhysicalConnection = connection.getDatabaseConnectionManager().getRandomConnection();
}
return currentPhysicalConnection;
} | @Test
void assertGetConnection() throws SQLException {
assertThat(shardingSphereDatabaseMetaData.getConnection(), is(dataSource.getConnection()));
} |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnDuplicateFinderMethod() {
@RestLiCollection(name = "duplicateFinderMethod")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord>
{
@Finder(value = "duplicate")
public List<EmptyRecord> findThis(@Qu... |
@Override
public HttpResponseOutputStream<StorageObject> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final S3Object object = new S3WriteFeature(session, acl).getDetails(file, status);
// ID for the initiated multipart upload.
... | @Test
public void testWrite() throws Exception {
final S3MultipartWriteFeature feature = new S3MultipartWriteFeature(session, new S3AccessControlListFeature(session));
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Tra... |
public <T extends Output<T>> void save(Path csvPath, Dataset<T> dataset, String responseName) throws IOException {
save(csvPath, dataset, Collections.singleton(responseName));
} | @Test
public void testSaveEmpty() throws IOException {
MutableDataset<MockOutput> src = new MutableDataset<>(null, new MockOutputFactory());
CSVSaver saver = new CSVSaver();
Path tmp = Files.createTempFile("foo-empty","csv");
tmp.toFile().deleteOnExit();
saver.save(tmp, src, ... |
@Bean
public RateLimiterRegistry rateLimiterRegistry(
RateLimiterConfigurationProperties rateLimiterProperties,
EventConsumerRegistry<RateLimiterEvent> rateLimiterEventsConsumerRegistry,
RegistryEventConsumer<RateLimiter> rateLimiterRegistryEventConsumer,
@Qualifier("compositeRateLim... | @Test
public void testRateLimiterRegistry() {
io.github.resilience4j.common.ratelimiter.configuration.CommonRateLimiterConfigurationProperties.InstanceProperties instanceProperties1 = new io.github.resilience4j.common.ratelimiter.configuration.CommonRateLimiterConfigurationProperties.InstanceProperties();
... |
@Override
public Result reconcile(GcRequest request) {
log.debug("Extension {} is being deleted", request);
client.fetch(request.gvk(), request.name())
.filter(deletable())
.ifPresent(extension -> {
var extensionStore = converter.convertTo(extension);
... | @Test
void shouldDeleteCorrectly() {
var fake = createExtension();
fake.getMetadata().setDeletionTimestamp(Instant.now());
fake.getMetadata().setFinalizers(null);
when(client.fetch(fake.groupVersionKind(), fake.getMetadata().getName()))
.thenReturn(Optional.of(convertTo(f... |
@Override
public EncryptRuleConfiguration buildToBeDroppedRuleConfiguration(final DropEncryptRuleStatement sqlStatement) {
Collection<EncryptTableRuleConfiguration> toBeDroppedTables = new LinkedList<>();
Map<String, AlgorithmConfiguration> toBeDroppedEncryptors = new HashMap<>();
for (Strin... | @Test
void assertUpdateCurrentRuleConfigurationWithInUsedEncryptor() {
EncryptRuleConfiguration ruleConfig = createCurrentRuleConfigurationWithMultipleTableRules();
EncryptRule rule = mock(EncryptRule.class);
when(rule.getConfiguration()).thenReturn(ruleConfig);
executor.setRule(rule... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test(expected = NotfoundException.class)
public void testListNotFoundFolderMinio() throws Exception {
final Host host = new Host(new S3Protocol(), "play.min.io", new Credentials(
"Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"
)) {
@Override
... |
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
super.check( remarks, transMeta, stepMeta, prev, input, output, i... | @Test
public void testCheck() {
SalesforceUpsertMeta meta = new SalesforceUpsertMeta();
meta.setDefault();
List<CheckResultInterface> remarks = new ArrayList<CheckResultInterface>();
meta.check( remarks, null, null, null, null, null, null, null, null, null );
boolean hasError = false;
for ( Ch... |
void runOnce() {
if (transactionManager != null) {
try {
transactionManager.maybeResolveSequences();
RuntimeException lastError = transactionManager.lastError();
// do not continue sending if the transaction manager is in a failed state
... | @Test
public void testIdempotenceWithMultipleInflightsWhereFirstFailsFatallyAndSequenceOfFutureBatchesIsAdjusted() throws Exception {
final long producerId = 343434L;
TransactionManager transactionManager = createTransactionManager();
setupWithTransactionState(transactionManager);
pr... |
@Override
public R apply(R record) {
final Matcher matcher = regex.matcher(record.topic());
if (matcher.matches()) {
final String topic = matcher.replaceFirst(replacement);
log.trace("Rerouting from topic '{}' to new topic '{}'", record.topic(), topic);
return rec... | @Test
public void slice() {
assertEquals("index", apply("(.*)-(\\d\\d\\d\\d\\d\\d\\d\\d)", "$1", "index-20160117"));
} |
public String redirectWithCorrectAttributesForAd(HttpServletRequest httpRequest, AuthenticationRequest authenticationRequest) throws UnsupportedEncodingException, SamlSessionException {
SamlSession samlSession = authenticationRequest.getSamlSession();
if (samlSession.getValidationStatus() != null && sa... | @Test
public void redirectWithCorrectAttributesToAdForBvDTest() throws UnsupportedEncodingException, SamlSessionException {
AuthenticationRequest authenticationRequest = new AuthenticationRequest();
authenticationRequest.setRequest(httpServletRequestMock);
SamlSession samlSession = new SamlS... |
public static Number toNumber(Object value, Number defaultValue) {
return convertQuietly(Number.class, value, defaultValue);
} | @Test
public void emptyToNumberTest() {
final Object a = "";
final Number number = Convert.toNumber(a);
assertNull(number);
} |
String buildCustomMessage(EventNotificationContext ctx, SlackEventNotificationConfig config, String template) throws PermanentEventNotificationException {
final List<MessageSummary> backlog = getMessageBacklog(ctx, config);
Map<String, Object> model = getCustomMessageModel(ctx, config.type(), backlog, c... | @Test(expected = PermanentEventNotificationException.class)
public void buildCustomMessageWithInvalidTemplate() throws EventNotificationException {
slackEventNotificationConfig = buildInvalidTemplate();
slackEventNotification.buildCustomMessage(eventNotificationContext, slackEventNotificationConfig,... |
@Override
public JsonElement serialize(Instant t, Type type, JsonSerializationContext jsc) {
return new JsonPrimitive(serializeToString(t, ZoneId.systemDefault()));
} | @Test
public void testSerialize() {
assertEquals(
"2024-02-13T15:11:06+08:00",
InstantTypeAdapter.serializeToString(Instant.ofEpochMilli(1707808266154L), ZoneOffset.ofHours(8))
);
} |
@Override
public boolean test(final Path test) {
return this.equals(new CaseInsensitivePathPredicate(test));
} | @Test
public void testPredicateTest() {
final Path t = new Path("/f", EnumSet.of(Path.Type.file));
assertTrue(new CaseInsensitivePathPredicate(t).test(new Path("/f", EnumSet.of(Path.Type.file))));
assertEquals(new CaseInsensitivePathPredicate(t).hashCode(), new CaseInsensitivePathPredicate(n... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, CALLBACK_PATH);
if (provider != null) {
handleProvider(request, response, provider);
}
} | @Test
public void redirect_when_failing_because_of_UnauthorizedExceptionException() throws Exception {
FailWithUnauthorizedExceptionIdProvider identityProvider = new FailWithUnauthorizedExceptionIdProvider();
when(request.getRequestURI()).thenReturn("/oauth2/callback/" + identityProvider.getKey());
identi... |
@Override
public String getName() {
return "Poetry Analyzer";
} | @Test
public void testPoetryLock() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, "poetry.lock"));
analyzer.analyze(result, engine);
assertEquals(88, engine.getDependencies().length);
boolean found = false;
for (Dependency... |
@Override
public void shutdown() {
try {
ksqlEngine.close();
} catch (final Exception e) {
log.warn("Failed to cleanly shutdown the KSQL Engine", e);
}
try {
serviceContext.close();
} catch (final Exception e) {
log.warn("Failed to cleanly shutdown services", e);
}
} | @Test
public void shouldCloseEngineOnStop() {
// When:
standaloneExecutor.shutdown();
// Then:
verify(ksqlEngine).close();
} |
public CompletableFuture<Optional<Topic>> getTopic(final String topic, boolean createIfMissing) {
return getTopic(topic, createIfMissing, null);
} | @Test
public void testGetTopic() throws Exception {
final String ns = "prop/ns-test";
admin.namespaces().createNamespace(ns, 2);
final String topicName = ns + "/topic-1";
admin.topics().createNonPartitionedTopic(String.format("persistent://%s", topicName));
Producer<String> p... |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void shouldPrintTopicDescribeExtended() {
// Given:
final List<RunningQuery> readQueries = ImmutableList.of(
new RunningQuery("read query", ImmutableSet.of("sink1"), ImmutableSet.of("sink1 topic"), new QueryId("readId"), queryStatusCount, KsqlConstants.KsqlQueryType.PERSISTENT)
);
... |
public Path getSubDir() {
return this.subDir;
} | @Test
public void testGetSubDir() throws Exception {
assertEquals(SUBDIR, deletionTask.getSubDir());
} |
protected void setRequestPropertiesWithHeaderInfo(Map<String, String> headerMap, Object request) {
// Try to obtain the unique name of the target service from the headerMap.
// Due to the MOSN routing logic, it may be different from the original service unique name.
if (request instanceof SofaRe... | @Test
public void testSetRequestPropertiesWithHeaderInfo() {
String service1 = "testService1";
String service2 = "testService2";
Map<String, String> headerMap = new HashMap();
headerMap.put(RemotingConstants.HEAD_TARGET_SERVICE, service1);
SofaRequest sofaRequest = new SofaRe... |
public static String gensalt(int log_rounds, SecureRandom random) {
if (log_rounds < MIN_LOG_ROUNDS || log_rounds > MAX_LOG_ROUNDS) {
throw new IllegalArgumentException("Bad number of rounds");
}
StringBuilder rs = new StringBuilder();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
... | @Test
public void testGensaltTooLittleRounds() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class);
BCrypt.gensalt(3);
} |
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "/{executionId}/labels")
@Operation(tags = {"Executions"}, summary = "Add or update labels of a terminated execution")
@ApiResponse(responseCode = "404", description = "If the execution cannot be found")
@ApiResponse(responseCode = "400", description = "If the ex... | @Test
void setLabels() {
// update label on a terminated execution
Execution result = triggerInputsFlowExecution(true);
assertThat(result.getState().getCurrent(), is(State.Type.SUCCESS));
Execution response = client.toBlocking().retrieve(
HttpRequest.POST("/api/v1/executi... |
@Override
@SuppressFBWarnings({ "SERVLET_HEADER_REFERER", "SERVLET_HEADER_USER_AGENT" })
public String format(ContainerRequestType servletRequest, ContainerResponseType servletResponse, SecurityContext ctx) {
//LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined
Str... | @Test
void logsCurrentTimeWhenContextNull() {
// given
proxyRequest.setRequestContext(null);
// when
String actual = sut.format(mockServletRequest, mockServletResponse, null);
// then
assertThat(actual, containsString("[07/02/1991:01:02:03Z]"));
} |
public String getRequestId() {
return requestId;
} | @Test
public void testGetRequestId() {
String requestId = requestContext.getRequestId();
assertNotNull(requestId);
assertNotNull(UUID.fromString(requestId));
requestContext.setRequestId("testRequestId");
assertEquals("testRequestId", requestContext.getRequestId());
} |
public boolean removeIf(Predicate<? super Entry<K, V>> filter)
{
checkMutability();
return _map.entrySet().removeIf(filter);
} | @Test
public void testRemoveIf()
{
final DataMap map = new DataMap();
map.put("key1", 100);
map.put("key2", 200);
map.put("key3", 500);
Assert.assertFalse(map.removeIf(entry -> entry.getKey().equals("Unknown")));
Assert.assertTrue(map.removeIf(entry -> entry.getKey().equals("key2") || ((Int... |
static @Nullable String resolveConsumerArn(Read spec, PipelineOptions options) {
String streamName = Preconditions.checkArgumentNotNull(spec.getStreamName());
KinesisIOOptions sourceOptions = options.as(KinesisIOOptions.class);
Map<String, String> streamToArnMapping = sourceOptions.getKinesisIOConsumerArns(... | @Test
public void testConsumerArnPassedInIO() {
KinesisIO.Read readSpec =
KinesisIO.read().withStreamName("stream-xxx").withConsumerArn("arn::consumer-yyy");
KinesisIOOptions options = createIOOptions();
assertThat(KinesisSource.resolveConsumerArn(readSpec, options)).isEqualTo("arn::consumer-yyy"... |
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
HttpHeaders inHeaders = in.headers();
final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
if (in instanceof HttpRequest) {
HttpRequest request = (HttpRequest) in;
... | @Test
public void connectionSpecificHeadersShouldBeRemoved() {
HttpHeaders inHeaders = new DefaultHttpHeaders();
inHeaders.add(CONNECTION, "keep-alive");
inHeaders.add(HOST, "example.com");
@SuppressWarnings("deprecation")
AsciiString keepAlive = KEEP_ALIVE;
inHeaders... |
public ExitStatus(Options options) {
this.options = options;
} | @Test
void with_undefined_scenarios() {
createRuntime();
bus.send(testCaseFinishedWithStatus(Status.UNDEFINED));
assertThat(exitStatus.exitStatus(), is(equalTo((byte) 0x1)));
} |
@Override
public V remove() {
V value = poll();
if (value == null) {
throw new NoSuchElementException();
}
return value;
} | @Test
public void testRemove() throws InterruptedException {
RBlockingQueue<String> blockingFairQueue = redisson.getBlockingQueue("delay_queue");
RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(blockingFairQueue);
delayedQueue.offer("1_1_1", 3, TimeUnit.SECONDS);
... |
public Search addStreamsToQueriesWithoutStreams(Supplier<Set<String>> defaultStreamsSupplier) {
if (!hasQueriesWithoutStreams()) {
return this;
}
final Set<Query> withStreams = queries().stream().filter(Query::hasStreams).collect(toSet());
final Set<Query> withoutStreams = Se... | @Test
void throwsExceptionIfQueryHasNoStreamsAndThereAreNoDefaultStreams() {
Search search = searchWithQueriesWithStreams("a,b,c", "");
assertThatExceptionOfType(MissingStreamPermissionException.class)
.isThrownBy(() -> search.addStreamsToQueriesWithoutStreams(ImmutableSet::of))
... |
public static Throwable getRootCause(Throwable throwable) {
if (throwable == null) {
return null;
}
Throwable rootCause = throwable;
// this is to avoid infinite loops for recursive cases
final Set<Throwable> seenThrowables = new HashSet<>();
seenThrowables.add(rootCause);
while ((root... | @Test
void rootCauseIsSelf() {
Throwable e = new Exception();
Throwable rootCause = ExceptionUtils.getRootCause(e);
assertThat(rootCause).isSameAs(e);
} |
@Override
public void check(Model model) {
if (model == null)
return;
List<Model> secondPhaseModels = new ArrayList<>();
deepFindAllModelsOfType(AppenderModel.class, secondPhaseModels, model);
deepFindAllModelsOfType(LoggerModel.class, secondPhaseModels, model);
... | @Test
public void smoke() {
ClassicTopModel topModel = new ClassicTopModel();
inwspeChecker.check(topModel);
statusChecker.assertIsWarningOrErrorFree();
} |
public void createSecret(String secretId, String secretData) {
checkArgument(!secretId.isEmpty(), "secretId can not be empty");
checkArgument(!secretData.isEmpty(), "secretData can not be empty");
try {
checkIsUsable();
ProjectName projectName = ProjectName.of(projectId);
// Create the pa... | @Test
public void testCreateSecretShouldCreate() {
Secret secret = Secret.getDefaultInstance();
when(secretManagerServiceClient.createSecret(
any(ProjectName.class), any(String.class), any(Secret.class)))
.thenReturn(secret);
testManager.createSecret(SECRET_ID, SECRET_DATA);
veri... |
public static boolean isRemovable(DockerContainerStatus containerStatus) {
return !containerStatus.equals(DockerContainerStatus.NONEXISTENT)
&& !containerStatus.equals(DockerContainerStatus.UNKNOWN)
&& !containerStatus.equals(DockerContainerStatus.REMOVING)
&& !containerStatus.equals(DockerC... | @Test
public void testIsRemovable() {
assertTrue(DockerCommandExecutor.isRemovable(
DockerContainerStatus.STOPPED));
assertTrue(DockerCommandExecutor.isRemovable(
DockerContainerStatus.RESTARTING));
assertTrue(DockerCommandExecutor.isRemovable(
DockerContainerStatus.EXITED));
a... |
@Override
public void set(String name, String value) {
checkKey(name);
String[] keyParts = splitKey(name);
String ns = registry.getNamespaceURI(keyParts[0]);
if (ns != null) {
try {
xmpData.setProperty(ns, keyParts[1], value);
} catch (XMPExc... | @Test
public void set_simplePropWithMultipleValues_throw() {
assertThrows(PropertyTypeException.class, () -> {
xmpMeta.set(TikaCoreProperties.FORMAT, new String[]{"value1", "value2"});
});
} |
@SuppressWarnings("checkstyle:MissingSwitchDefault")
@Override
protected void doCommit(TableMetadata base, TableMetadata metadata) {
int version = currentVersion() + 1;
CommitStatus commitStatus = CommitStatus.FAILURE;
/* This method adds no fs scheme, and it persists in HTS that way. */
final Stri... | @Test
void testDoCommitAppendSnapshotsExistingVersion() throws IOException {
List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots();
// add 1 snapshot to the base metadata
TableMetadata base =
TableMetadata.buildFrom(BASE_TABLE_METADATA)
.setBranchSnapshot(testSnapshots.get(0), ... |
public void changeFieldType(final CustomFieldMapping customMapping,
final Set<String> indexSetsIds,
final boolean rotateImmediately) {
checkFieldTypeCanBeChanged(customMapping.fieldName());
checkType(customMapping);
checkAllIndicesS... | @Test
void testThrowsExceptionOnIndexThatCannotHaveFieldTypeChanged() {
IndexSetConfig illegalForFieldTypeChange = mock(IndexSetConfig.class);
doReturn(Optional.of(illegalForFieldTypeChange)).when(indexSetService).get("existing_index_set");
assertThrows(BadRequestException.class, () -> toTe... |
public static void quoteHtmlChars(OutputStream output, byte[] buffer,
int off, int len) throws IOException {
for(int i=off; i < off+len; i++) {
switch (buffer[i]) {
case '&':
output.write(AMP_BYTES);
break;
case '<':
output.write(LT_BYTES... | @Test public void testQuoting() throws Exception {
assertEquals("ab<cd", HtmlQuoting.quoteHtmlChars("ab<cd"));
assertEquals("ab>", HtmlQuoting.quoteHtmlChars("ab>"));
assertEquals("&&&", HtmlQuoting.quoteHtmlChars("&&&"));
assertEquals(" '\n", HtmlQuoting.quoteHtmlChars(" '\n"));
... |
public List<QueuePath> getWildcardedQueuePaths(int maxAutoCreatedQueueDepth) {
List<QueuePath> wildcardedPaths = new ArrayList<>();
// Start with the most explicit format (without wildcard)
wildcardedPaths.add(this);
String[] pathComponents = getPathComponents();
int supportedWildcardLevel = getSup... | @Test
public void testWildcardedQueuePathsWithOneLevelWildCard() {
int maxAutoCreatedQueueDepth = 1;
List<QueuePath> expectedPaths = new ArrayList<>();
expectedPaths.add(TEST_QUEUE_PATH);
expectedPaths.add(ONE_LEVEL_WILDCARDED_TEST_PATH);
List<QueuePath> wildcardedPaths = TEST_QUEUE_PATH
... |
public static void setFromConfiguration(Configuration configuration) {
final FlinkSecurityManager flinkSecurityManager =
FlinkSecurityManager.fromConfiguration(configuration);
if (flinkSecurityManager != null) {
try {
System.setSecurityManager(flinkSecurityMan... | @Test
void testRegistrationNotAllowedByExistingSecurityManager() {
Configuration configuration = new Configuration();
configuration.set(
ClusterOptions.INTERCEPT_USER_SYSTEM_EXIT, ClusterOptions.UserSystemExitMode.THROW);
System.setSecurityManager(
new Securi... |
@Override
public long remainTimeToLive(K key) {
return get(remainTimeToLiveAsync(key));
} | @Test
public void testRemainTimeToLive() {
RMapCache<String, String> map = redisson.getMapCache("test");
map.put("1", "2", 2, TimeUnit.SECONDS);
assertThat(map.remainTimeToLive("1")).isBetween(1900L, 2000L);
map.put("3", "4");
assertThat(map.remainTimeToLive("3")).isEqualTo(-... |
public FEELFnResult<String> invoke(@ParameterName("from") Object val) {
if ( val == null ) {
return FEELFnResult.ofResult( null );
} else {
return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) );
}
} | @Test
void invokeNull() {
FunctionTestUtil.assertResult(stringFunction.invoke(null), null);
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final WindowRangeQuery<GenericKey, GenericRow> query = WindowR... | @Test
public void shouldReturnValueIfSessionEndsAtUpperBoundIfUpperBoundClosed() {
// Given:
final Range<Instant> endBounds = Range.closed(
LOWER_INSTANT,
UPPER_INSTANT
);
final Instant wstart = UPPER_INSTANT.minusMillis(1);
givenSingleSession(wstart, UPPER_INSTANT);
// When:
... |
public static Comparator<StructLike> forType(Types.StructType struct) {
return new StructLikeComparator(struct);
} | @Test
public void testDouble() {
assertComparesCorrectly(Comparators.forType(Types.DoubleType.get()), 0.1d, 0.2d);
} |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
final Path found = this.search(file, listener);
return found != null;
}
catch(Notfound... | @Test
public void testFindByType() throws Exception {
final DefaultFindFeature feature = new DefaultFindFeature(new NullSession(new Host(new TestProtocol())) {
@Override
public AttributedList<Path> list(Path file, ListProgressListener listener) {
return new Attributed... |
public Map<String, Object> getConfigurationByPluginTypeOrAliases(final String pluginType, final Class<? extends Plugin> plugin) {
Map<String, Object> configuration = getConfigurationByPluginType(pluginType);
if (configuration.isEmpty()) {
// let's check if the plugin-configuration was provid... | @Test
void shouldGetConfigurationForAlias() {
// Given
Map<String, Object> config = Map.of(
"prop1", "v1",
"prop2", "v1",
"prop3", "v1"
);
PluginConfigurations configurations = new PluginConfigurations(List.of(
new PluginConfiguration(0... |
public final Sensor storeLevelSensor(final String taskId,
final String storeName,
final String sensorSuffix,
final RecordingLevel recordingLevel,
final Sens... | @Test
public void shouldNotUseSameStoreLevelSensorKeyWithDifferentTaskIds() {
final Metrics metrics = mock(Metrics.class);
final ArgumentCaptor<String> sensorKeys = setUpSensorKeyTests(metrics);
final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, VERSION, tim... |
public static <T extends NamedConfig> T getConfig(ConfigPatternMatcher configPatternMatcher,
Map<String, T> configs, String name,
Class clazz) {
return getConfig(configPatternMatcher, configs, name, clazz... | @Test
public void getNonExistingConfig_createNewWithCloningDefault() {
QueueConfig aDefault = new QueueConfig("default");
aDefault.setBackupCount(5);
queueConfigs.put(aDefault.getName(), aDefault);
QueueConfig newConfig = ConfigUtils.getConfig(configPatternMatcher, queueConfigs, "new... |
public boolean containsTableSubquery() {
return getSqlStatement().getFrom().isPresent() && getSqlStatement().getFrom().get() instanceof SubqueryTableSegment || getSqlStatement().getWithSegment().isPresent();
} | @Test
void assertContainsEnhancedTable() {
SelectStatement selectStatement = new MySQLSelectStatement();
selectStatement.setProjections(new ProjectionsSegment(0, 0));
selectStatement.setFrom(new SubqueryTableSegment(0, 0, new SubquerySegment(0, 0, createSubSelectStatement(), "")));
S... |
@Override
@ManagedOperation(description = "Clear the store")
public void clear() {
cache.clear();
} | @Test
void testClear() {
// add key to remove
assertTrue(repo.add(key01));
assertTrue(repo.confirm(key01));
// remove key
assertTrue(repo.remove(key01));
assertFalse(repo.confirm(key01));
// try to remove a key that isn't there
repo.remove(key02);
... |
synchronized void add(int splitCount) {
int pos = count % history.length;
history[pos] = splitCount;
count += 1;
} | @Test
public void testNotFullHistory() {
EnumerationHistory history = new EnumerationHistory(3);
history.add(1);
history.add(2);
int[] expectedHistorySnapshot = {1, 2};
testHistory(history, expectedHistorySnapshot);
} |
@Override
public KubevirtNetwork network(String networkId) {
checkArgument(!Strings.isNullOrEmpty(networkId), ERR_NULL_NETWORK_ID);
return networkStore.network(networkId);
} | @Test
public void testGetNetworkById() {
createBasicNetworks();
assertNotNull("Network did not match", target.network(NETWORK_ID));
assertNull("Network did not match", target.network(UNKNOWN_ID));
} |
public final void containsNoDuplicates() {
List<Multiset.Entry<?>> duplicates = newArrayList();
for (Multiset.Entry<?> entry : LinkedHashMultiset.create(checkNotNull(actual)).entrySet()) {
if (entry.getCount() > 1) {
duplicates.add(entry);
}
}
if (!duplicates.isEmpty()) {
failW... | @Test
public void doesNotContainDuplicatesMixedTypes() {
assertThat(asList(1, 2, 2L, 3)).containsNoDuplicates();
} |
@Override
public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) {
ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult();
result.setOrder(false);
result.setAutoCommit(true);
List<MessageExt> msgs = new ArrayList<>();
... | @Test
public void testConsumeMessageDirectlyWithCrLater() {
when(messageListener.consumeMessage(any(), any(ConsumeConcurrentlyContext.class))).thenReturn(ConsumeConcurrentlyStatus.RECONSUME_LATER);
ConsumeMessageDirectlyResult actual = popService.consumeMessageDirectly(createMessageExt(), defaultBro... |
@Override
public Boolean load(@Nonnull final NamedQuantity key)
{
if (Strings.isNullOrEmpty(key.getName()))
{
return false;
}
final String filteredName = key.getName().trim();
for (final ItemThreshold entry : itemThresholds)
{
if (WildcardMatcher.matches(entry.getItemName(), filteredName)
&& e... | @Test
public void testLoadQuantities()
{
WildcardMatchLoader loader = new WildcardMatchLoader(Arrays.asList("rune* < 3", "*whip>3", "nature*<5", "*rune > 30"));
assertTrue(loader.load(new NamedQuantity("Nature Rune", 50)));
assertFalse(loader.load(new NamedQuantity("Nature Impling", 5)));
assertTrue(loader.lo... |
@Nullable
public CommittableManager<CommT> getEndOfInputCommittable() {
return checkpointCommittables.get(EOI);
} | @Test
void testGetEndOfInputCommittable() {
final CommittableCollector<Integer> committableCollector =
new CommittableCollector<>(1, 1, METRIC_GROUP);
CommittableSummary<Integer> first = new CommittableSummary<>(1, 1, null, 1, 0, 0);
committableCollector.addMessage(first);
... |
@Override
@MethodNotAvailable
public CompletionStage<Void> setAsync(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testSetAsync() {
adapter.setAsync(42, "value");
} |
@Override
public ShardingSphereUser swapToObject(final YamlUserConfiguration yamlConfig) {
if (null == yamlConfig) {
return null;
}
Grantee grantee = convertYamlUserToGrantee(yamlConfig.getUser());
return new ShardingSphereUser(grantee.getUsername(), yamlConfig.getPasswor... | @Test
void assertSwapToObjectWithUserEndWithAt() {
YamlUserConfiguration user = new YamlUserConfiguration();
user.setUser("foo_user@");
user.setPassword("foo_pwd");
ShardingSphereUser actual = new YamlUserSwapper().swapToObject(user);
assertNotNull(actual);
assertThat... |
public void autoRequeue() {
autoRequeue.set(true);
} | @Test
public void testAutoRequeue() throws Exception {
Timing timing = new Timing();
LeaderSelector selector = null;
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(server.getConnectString())
.retryPolicy(new RetryOneTime(1))
... |
public Optional<String> getErrorMsg() {
if (hasLeader()) {
return Optional.empty();
}
return Optional.of("No leader for raft group " + Constants.NAMING_PERSISTENT_SERVICE_GROUP
+ ", please see logs `alipay-jraft.log` or `naming-raft.log` to see details.");
} | @Test
void testGetErrorMsg() {
ServerStatusManager serverStatusManager = new ServerStatusManager(protocolManager, switchDomain);
Optional<String> errorMsg = serverStatusManager.getErrorMsg();
assertTrue(errorMsg.isPresent());
} |
@Override
public DescribeLogDirsResult describeLogDirs(Collection<Integer> brokers, DescribeLogDirsOptions options) {
final Map<Integer, KafkaFutureImpl<Map<String, LogDirDescription>>> futures = new HashMap<>(brokers.size());
final long now = time.milliseconds();
for (final Integer brokerI... | @Test
public void testDescribeLogDirsPartialFailure() throws Exception {
long defaultApiTimeout = 60000;
MockTime time = new MockTime();
try (AdminClientUnitTestEnv env = mockClientEnv(time, AdminClientConfig.RETRIES_CONFIG, "0")) {
env.kafkaClient().prepareResponseFrom(
... |
public void log(QueryLogParams params) {
_logger.debug("Broker Response: {}", params._response);
if (!(_logRateLimiter.tryAcquire() || shouldForceLog(params))) {
_numDroppedLogs.incrementAndGet();
return;
}
final StringBuilder queryLogBuilder = new StringBuilder();
for (QueryLogEntry v... | @Test
public void shouldNotForceLog() {
// Given:
Mockito.when(_logRateLimiter.tryAcquire()).thenReturn(false);
QueryLogger.QueryLogParams params = generateParams(false, 0, 456);
QueryLogger queryLogger = new QueryLogger(_logRateLimiter, 100, true, _logger, _droppedRateLimiter);
// When:
quer... |
public static String getGroupedName(final String serviceName, final String groupName) {
if (StringUtils.isBlank(serviceName)) {
throw new IllegalArgumentException("Param 'serviceName' is illegal, serviceName is blank");
}
if (StringUtils.isBlank(groupName)) {
throw new Il... | @Test
void testGetGroupedNameWithoutServiceName() {
assertThrows(IllegalArgumentException.class, () -> {
NamingUtils.getGroupedName("", "group");
});
} |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test(description = "Filter class return type")
public void testTicket3074() {
Reader reader = new Reader(new OpenAPI());
OpenAPI oasResult = reader.read(RefParameter3074Resource.class);
SerializationMatchers.assertEqualsToYaml(oasResult, RefParameter3074Resource.EXPECTED_YAML_WITH_WRAPPER);... |
@Override
public boolean isUserManaged(DbSession dbSession, String userUuid) {
return findManagedInstanceService()
.map(managedInstanceService -> managedInstanceService.isUserManaged(dbSession, userUuid))
.orElse(false);
} | @Test
public void isUserManaged_delegatesToRightService_andPropagateAnswer() {
DelegatingManagedServices managedInstanceService = new DelegatingManagedServices(Set.of(new NeverManagedInstanceService(), new AlwaysManagedInstanceService()));
assertThat(managedInstanceService.isUserManaged(dbSession, "whatever"... |
@POST
@ApiOperation("Create a new view")
@AuditEvent(type = ViewsAuditEventTypes.VIEW_CREATE)
public ViewDTO create(@ApiParam @Valid @NotNull(message = "View is mandatory") ViewDTO dto,
@Context UserContext userContext,
@Context SearchUser searchUser) thro... | @Test
public void throwsExceptionWhenCreatingDashboardWithFilterThatUserIsNotAllowedToSee() {
final ViewsResource viewsResource = createViewsResource(
mockViewService(TEST_DASHBOARD_VIEW),
mock(StartPageService.class),
mock(RecentActivityService.class),
... |
@VisibleForTesting
AuthRequest buildAuthRequest(Integer socialType, Integer userType) {
// 1. 先查找默认的配置项,从 application-*.yaml 中读取
AuthRequest request = authRequestFactory.get(SocialTypeEnum.valueOfType(socialType).getSource());
Assert.notNull(request, String.format("社交平台(%d) 不存在", socialType)... | @Test
public void testBuildAuthRequest_clientEnable() {
// 准备参数
Integer socialType = SocialTypeEnum.WECHAT_MP.getType();
Integer userType = randomPojo(SocialTypeEnum.class).getType();
// mock 获得对应的 AuthRequest 实现
AuthConfig authConfig = mock(AuthConfig.class);
AuthReq... |
public static HttpRequest.Builder buildRefreshRequestUrlForAccessToken(
TokensAndUrlAuthData authData, AppCredentials appCredentials) throws IllegalStateException {
BodyPublisher postBody = buildRefreshRequestPostBody(authData, appCredentials);
URI refreshUri = authData.getTokenServerEncodedUri();
ret... | @Test
public void test_buildRefreshRequestUrlForAccessToken() {
//
// Arrange
//
final String fakeAuthUrl = "https://www.example.com/auth";
TokensAndUrlAuthData fakeAuthData =
new TokensAndUrlAuthData("my_access_token", "my_refresh_token", fakeAuthUrl);
AppCredentials mockAppCredential... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
final boolean satisfied = first.getValue(index).isLessThan(second.getValue(index));
traceIsSatisfied(index, satisfied);
return satisfied;
} | @Test
public void isSatisfied() {
assertTrue(rule.isSatisfied(0));
assertFalse(rule.isSatisfied(1));
assertFalse(rule.isSatisfied(2));
assertFalse(rule.isSatisfied(3));
assertTrue(rule.isSatisfied(4));
assertFalse(rule.isSatisfied(5));
assertFalse(rule.isSatis... |
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean is... | @Test
void testNoStrategySpecifiedWhenCheckpointingDisabled() {
final RestartBackoffTimeStrategy.Factory factory =
RestartBackoffTimeStrategyFactoryLoader.createRestartBackoffTimeStrategyFactory(
DEFAULT_JOB_LEVEL_RESTART_CONFIGURATION,
new Con... |
public UpsertPartitioner(WorkloadProfile profile, HoodieEngineContext context, HoodieTable table,
HoodieWriteConfig config, WriteOperationType operationType) {
super(profile, table);
updateLocationToBucket = new HashMap<>();
partitionPathToInsertBucketInfos = new HashMap<>();
... | @Test
public void testUpsertPartitioner() throws Exception {
final String testPartitionPath = "2016/09/26";
// Inserts + Updates... Check all updates go together & inserts subsplit
UpsertPartitioner partitioner = getUpsertPartitioner(0, 200, 100, 1024, testPartitionPath, false);
List<InsertBucketCumul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.