focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static String normalize(String path) {
if (path == null) {
return null;
}
//兼容Windows下的共享目录路径(原始路径如果以\\开头,则保留这种路径)
if (path.startsWith("\\\\")) {
return path;
}
// 兼容Spring风格的ClassPath路径,去除前缀,不区分大小写
String pathToUse = StrUtil.removePrefixIgnoreCase(path, URLUtil.CLASSPATH_URL_PREFIX);
// ... | @Test
public void normalizeClassPathTest() {
assertEquals("", FileUtil.normalize("classpath:"));
} |
public void snapshotTimer(final long correlationId, final long deadline)
{
idleStrategy.reset();
while (true)
{
final long result = publication.tryClaim(ENCODED_TIMER_LENGTH, bufferClaim);
if (result > 0)
{
timerEncoder
... | @Test
void snapshotTimer()
{
final int offset = 18;
final int length = MessageHeaderEncoder.ENCODED_LENGTH + TimerEncoder.BLOCK_LENGTH;
final long correlationId = -901;
final long deadline = 12345678901L;
when(publication.tryClaim(eq(length), any()))
.thenRetu... |
public void useModules(String... names) {
checkNotNull(names, "names cannot be null");
Set<String> deduplicateNames = new HashSet<>();
for (String name : names) {
if (!loadedModules.containsKey(name)) {
throw new ValidationException(
String.for... | @Test
void testUseUnloadedModules() {
assertThatThrownBy(() -> manager.useModules(CoreModuleFactory.IDENTIFIER, "x"))
.isInstanceOf(ValidationException.class)
.hasMessage("No module with name 'x' exists");
} |
@Override
public HttpAction restore(final CallContext ctx, final String defaultUrl) {
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val optRequestedUrl = sessionStore.get(webContext, Pac4jConstants.REQUESTED_URL);
HttpAction requestedAction = null;
... | @Test
public void testRestoreNoRequestedUrl() {
val context = MockWebContext.create();
val sessionStore = new MockSessionStore();
val action = handler.restore(new CallContext(context, sessionStore), LOGIN_URL);
assertTrue(action instanceof FoundAction);
assertEquals(LOGIN_URL... |
static void populateOutputFields(final PMML4Result toUpdate,
final ProcessingDTO processingDTO) {
logger.debug("populateOutputFields {} {}", toUpdate, processingDTO);
for (KiePMMLOutputField outputField : processingDTO.getOutputFields()) {
Object variable... | @Test
void populateTransformedOutputFieldWithApplyDerivedFieldFromApply() {
// <DerivedField name="CUSTOM_FIELD" optype="continuous" dataType="double">
// <Apply function="+">
// <Constant>64.0</Constant>
// <Constant>36.0</Constant>
// </Apply>
... |
@Override
public <T> Invoker<T> buildInvokerChain(final Invoker<T> originalInvoker, String key, String group) {
Invoker<T> last = originalInvoker;
URL url = originalInvoker.getUrl();
List<ModuleModel> moduleModels = getModuleModelsFromUrl(url);
List<Filter> filters;
if (modul... | @Test
void testBuildInvokerChainForRemoteReference() {
DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder();
// verify that no filter is built by default
URL urlWithoutFilter = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(... |
public static byte getProtocolTypeFromString(String str) {
switch (str.toLowerCase()) {
case PROTOCOL_NAME_TCP:
return IPv4.PROTOCOL_TCP;
case PROTOCOL_NAME_UDP:
return IPv4.PROTOCOL_UDP;
case PROTOCOL_NAME_ANY:
default:
... | @Test
public void testGetProtocolTypeFromString() {
assertEquals(IPv4.PROTOCOL_TCP, getProtocolTypeFromString(PROTOCOL_TCP_L));
assertEquals(IPv4.PROTOCOL_TCP, getProtocolTypeFromString(PROTOCOL_TCP_S));
assertEquals(IPv4.PROTOCOL_UDP, getProtocolTypeFromString(PROTOCOL_UDP_L));
ass... |
static <T> ConsumerImpl<T> newConsumerImpl(PulsarClientImpl client,
String topic,
ConsumerConfigurationData<T> conf,
ExecutorProvider executorProvider,
... | @Test
public void testConsumerCreatedWhilePaused() throws InterruptedException {
PulsarClientImpl client = ClientTestFixtures.createPulsarClientMock(executorProvider, internalExecutor);
ClientConfigurationData clientConf = client.getConfiguration();
clientConf.setOperationTimeoutMs(100);
... |
public abstract int getPriority(); | @Test
void testGetPriority() {
assertEquals(Integer.MIN_VALUE, abilityControlManager.getPriority());
} |
@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 shouldApplyDropConnectorIfExistsStatement() throws Exception {
// Given:
command = PARSER.parse("-v", "3");
createMigrationFile(1, NAME, migrationsDir, COMMAND);
createMigrationFile(3, NAME, migrationsDir, DROP_CONNECTOR_IF_EXISTS);
givenCurrentMigrationVersion("1");
givenApp... |
@Override
public double logp(int k) {
if (k <= 0) {
return Double.NEGATIVE_INFINITY;
} else {
return (k - 1) * Math.log(1 - p) + Math.log(p);
}
} | @Test
public void testLogP() {
System.out.println("logP");
ShiftedGeometricDistribution instance = new ShiftedGeometricDistribution(0.3);
instance.rand();
assertEquals(Math.log(0.3), instance.logp(1), 1E-6);
assertEquals(Math.log(0.21), instance.logp(2), 1E-6);
assert... |
boolean connectedToRepository() {
return repository.isConnected();
} | @Test
public void connectedToRepositoryReturnsFalse() {
when( repository.isConnected() ).thenReturn( false );
assertFalse( timeoutHandler.connectedToRepository() );
} |
@Override
public String getString(int rowIndex, int columnIndex) {
if (columnIndex != 0) {
throw new IllegalArgumentException("Column index must always be 0 for aggregation result sets");
}
return _groupByResults.get(rowIndex).get("value").asText();
} | @Test
public void testGetString() {
// Run the test
final String result = _groupByResultSetUnderTest.getString(0, 0);
// Verify the results
assertEquals("1", result);
} |
public static String removeAllHtmlAttr(String content, String... tagNames) {
String regex;
for (String tagName : tagNames) {
regex = StrUtil.format("(?i)<{}[^>]*?>", tagName);
content = content.replaceAll(regex, StrUtil.format("<{}>", tagName));
}
return content;
} | @Test
public void removeAllHtmlAttrTest() {
final String html = "<div class=\"test_div\" width=\"120\"></div>";
final String result = HtmlUtil.removeAllHtmlAttr(html, "div");
assertEquals("<div></div>", result);
} |
@Override
public String getResourceInputNodeType() {
return DictionaryConst.NODE_TYPE_FILE_FIELD;
} | @Test
public void testGetResourceInputNodeType() throws Exception {
assertEquals( DictionaryConst.NODE_TYPE_FILE_FIELD, analyzer.getResourceInputNodeType() );
} |
public static Object matchEndpointKey(String path, Map<String, Object> map) {
if (isEmpty(map)) {
return null;
}
// iterate key set to find the endpoint pattern that matches the request path
for (String endpoint : map.keySet()) {
if (StringUtils.matchPathToPattern... | @Test
public void testMatchEndpointKey() {
Map<String, Object> map = new HashMap<>();
map.put("/v1/cat/{petId}", "123");
map.put("/v1/dog/{petId}/uploadImage", "456");
map.put("/v1/fish/{petId}/uploadImage/{imageId}", "789");
Assert.assertEquals("123", CollectionUtils.matchE... |
@Override
public TenantDO getTenantByName(String name) {
return tenantMapper.selectByName(name);
} | @Test
public void testGetTenantByName() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setName("芋道"));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
// 调用
TenantDO result = tenantService.getTenantByName("芋道");
// 校验存在
assertPojoEquals... |
public static String[] getEmptyPaddedStrings() {
if ( emptyPaddedSpacesStrings == null ) {
emptyPaddedSpacesStrings = new String[250];
for ( int i = 0; i < emptyPaddedSpacesStrings.length; i++ ) {
emptyPaddedSpacesStrings[i] = rightPad( "", i );
}
}
return emptyPaddedSpacesStrings;... | @Test
public void testGetEmptyPaddedStrings() {
final String[] strings = Const.getEmptyPaddedStrings();
for ( int i = 0; i < 250; i++ ) {
assertEquals( i, strings[i].length() );
}
} |
@Override
public boolean databaseExists(String databaseName) throws CatalogException {
checkArgument(!StringUtils.isNullOrEmpty(databaseName));
return listDatabases().contains(databaseName);
} | @Test
public void testDatabaseExists() {
assertTrue(catalog.databaseExists(TEST_DEFAULT_DATABASE));
assertFalse(catalog.databaseExists(NONE_EXIST_DATABASE));
} |
@Override
public CompletableFuture<MastershipRole> requestRoleFor(DeviceId deviceId) {
checkNotNull(deviceId, DEVICE_ID_NULL);
final Timer.Context timer = startTimer(requestRoleTimer);
return store.requestRole(networkId, deviceId)
.whenComplete((result, error) -> stopTimer(t... | @Test
public void requestRoleFor() {
mastershipMgr1.setRole(NID_LOCAL, VDID1, MASTER);
mastershipMgr1.setRole(NID_OTHER, VDID2, MASTER);
//local should be master for one but standby for other
assertEquals("wrong role:", MASTER, Futures.getUnchecked(mastershipMgr1.requestRoleFor(VDID... |
@Override
public boolean trySetCapacity(int capacity) {
return get(trySetCapacityAsync(capacity));
} | @Test
public void testConcurrentPut() throws InterruptedException {
final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("bounded-queue:testConcurrentPut");
assertThat(queue1.trySetCapacity(10000)).isTrue();
ExecutorService executor = Executors.newFixedThreadPool(Ru... |
public String build( final String cellValue ) {
switch ( type ) {
case FORALL:
return buildForAll( cellValue );
case INDEXED:
return buildMulti( cellValue );
default:
return buildSingle( cellValue );
}
} | @Test
public void testSingleParamMultipleTimes() {
final String snippet = "something.param.getAnother($param).equals($param);";
final SnippetBuilder snip = new SnippetBuilder(snippet);
final String cellValue = "42";
final String result = snip.build(cellValue);
assertThat(resu... |
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (issue.isNew()) {
// analyzer can provide some tags. They must be merged with rule tags
Rule rule = ruleRepository.getByKey(issue.ruleKey());
issue.setTags(union(issue.tags(), rule.getTags()));
}
} | @Test
public void copy_tags_if_new_external_issue() {
externalRule.setTags(Sets.newHashSet("es_lint", "java"));
externalIssue.setNew(true);
underTest.onIssue(mock(Component.class), externalIssue);
assertThat(externalIssue.tags()).containsExactly("es_lint", "java");
} |
@Override
public ListConsumerGroupOffsetsResult listConsumerGroupOffsets(Map<String, ListConsumerGroupOffsetsSpec> groupSpecs,
ListConsumerGroupOffsetsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, OffsetAndMetad... | @Test
public void testListConsumerGroupOffsetsRetriableErrors() throws Exception {
// Retriable errors should be retried
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
env.ka... |
public static void tryEnrichClusterEntryPointError(@Nullable Throwable root) {
tryEnrichOutOfMemoryError(
root,
JM_METASPACE_OOM_ERROR_MESSAGE,
JM_DIRECT_OOM_ERROR_MESSAGE,
JM_HEAP_SPACE_OOM_ERROR_MESSAGE);
} | @Test
public void testMetaspaceOOMHandling() {
OutOfMemoryError error = new OutOfMemoryError("Metaspace");
ClusterEntryPointExceptionUtils.tryEnrichClusterEntryPointError(error);
assertThat(
error.getMessage(),
is(ClusterEntryPointExceptionUtils.JM_METASPACE_... |
@Override
public String getFailureMessage() {
return _failureMessage;
} | @Test
public void testSetFailureMessage() {
BasicAuthorizationResultImpl result = new BasicAuthorizationResultImpl(true, "New Failure Message");
assertEquals("New Failure Message", result.getFailureMessage());
} |
@Override
protected Logger newLogger(String name) {
return new JettyLoggerAdapter(name);
} | @Test
void testNewLogger() {
JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter();
org.eclipse.jetty.util.log.Logger logger =
loggerAdapter.newLogger(this.getClass().getName());
assertThat(logger.getClass().isAssignableFrom(JettyLoggerAdapter.class), is(true));
} |
public boolean isEphemeral() {
return ephemeral;
} | @Test
void testIsEphemeral() {
assertTrue(serviceMetadata.isEphemeral());
} |
@Udf
public Integer extractPort(
@UdfParameter(description = "a valid URL to extract a port from") final String input) {
final Integer port = UrlParser.extract(input, URI::getPort);
// check for LT 0 because URI::getPort returns -1 if the port
// does not exist, but UrlParser#extract will return nu... | @Test
public void shouldExtractPortIfPresent() {
assertThat(
extractUdf.extractPort("https://docs.confluent.io:8080/current/ksql/docs/syntax-reference.html#scalar-functions"),
equalTo(8080));
} |
@Override
public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) {
LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats);
BinaryColumnStatsData aggregateData = aggregateColStats.getStatsData().getBinaryStats();
BinaryCo... | @Test
public void testMergeNonNullValues() {
ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(byte[].class)
.avgColLen(3)
.maxColLen(2)
.numNulls(2)
.build());
ColumnStatisticsObj newObj = createColumnStatisticsObj(new ColStatsBuilder<>(byte[].class... |
public List<Date> parse(String language)
{
return parse(language, new Date());
} | @Test
public void testParseTimes()
{
List<Date> parse = new PrettyTimeParser().parse("let's get lunch at two pm");
Assert.assertFalse(parse.isEmpty());
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse.get(0));
Assert.assertEquals(14, calendar.get(Calendar.HOUR_OF_DA... |
@Override
public void run(AdminStatisticsJobRequest jobRequest) throws Exception {
var year = jobRequest.getYear();
var month = jobRequest.getMonth();
LOGGER.info(">> ADMIN REPORT STATS {} {}", year, month);
var stopwatch = new StopWatch();
stopwatch.start("repositories.coun... | @Test
public void testAdminStatisticsJobRequestHandlerWithPreviousStatistics() throws Exception {
var expectedStatistics = mockAdminStatistics();
expectedStatistics.setDownloads(678L);
var prevStatistics = new AdminStatistics();
prevStatistics.setDownloadsTotal(5000);
Mockit... |
public static String toJavaCode(
final String argName,
final Class<?> argType,
final String lambdaBody
) {
return toJavaCode(ImmutableList.of(new Pair<>(argName, argType)), lambdaBody);
} | @Test(expected= KsqlException.class)
public void shouldThrowOnNonSupportedArguments() {
// Given:
final Pair<String, Class<?>> argName1 = new Pair<>("fred", Long.class);
final Pair<String, Class<?>> argName2 = new Pair<>("bob", Long.class);
final Pair<String, Class<?>> argName3 = new Pair<>("tim", Lon... |
public String sanitizeInput(String input) {
if (input != null) {
for (String unsafeTag : unsafeTags) {
String unsafeRegex = "<" + unsafeTag + ">(.*)</" + unsafeTag + ">";
Pattern pattern = Pattern.compile(unsafeRegex);
Matcher matcher = pattern.matcher(input);
if (matcher.find(... | @Test
void sanitizeInput() {
String input = "This is "
+ "<script>alert(1);</script> "
+ "<div onclick='alert(2)'>this is div</div> "
+ "text";
String output = md.sanitizeInput(input);
assertFalse(output.contains("<script>"));
assertFalse(output.contains("onclick"));
assert... |
public static OperatorID fromUid(String uid) {
byte[] hash = Hashing.murmur3_128(0).newHasher().putString(uid, UTF_8).hash().asBytes();
return new OperatorID(hash);
} | @Test
public void testOperatorIdMatchesUid() {
OperatorID expectedId = getOperatorID();
OperatorID generatedId = OperatorIDGenerator.fromUid(UID);
Assert.assertEquals(expectedId, generatedId);
} |
static int determineOperatorReservoirSize(int operatorParallelism, int numPartitions) {
int coordinatorReservoirSize = determineCoordinatorReservoirSize(numPartitions);
int totalOperatorSamples = coordinatorReservoirSize * OPERATOR_OVER_SAMPLE_RATIO;
return (int) Math.ceil((double) totalOperatorSamples / op... | @Test
public void testOperatorReservoirSize() {
assertThat(SketchUtil.determineOperatorReservoirSize(5, 3))
.isEqualTo((10_002 * SketchUtil.OPERATOR_OVER_SAMPLE_RATIO) / 5);
assertThat(SketchUtil.determineOperatorReservoirSize(123, 123))
.isEqualTo((123_00 * SketchUtil.OPERATOR_OVER_SAMPLE_RAT... |
public final void tag(I input, ScopedSpan span) {
if (input == null) throw new NullPointerException("input == null");
if (span == null) throw new NullPointerException("span == null");
if (span.isNoop()) return;
tag(span, input, span.context());
} | @Test void tag_customizer_doesntParseNoop() {
tag.tag(input, context, NoopSpanCustomizer.INSTANCE);
verifyNoMoreInteractions(parseValue); // parsing is lazy
} |
@Description("Inverse of F cdf given numerator degrees of freedom (df1), denominator degrees of freedom (df2) parameters, and probability")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double inverseFCdf(
@SqlType(StandardTypes.DOUBLE) double df1,
@SqlType(StandardTyp... | @Test
public void testInverseFCdf()
{
assertFunction("inverse_f_cdf(2.0, 5.0, 0.0)", DOUBLE, 0.0);
assertFunction("round(inverse_f_cdf(2.0, 5.0, 0.5), 4)", DOUBLE, 0.7988);
assertFunction("round(inverse_f_cdf(2.0, 5.0, 0.9), 4)", DOUBLE, 3.7797);
assertInvalidFunction("inverse_f... |
void retriggerSubpartitionRequest(Timer timer) {
synchronized (requestLock) {
checkState(subpartitionView == null, "already requested partition");
timer.schedule(
new TimerTask() {
@Override
public void run() {
... | @Test
void testChannelErrorWhileRetriggeringRequest() {
final SingleInputGate inputGate = createSingleInputGate(1);
final LocalInputChannel localChannel =
createLocalInputChannel(inputGate, new ResultPartitionManager());
final Timer timer =
new Timer(true) {
... |
@Override
public Optional<Product> findProduct(int productId) {
return this.productRepository.findById(productId);
} | @Test
void findProduct_ProductDoesNotExist_ReturnsEmptyOptional() {
// given
var product = new Product(1, "Товар №1", "Описание товара №1");
// when
var result = this.service.findProduct(1);
// then
assertNotNull(result);
assertTrue(result.isEmpty());
... |
@Override
public long nextDelayDuration(int reconsumeTimes) {
if (reconsumeTimes < 0) {
reconsumeTimes = 0;
}
if (reconsumeTimes > 32) {
reconsumeTimes = 32;
}
return Math.min(max, initial * (long) Math.pow(multiplier, reconsumeTimes));
} | @Test
public void testNextDelayDurationOutOfRange() {
ExponentialRetryPolicy exponentialRetryPolicy = new ExponentialRetryPolicy();
long actual = exponentialRetryPolicy.nextDelayDuration(-1);
assertThat(actual).isEqualTo(TimeUnit.SECONDS.toMillis(5));
actual = exponentialRetryPolicy.... |
public static LocalUri parse(String path) {
if (path.startsWith(SCHEME)) {
URI parsed = URI.create(path);
path = parsed.getPath();
}
if (!path.startsWith(SLASH)) {
throw new IllegalArgumentException("Path must start at root /");
}
StringTokeniz... | @Test
public void testParseMalformedRelative() {
String path = "example////some-id//instances/some-instance-id";
assertThrows(IllegalArgumentException.class, () -> LocalUri.parse(path));
} |
@Override
public Predicate negate() {
int size = predicates.length;
Predicate[] inners = new Predicate[size];
for (int i = 0; i < size; i++) {
Predicate original = predicates[i];
Predicate negated;
if (original instanceof NegatablePredicate predicate) {
... | @Test
public void negate_whenContainsNonNegatablePredicate_thenReturnOrPredicateWithNotInside() {
// ~(foo and bar) --> (~foo or ~bar)
// this is testing the case where the inner predicate does NOT implement {@link Negatable}
Predicate nonNegatable = mock(Predicate.class);
AndPre... |
@Override
public ApiResult<TopicPartition, ListOffsetsResultInfo> handleResponse(
Node broker,
Set<TopicPartition> keys,
AbstractResponse abstractResponse
) {
ListOffsetsResponse response = (ListOffsetsResponse) abstractResponse;
Map<TopicPartition, ListOffsetsResultInfo>... | @Test
public void testHandleUnexpectedPartitionErrorResponse() {
TopicPartition errorPartition = t0p0;
Errors error = Errors.UNKNOWN_SERVER_ERROR;
Map<TopicPartition, Short> errorsByPartition = new HashMap<>();
errorsByPartition.put(errorPartition, error.code());
ApiResult<T... |
public String hash() {
try (LockResource r = new LockResource(mLock.readLock())) {
return mHash.get();
}
} | @Test
public void hashEmpty() {
PathProperties emptyProperties = new PathProperties();
String hash = emptyProperties.hash();
Assert.assertNotNull(hash);
Assert.assertEquals(hash, emptyProperties.hash());
} |
@Override
public Option<FileSlice> getLatestFileSlice(String partitionPath, String fileId) {
return execute(partitionPath, fileId, preferredView::getLatestFileSlice, (path, fgId) -> getSecondaryView().getLatestFileSlice(path, fgId));
} | @Test
public void testGetLatestFileSlice() {
Option<FileSlice> actual;
Option<FileSlice> expected = Option.fromJavaOptional(testFileSliceStream.findFirst());
String partitionPath = "/table2";
String fileID = "file.123";
when(primary.getLatestFileSlice(partitionPath, fileID)).thenReturn(expected);... |
@Nonnull
public static <T> Sink<T> remoteReliableTopic(@Nonnull String reliableTopicName,
@Nonnull ClientConfig clientConfig) {
String clientXml = asXmlString(clientConfig); //conversion needed for serializability
return SinkBuilder
.... | @Test
public void remoteReliableTopic() {
// Given
populateList(srcList);
List<Object> receivedList = new ArrayList<>();
remoteHz.getReliableTopic(sinkName).addMessageListener(message -> receivedList.add(message.getMessageObject()));
// When
Sink<Object> sink = Sink... |
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final List<Path> containers = new ArrayList<>();
for(Path file : files.keySet()) {
if(containerService.isContainer(file)) {
container... | @Test
public void testDeleteFile() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path test = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new S3To... |
public static KubernetesJobManagerSpecification buildKubernetesJobManagerSpecification(
FlinkPod podTemplate, KubernetesJobManagerParameters kubernetesJobManagerParameters)
throws IOException {
FlinkPod flinkPod = Preconditions.checkNotNull(podTemplate).copy();
List<HasMetadata> ... | @Test
void testSetJobManagerDeploymentReplicas() throws Exception {
flinkConfig.set(HighAvailabilityOptions.HA_MODE, HighAvailabilityMode.KUBERNETES.name());
flinkConfig.set(
KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, JOBMANAGER_REPLICAS);
kubernetesJobManagerSpe... |
public void runPickle(Pickle pickle) {
try {
StepTypeRegistry stepTypeRegistry = createTypeRegistryForPickle(pickle);
snippetGenerators = createSnippetGeneratorsForPickle(stepTypeRegistry);
// Java8 step definitions will be added to the glue here
buildBackendWorl... | @Test
void aftersteps_are_executed_after_failed_step() {
StubStepDefinition stepDefinition = spy(new StubStepDefinition("some step") {
@Override
public void execute(Object[] args) {
super.execute(args);
throw new RuntimeException();
}
... |
public static RecordBuilder<Schema> record(String name) {
return builder().record(name);
} | @Test
void validateDefaultsEnabled() {
assertThrows(AvroRuntimeException.class, () -> {
try {
SchemaBuilder.record("ValidationRecord").fields().name("IntegerField").type("int").withDefault("Invalid")
.endRecord();
} catch (AvroRuntimeException e) {
assertEquals("Invalid def... |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testCollectFetchInitializationWithUpdateLogStartOffsetOnNotAssignedPartition() {
final TopicPartition topicPartition0 = new TopicPartition("topic", 0);
final long fetchOffset = 42;
final long highWatermark = 1000;
final long logStartOffset = 10;
final Subscr... |
public static Block getBlockObject(Type type, Object object, ObjectInspector objectInspector)
{
return requireNonNull(serializeObject(type, null, object, objectInspector), "serialized result is null");
} | @Test
public void testReuse()
{
BytesWritable value = new BytesWritable();
byte[] first = "hello world".getBytes(UTF_8);
value.set(first, 0, first.length);
byte[] second = "bye".getBytes(UTF_8);
value.set(second, 0, second.length);
Type type = new TypeToken<Map... |
public static HgVersion parse(String hgOut) {
String[] lines = hgOut.split("\n");
String firstLine = lines[0];
Matcher m = HG_VERSION_PATTERN.matcher(firstLine);
if (m.matches()) {
try {
return new HgVersion(Version.create(
asInt(m, 1),... | @Test
void shouldBombIfVersionCannotBeParsed() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> HgVersion.parse(WINDOWS_HG_TORTOISE))
.withMessage("cannot parse Hg version : " + WINDOWS_HG_TORTOISE);
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
String highwayValue = way.getTag("highway");
if (skipEmergency && "service".equals(highwayValue) && "emergency_access".equals(way.getTag("service")))
return;
int ... | @Test
public void testPrivate() {
ReaderWay way = new ReaderWay(1);
way.setTag("highway", "primary");
way.setTag("access", "private");
EdgeIntAccess edgeIntAccess = ArrayEdgeIntAccess.createFromBytes(em.getBytesForFlags());
int edgeId = 0;
parser.handleWayTags(edgeId,... |
@Override
public byte[] toByteArray() {
return toByteArray(0);
} | @Test(expected = UnsupportedOperationException.class)
public void testToByteArray() {
out.toByteArray();
} |
@VisibleForTesting
static Number convert(Date date, TimeUnit timeUnit, FieldSpec.DataType dataType) {
long convertedTime = timeUnit.convert(date.getTime(), TimeUnit.MILLISECONDS);
if (dataType == FieldSpec.DataType.LONG || dataType == FieldSpec.DataType.TIMESTAMP) {
return convertedTime;
}
if (d... | @Test
public void testConvert() {
int oneHourInMillis = 60 * 60 * 1000;
Date date = new Date(oneHourInMillis + 1);
// seconds
Number convertedTime = TimeGenerator.convert(date, TimeUnit.SECONDS, FieldSpec.DataType.LONG);
assertTrue(convertedTime instanceof Long);
assertEquals(3600L, converted... |
@Override
public RouteContext route(final RouteContext routeContext, final BroadcastRule broadcastRule) {
RouteMapper dataSourceMapper = getDataSourceRouteMapper(broadcastRule.getDataSourceNames());
routeContext.getRouteUnits().add(new RouteUnit(dataSourceMapper, createTableRouteMappers()));
... | @Test
void assertRouteWithCursorStatement() {
CreateViewStatementContext sqlStatementContext = mock(CreateViewStatementContext.class);
Collection<String> logicTables = Collections.singleton("t_address");
ConnectionContext connectionContext = mock(ConnectionContext.class);
BroadcastUn... |
public void enablePrivacy(double epsilon)
{
enablePrivacy(epsilon, getDefaultRandomizationStrategy());
} | @Test
public void testEnablePrivacy()
{
SfmSketch sketch = SfmSketch.create(4096, 24);
double epsilon = 4;
for (int i = 0; i < 100_000; i++) {
sketch.add(i);
}
long cardinalityBefore = sketch.cardinality();
sketch.enablePrivacy(epsilon, new TestingSe... |
@Override
@Nullable
public Object convert(@Nullable String value) {
if (isNullOrEmpty(value)) {
return null;
}
LOG.debug("Trying to parse date <{}> with pattern <{}>, locale <{}>, and timezone <{}>.", value, dateFormat, locale, timeZone);
final DateTimeFormatter form... | @Test
public void convertObeysTimeZone() throws Exception {
final DateTimeZone timeZone = DateTimeZone.forOffsetHours(12);
final Converter c = new DateConverter(config("YYYY-MM-dd HH:mm:ss", timeZone.toString(), null));
final DateTime dateOnly = (DateTime) c.convert("2014-03-12 10:00:00");
... |
@Override
public List<String> detect(ClassLoader classLoader) {
List<File> classpathContents =
classGraph
.disableNestedJarScanning()
.addClassLoader(classLoader)
.scan(1)
.getClasspathFiles();
return classpathContents.stream().map(File::getAbsolutePath... | @Test
public void shouldStillDetectResourcesEvenIfClassloaderIsUseless() {
ClassLoader uselessClassLoader = Mockito.mock(ClassLoader.class);
ClasspathScanningResourcesDetector detector =
new ClasspathScanningResourcesDetector(new ClassGraph());
List<String> detectedResources = detector.detect(use... |
@Subscribe
public synchronized void renew(final ClusterStateEvent event) {
contextManager.getStateContext().switchClusterState(event.getClusterState());
} | @Test
void assertRenewInstanceState() {
ComputeNodeInstanceStateChangedEvent event = new ComputeNodeInstanceStateChangedEvent(
contextManager.getComputeNodeInstanceContext().getInstance().getMetaData().getId(), InstanceState.OK.name());
subscriber.renew(event);
assertThat(con... |
@SuppressWarnings("unchecked")
public static <T extends Factory> T discoverFactory(
ClassLoader classLoader, Class<T> factoryClass, String factoryIdentifier) {
final List<Factory> factories = discoverFactories(classLoader);
final List<Factory> foundFactories =
factories.... | @Test
void testCreateCatalogStore() {
final Map<String, String> options = new HashMap<>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final FactoryUtil.DefaultCatalogStoreContext discoveryContext =
new FactoryUtil.DefaultCatalogStoreContext(opti... |
@Override
public Response request(Request request, long timeouts) throws NacosException {
Payload grpcRequest = GrpcUtils.convert(request);
ListenableFuture<Payload> requestFuture = grpcFutureServiceStub.request(grpcRequest);
Payload grpcResponse;
try {
if (timeouts <= 0)... | @Test
void testRequestTimeout() throws InterruptedException, ExecutionException, TimeoutException, NacosException {
assertThrows(NacosException.class, () -> {
when(future.get(100L, TimeUnit.MILLISECONDS)).thenThrow(new TimeoutException("test"));
connection.request(new HealthCheckRequ... |
public int getVersion() {
return mVersion;
} | @Test
public void testProperties() {
PrefsRoot root = new PrefsRoot(3);
Assert.assertEquals(3, root.getVersion());
} |
public IZAddress resolve(boolean ipv6)
{
resolved = protocol.zresolve(address, ipv6);
return resolved;
} | @Test(expected = ZMQException.class)
public void testInvalid()
{
new Address("tcp", "ggglocalhostxxx.google.com:80").resolve(false);
} |
public static String explainPlanFor(String sqlRequest) throws SQLException, NamingException {
final Connection connection = getConnection();
if (connection != null) {
try {
final Database database = Database.getDatabaseForConnection(connection);
if (database == Database.ORACLE) {
// Si oracle, on de... | @Test
public void testExplainPlanFor() throws SQLException, NamingException {
DatabaseInformations.explainPlanFor("select 1");
} |
@Override
public Set<ModelLocalUriId> getModelLocalUriIdsForFile() {
Set<ModelLocalUriId> localUriIds = localUriIdKeySet();
String matchingBase = SLASH + fileNameNoSuffix;
return localUriIds.stream().filter(modelLocalUriId -> modelLocalUriId.basePath().startsWith(matchingBase)).collect(Colle... | @Test
void getModelLocalUriIdsForFile() {
String path = "/pmml/" + fileName + "/testmod";
LocalUri parsed = LocalUri.parse(path);
ModelLocalUriId modelLocalUriId = new ModelLocalUriId(parsed);
pmmlCompilationContext.addGeneratedClasses(modelLocalUriId, compiledClasses);
Set<M... |
private <T> RestResponse<T> get(final String path, final Class<T> type) {
return executeRequestSync(HttpMethod.GET,
path,
null,
r -> deserialize(r.getBody(), type),
Optional.empty());
} | @Test
public void shouldPostQueryRequest_chunkHandler() {
ksqlTarget = new KsqlTarget(httpClient, socketAddress, localProperties, authHeader, HOST,
Collections.emptyMap(), RequestOptions.DEFAULT_TIMEOUT);
executor.submit(this::expectPostQueryRequestChunkHandler);
assertThatEventually(requestStarte... |
public static List<Event> computeEventDiff(final Params params) {
final List<Event> events = new ArrayList<>();
emitPerNodeDiffEvents(createBaselineParams(params), events);
emitWholeClusterDiffEvent(createBaselineParams(params), events);
emitDerivedBucketSpaceStatesDiffEvents(params, ev... | @Test
void cluster_event_is_tagged_with_given_time() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
.currentTimeMs(56789);
final List... |
public static byte[] hexStringToByteArray(final String s) {
if (s == null) {
return null;
}
final int len = s.length();
final byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
bytes[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4... | @Test
public void testHexStringToByteArray() {
Assert.assertNull(BytesUtil.hexStringToByteArray(null));
Assert.assertArrayEquals(new byte[] { -17, -5 }, BytesUtil.hexStringToByteArray("foob"));
} |
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if (StringUtils.isBlank(msg)) {
ctx.writeAndFlush(QosProcessHandler.PROMPT);
} else {
CommandContext commandContext = TelnetCommandDecoder.decode(msg);
commandContext.... | @Test
void testGreeting() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(),
QosConfiguration.builder()
.anonymousAccessP... |
@Override
public void importFrom(Import theImport, String sourceSystemId) {
this.namespace = theImport.getNamespace() == null ? "" : theImport.getNamespace() + ":";
this.importFrom(theImport.getLocation());
} | @Test
public void testImportInheritedElement() throws Exception {
URL url = ReflectUtil.getResource("org/flowable/engine/impl/webservice/inherited-elements-in-types.wsdl");
assertThat(url).isNotNull();
importer.importFrom(url.toString());
List<StructureDefinition> structures = sortS... |
public static <T> List<T> notNullElements(List<T> list, String name) {
notNull(list, name);
for (int i = 0; i < list.size(); i++) {
notNull(list.get(i), MessageFormat.format("list [{0}] element [{1}]", name, i));
}
return list;
} | @Test(expected = IllegalArgumentException.class)
public void notNullElementsNullList() {
Check.notNullElements(null, "name");
} |
@VisibleForTesting
ZonedDateTime parseZoned(final String text, final ZoneId zoneId) {
final TemporalAccessor parsed = formatter.parse(text);
final ZoneId parsedZone = parsed.query(TemporalQueries.zone());
ZonedDateTime resolved = DEFAULT_ZONED_DATE_TIME.apply(
ObjectUtils.defaultIfNull(parsedZone... | @Test
public void shouldResolveDefaultsForPartial() {
// Given
final String format = "yyyy";
final String timestamp = "2019";
// When
final ZonedDateTime ts = new StringToTimestampParser(format).parseZoned(timestamp, ZID);
// Then
assertThat(ts, is(sameInstant(EPOCH.withYear(2019).withZo... |
@Override
public void stopTrackingAndReleaseJobPartitions(
Collection<ResultPartitionID> partitionsToRelease) {
LOG.debug("Releasing Job Partitions {}", partitionsToRelease);
if (partitionsToRelease.isEmpty()) {
return;
}
stopTrackingPartitions(partitionsToRe... | @Test
void testStopTrackingAndReleaseJobPartitions() throws Exception {
final TestingShuffleEnvironment testingShuffleEnvironment = new TestingShuffleEnvironment();
final CompletableFuture<Collection<ResultPartitionID>> shuffleReleaseFuture =
new CompletableFuture<>();
testin... |
private static VerificationResult verifyChecksums(String expectedDigest, String actualDigest, boolean caseSensitive) {
if (expectedDigest == null) {
return VerificationResult.NOT_PROVIDED;
}
if (actualDigest == null) {
return VerificationResult.NOT_COMPUTED;
}
... | @Test
public void sha1DoesNotIgnoreCase() {
final Exception ex = assertThrows(Exception.class, () -> UpdateCenter.verifyChecksums(
new MockDownloadJob(EMPTY_SHA1, EMPTY_SHA256, EMPTY_SHA512),
buildEntryWithExpectedChecksums(EMPTY_SHA1.toUpperCase(Locale.US), null, null), new ... |
public void insert(int key, int value) {
GHIntHashSet set = map.get(value);
if (set == null) {
map.put(value, set = new GHIntHashSet(slidingMeanValue));
}
// else
// slidingMeanValue = Math.max(5, (slidingMeanValue + set.size()) / 2);
if (!set.add(key)) {
... | @Test
public void testInsert() {
GHSortedCollection instance = new GHSortedCollection();
assertTrue(instance.isEmpty());
instance.insert(0, 10);
assertEquals(1, instance.getSize());
assertEquals(10, instance.peekValue());
assertEquals(0, instance.peekKey());
i... |
@Override
public Charset detect(InputStream input, Metadata metadata) throws IOException {
input.mark(MAX_BYTES);
byte[] bytes = new byte[MAX_BYTES];
try {
int numRead = IOUtils.read(input, bytes);
if (numRead < MIN_BYTES) {
return null;
} ... | @Test
public void testBasic() throws Exception {
EncodingDetector detector = new BOMDetector();
for (ByteOrderMark bom : new ByteOrderMark[]{
ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE,
ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_32LE
})... |
public void addCacheConfig(CacheConfig cacheConfig) {
configs.add(cacheConfig);
} | @Test
public void test_cachePostJoinOperationFails_whenJCacheNotAvailable_withCacheConfigs() {
// JCache is not available in classpath
OnJoinCacheOperation onJoinCacheOperation = createTestOnJoinCacheOperation(false);
// some CacheConfigs are added in the OnJoinCacheOperation (so JCache is a... |
public static String getAddress(ECKeyPair ecKeyPair) {
return getAddress(ecKeyPair.getPublicKey());
} | @Test
public void testGetAddressZeroPadded() {
byte[] address =
Keys.getAddress(
Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE));
String expected = Numeric.toHexStringNoPrefix(address);
String value = "1234";
assertEqu... |
public static <V, F extends Future<V>> F cascade(final F future, final Promise<? super V> promise) {
return cascade(true, future, promise);
} | @Test
public void testCancelPropagationWhenFusedFromFuture() {
Promise<Void> p1 = ImmediateEventExecutor.INSTANCE.newPromise();
Promise<Void> p2 = ImmediateEventExecutor.INSTANCE.newPromise();
Promise<Void> returned = PromiseNotifier.cascade(p1, p2);
assertSame(p1, returned);
... |
@Override
public Optional<String> getContentHash() {
return Optional.ofNullable(mContentHash);
} | @Test
public void writeByteArrayForLargeFile() throws Exception {
int partSize = (int) FormatUtils.parseSpaceSize(PARTITION_SIZE);
byte[] b = new byte[partSize + 1];
assertEquals(mStream.getPartNumber(), 1);
mStream.write(b, 0, b.length);
assertEquals(mStream.getPartNumber(), 2);
Mockito.verif... |
@Udf
public String elt(
@UdfParameter(description = "the nth element to extract") final int n,
@UdfParameter(description = "the strings of which to extract the nth") final String... args
) {
if (args == null) {
return null;
}
if (n < 1 || n > args.length) {
return null;
}
... | @Test
public void shouldHandleNoArgs() {
// When:
final String el = elt.elt(2);
// Then:
assertThat(el, is(nullValue()));
} |
@Override
public IndexRange get(String index) throws NotFoundException {
final DBQuery.Query query = DBQuery.and(
DBQuery.notExists("start"),
DBQuery.is(IndexRange.FIELD_INDEX_NAME, index));
final MongoIndexRange indexRange = collection.findOne(query);
if (ind... | @Test(expected = NotFoundException.class)
@MongoDBFixtures("MongoIndexRangeServiceTest-LegacyIndexRanges.json")
public void getIgnoresLegacyIndexRange() throws Exception {
indexRangeService.get("graylog_0");
} |
@Override public Repository getRepository() {
IPentahoSession session = pentahoSessionSupplier.get();
if ( session == null ) {
LOGGER.debug( "No active Pentaho Session, attempting to load PDI repository unauthenticated." );
return null;
}
ICacheManager cacheManager = cacheManagerFunction.app... | @Test
public void testGetRepositoryNullSession() {
when( pentahoSessionSupplier.get() ).thenReturn(null );
assertNull( pentahoSessionHolderRepositoryProvider.getRepository() );
} |
synchronized boolean tryToMoveTo(State to) {
boolean res = false;
State currentState = state;
if (TRANSITIONS.get(currentState).contains(to)) {
this.state = to;
res = true;
listeners.forEach(listener -> listener.onProcessState(processId, to));
}
LOG.debug("{} tryToMoveTo {} from {}... | @Test
@UseDataProvider("allStates")
public void no_state_can_not_move_to_itself(State state) {
assertThat(newLifeCycle(state).tryToMoveTo(state)).isFalse();
} |
@Override
public SelJodaDateTime assignOps(SelOp op, SelType rhs) {
if (op == SelOp.ASSIGN) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
this.val = ((SelJodaDateTime) rhs).val;
return this;
}
throw new UnsupportedOperationException(type() + " DO NOT support assignment operation... | @Test
public void assignOps() {
one.assignOps(SelOp.ASSIGN, another);
assertEquals("DATETIME: 2019-01-01T00:00:00.000Z", one.type() + ": " + one);
} |
public static <T> Comparator<T> comparingPinyin(Function<T, String> keyExtractor) {
return comparingPinyin(keyExtractor, false);
} | @Test
public void comparingPinyin() {
List<String> list = ListUtil.toList("成都", "北京", "上海", "深圳");
List<String> ascendingOrderResult = ListUtil.of("北京", "成都", "上海", "深圳");
List<String> descendingOrderResult = ListUtil.of("深圳", "上海", "成都", "北京");
// 正序
list.sort(CompareUtil.comparingPinyin(e -> e));
asser... |
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") // Not a bug
synchronized CompletableFuture<Void> getFutureForSequenceNumber(final long seqNum) {
if (seqNum <= lastCompletedSequenceNumber) {
return CompletableFuture.completedFuture(null);
}
return sequenceNumberFutures.computeIfAbsent(seqNum, k ->... | @Test
public void shouldReturnFutureForExistingSequenceNumber() {
// Given:
final CompletableFuture<Void> existingFuture = futureStore.getFutureForSequenceNumber(2);
// When:
final CompletableFuture<Void> newFuture = futureStore.getFutureForSequenceNumber(2);
// Then:
assertThat(newFuture, i... |
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
String methodName = RpcUtils.getMethodName(invocation);
int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0);
final RpcStatus rpcStatus = R... | @Test
void testInvokeLessActives() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=10");
Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
activeLimitFilter.inv... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testKreearra()
{
ChatMessage chatMessageEvent = new ChatMessage(null, GAMEMESSAGE, "", "Your Kree'arra kill count is: <col=ff0000>4</col>.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessageEvent);
verify(configManager).setRSProfileConfiguration("killcount", "kree'arra", 4);
} |
@Override
public String toString() {
String feedBlockedStr = clusterFeedIsBlocked()
? String.format(", feed blocked: '%s'", feedBlock.description)
: "";
String distributionConfigStr = (distributionConfig != null)
? ", distribution config: %s".formatted... | @Test
void toString_includes_all_bucket_space_states() {
ClusterStateBundle bundle = createTestBundle();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
"global 'distributor:2 stor... |
@Override
public Long createDictData(DictDataSaveReqVO createReqVO) {
// 校验字典类型有效
validateDictTypeExists(createReqVO.getDictType());
// 校验字典数据的值的唯一性
validateDictDataValueUnique(null, createReqVO.getDictType(), createReqVO.getValue());
// 插入字典类型
DictDataDO dictData = ... | @Test
public void testCreateDictData_success() {
// 准备参数
DictDataSaveReqVO reqVO = randomPojo(DictDataSaveReqVO.class,
o -> o.setStatus(randomCommonStatus()))
.setId(null); // 防止 id 被赋值
// mock 方法
when(dictTypeService.getDictType(eq(reqVO.getDictType()... |
public void validate(ExternalIssueReport report, Path reportPath) {
if (report.rules != null && report.issues != null) {
Set<String> ruleIds = validateRules(report.rules, reportPath);
validateIssuesCctFormat(report.issues, ruleIds, reportPath);
} else if (report.rules == null && report.issues != nul... | @Test
public void validate_whenMissingMessageFieldForPrimaryLocation_shouldThrowException() throws IOException {
ExternalIssueReport report = read(REPORTS_LOCATION);
report.issues[0].primaryLocation.message = null;
assertThatThrownBy(() -> validator.validate(report, reportPath))
.isInstanceOf(Illeg... |
static SortKey[] rangeBounds(
int numPartitions, Comparator<StructLike> comparator, SortKey[] samples) {
// sort the keys first
Arrays.sort(samples, comparator);
int numCandidates = numPartitions - 1;
SortKey[] candidates = new SortKey[numCandidates];
int step = (int) Math.ceil((double) sample... | @Test
public void testRangeBoundsSkipDuplicates() {
// step is 3 = ceiling(11/4)
assertThat(
SketchUtil.rangeBounds(
4,
SORT_ORDER_COMPARTOR,
new SortKey[] {
CHAR_KEYS.get("a"),
CHAR_KEYS.get("b"),
... |
public DoubleArrayAsIterable usingTolerance(double tolerance) {
return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_contains_nullExpected() {
expectFailureWhenTestingThat(array(1.1, 2.2, 3.3))
.usingTolerance(DEFAULT_TOLERANCE)
.contains(null);
assertFailureKeys(
"value of",
"expected to contain",
"testing whether",
"but was",
"additio... |
void createOutputValueMapping() throws KettleException {
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields( getInputRowMeta(), getStepname(), null, null, this, repository, metaStore );
data.fieldIndex = getInputRowMeta().indexOfValue( meta.getFieldname() );
if ( data.fieldIndex < 0 ) {
... | @Test
public void testCreateOutputValueMappingWithBinaryType() throws KettleException, URISyntaxException,
ParserConfigurationException, SAXException, IOException {
SwitchCaseCustom krasavez = new SwitchCaseCustom( mockHelper );
// load step info value-case mapping from xml.
List<DatabaseMeta> emptyL... |
public static Object[] realize(Object[] objs, Class<?>[] types) {
if (objs.length != types.length) {
throw new IllegalArgumentException("args.length != types.length");
}
Object[] dests = new Object[objs.length];
for (int i = 0; i < objs.length; i++) {
dests[i] = ... | @Test
void testRealize() throws Exception {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Object obj = PojoUtils.generalize(map);
assertTrue(obj instanceof LinkedHashMap);
Object outputObject = PojoUtils.realize(map, LinkedHashMap.cla... |
public static ActiveRuleKey parse(String s) {
Preconditions.checkArgument(s.split(":").length >= 3, "Bad format of activeRule key: " + s);
int semiColonPos = s.indexOf(':');
String ruleProfileUuid = s.substring(0, semiColonPos);
String ruleKey = s.substring(semiColonPos + 1);
return new ActiveRuleKe... | @Test
void parse_fail_when_less_than_three_colons() {
try {
ActiveRuleKey.parse("P1:xoo");
Assertions.fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Bad format of activeRule key: P1:xoo");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.