focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static <T> CompressedSource<T> from(FileBasedSource<T> sourceDelegate) {
return new CompressedSource<>(sourceDelegate, CompressionMode.AUTO);
} | @Test
public void testUnsplittable() throws IOException {
String baseName = "test-input";
File compressedFile = tmpFolder.newFile(baseName + ".gz");
byte[] input = generateInput(10000);
writeFile(compressedFile, input, Compression.GZIP);
CompressedSource<Byte> source =
CompressedSource.fr... |
@Override
protected void handleEndTxn(CommandEndTxn command) {
checkArgument(state == State.Connected);
final long requestId = command.getRequestId();
final int txnAction = command.getTxnAction().getValue();
TxnID txnID = new TxnID(command.getTxnidMostBits(), command.getTxnidLeastBit... | @Test(expectedExceptions = IllegalArgumentException.class)
public void shouldFailHandleEndTxn() throws Exception {
ServerCnx serverCnx = mock(ServerCnx.class, CALLS_REAL_METHODS);
Field stateUpdater = ServerCnx.class.getDeclaredField("state");
stateUpdater.setAccessible(true);
stateU... |
@Override
public int partition(Integer bucketId, int numPartitions) {
Preconditions.checkNotNull(bucketId, BUCKET_NULL_MESSAGE);
Preconditions.checkArgument(bucketId >= 0, BUCKET_LESS_THAN_LOWER_BOUND_MESSAGE, bucketId);
Preconditions.checkArgument(
bucketId < maxNumBuckets, BUCKET_GREATER_THAN_UP... | @Test
public void testPartitionerBucketIdOutOfRangeFail() {
PartitionSpec partitionSpec = TableSchemaType.ONE_BUCKET.getPartitionSpec(DEFAULT_NUM_BUCKETS);
BucketPartitioner bucketPartitioner = new BucketPartitioner(partitionSpec);
int negativeBucketId = -1;
assertThatExceptionOfType(IllegalArgumentE... |
@PostMapping("/authorize")
@Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@Parameters({
@Parameter(name = "response_type", required = true, description = "响应类型", example = "code"),
@Parameter(name = "client_id", required = true, descr... | @Test // autoApprove = false,通过 + code
public void testApproveOrDeny_approveWithCode() {
// 准备参数
String responseType = "code";
String clientId = randomString();
String scope = "{\"read\": true, \"write\": false}";
String redirectUri = "https://www.iocoder.cn";
String ... |
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("Xoo Significant Code Ranges Sensor")
.onlyOnLanguages(Xoo.KEY);
} | @Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
} |
@Override
public List<PartitionKey> getPrunedPartitions(Table table, ScalarOperator predicate, long limit, TableVersionRange version) {
IcebergTable icebergTable = (IcebergTable) table;
String dbName = icebergTable.getRemoteDbName();
String tableName = icebergTable.getRemoteTableName();
... | @Test
public void testTransformedPartitionPrune() {
IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG);
List<Column> columns = Lists.newArrayList(new Column("k1", INT), new Column("ts", DATETIME));
IcebergMetadata metadata = new ... |
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) {
return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive();
} | @Test
public void linearOneWay() {
// 0 -> 1 -> 2
g.edge(0, 1).setDistance(1).set(speedEnc, 10, 0);
g.edge(1, 2).setDistance(1).set(speedEnc, 10, 0);
ConnectedComponents result = EdgeBasedTarjanSCC.findComponentsRecursive(g, fwdAccessFilter, false);
assertEquals(4, result.get... |
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
if (varbitChanged.getVarpId() == VarPlayer.CANNON_AMMO)
{
int old = cballsLeft;
cballsLeft = varbitChanged.getValue();
if (cballsLeft > old)
{
cannonBallNotificationSent = false;
}
if (!cannonBallNotificationSent && cbal... | @Test
public void testThresholdNotificationShouldNotifyOnce()
{
when(config.showCannonNotifications()).thenReturn(Notification.ON);
when(config.lowWarningThreshold()).thenReturn(10);
for (int cballs = 15; cballs >= 8; --cballs)
{
cannonAmmoChanged.setValue(cballs);
plugin.onVarbitChanged(cannonAmmoChan... |
public void removeWorkerFromMap(long workerId, String workerIpPort) {
try (LockCloseable lock = new LockCloseable(rwLock.writeLock())) {
workerToNode.remove(workerId);
workerToId.remove(workerIpPort);
}
LOG.info("remove worker {} success from StarMgr", workerIpPort);
... | @Test
public void testRemoveWorkerFromMap() {
String workerHost = "127.0.0.1:8090";
Map<String, Long> mockWorkerToId = Maps.newHashMap();
mockWorkerToId.put(workerHost, 5L);
Deencapsulation.setField(starosAgent, "workerToId", mockWorkerToId);
Assert.assertEquals(5L, starosAge... |
public static Set<String> minus(Collection<String> list1, Collection<String> list2) {
HashSet<String> s1 = new HashSet<>(list1);
s1.removeAll(list2);
return s1;
} | @Test
public void testMinus() {
String topicName1 = "persistent://my-property/my-ns/pattern-topic-1";
String topicName2 = "persistent://my-property/my-ns/pattern-topic-2";
String topicName3 = "persistent://my-property/my-ns/pattern-topic-3";
String topicName4 = "persistent://my-prope... |
static boolean isFullWidth(int codePoint) {
int value = UCharacter.getIntPropertyValue(codePoint, UProperty.EAST_ASIAN_WIDTH);
switch (value) {
case UCharacter.EastAsianWidth.NEUTRAL:
case UCharacter.EastAsianWidth.AMBIGUOUS:
case UCharacter.EastAsianWidth.HALFWIDTH:
... | @Test
void testCharFullWidth() {
char[] chars = new char[] {'A', 'a', ',', '中', ',', 'こ'};
boolean[] expected = new boolean[] {false, false, false, true, true, true};
for (int i = 0; i < chars.length; i++) {
assertThat(TableauStyle.isFullWidth(Character.codePointAt(chars, i)))
... |
@VisibleForTesting
void forceFreeMemory()
{
memoryManager.close();
} | @Test
public void testForceFreeMemory()
throws Throwable
{
PartitionedOutputBuffer buffer = createPartitionedBuffer(
createInitialEmptyOutputBuffers(PARTITIONED)
.withBuffer(FIRST, 0)
.withNoMoreBufferIds(),
size... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testIntegerNotIn() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, notIn("id", INT_MIN_VALUE - 25, INT_MIN_VALUE - 24))
.eval(FILE);
assertThat(shouldRead).as("Should read: id below lower bound (5 < 30, 6 < 30)").isTrue();
shouldRead =
new Inclus... |
public static String getServiceName(NetworkService networkService) {
if (isWebService(networkService) && networkService.hasSoftware()) {
return Ascii.toLowerCase(networkService.getSoftware().getName());
}
return Ascii.toLowerCase(networkService.getServiceName());
} | @Test
public void getServiceName_whenNonWebService_returnsServiceName() {
assertThat(
NetworkServiceUtils.getServiceName(
NetworkService.newBuilder()
.setNetworkEndpoint(forIpAndPort("127.0.0.1", 22))
.setServiceName("ssh")
.b... |
@Override
public Type classify(final Throwable e) {
Type type = Type.UNKNOWN;
if (e instanceof KsqlSerializationException
|| (e instanceof StreamsException
&& (ExceptionUtils.indexOfThrowable(e, KsqlSerializationException.class) != -1))) {
if (!hasInternalTopicPrefix(e)) {
t... | @Test
public void shouldClassifyKsqlSerializationExceptionWithRepartitionTopicAsUnknownError() {
// Given:
final String topic = "_confluent-ksql-default_query_CTAS_USERS_0-Aggregate-GroupBy-repartition";
final Exception e = new KsqlSerializationException(
topic,
"Error serializing message ... |
public H3IndexResolution getResolution() {
return _resolution;
} | @Test
public void withDisabledFalse()
throws JsonProcessingException {
String confStr = "{\"disabled\": false}";
H3IndexConfig config = JsonUtils.stringToObject(confStr, H3IndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
assertNull(config.getResolution(), "Unexpected... |
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
advance(length);
super.characters(ch, start, length);
} | @Test
public void testTenCharactersPerByte() throws IOException {
try {
char[] ch = new char[10];
for (int i = 0; i < MANY_BYTES; i++) {
stream.read();
handler.characters(ch, 0, ch.length);
}
} catch (SAXException e) {
f... |
@Override
public ImagesAndRegistryClient call()
throws IOException, RegistryException, LayerPropertyNotFoundException,
LayerCountMismatchException, BadContainerConfigurationFormatException,
CacheCorruptedException, CredentialRetrievalException {
EventHandlers eventHandlers = buildContext... | @Test
public void testCall_allMirrorsFail()
throws InvalidImageReferenceException, IOException, RegistryException,
LayerPropertyNotFoundException, LayerCountMismatchException,
BadContainerConfigurationFormatException, CacheCorruptedException,
CredentialRetrievalException {
Mock... |
public RestException(Response.Status status, String message) {
this(status.getStatusCode(), message);
} | @Test
public void testRestException() {
RestException re = new RestException(Status.TEMPORARY_REDIRECT, "test rest exception");
RestException testException = new RestException(re);
assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), testException.getResponse().getStatus());
asse... |
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
if (remaining.split("/").length > 1) {
throw new IllegalArgumentException("Invalid URI: " + URISupport.sanitizeUri(uri));
}
SplunkHECEndpoint answer = new... | @Test
public void testTokenValid() throws Exception {
SplunkHECEndpoint endpoint = (SplunkHECEndpoint) component.createEndpoint(
"splunk-hec:localhost:18808?token=11111111-1111-1111-1111-111111111111");
endpoint.init();
assertEquals("11111111-1111-1111-1111-111111111111", end... |
public SourceWithMetadata lookupSource(int globalLineNumber, int sourceColumn)
throws IncompleteSourceWithMetadataException {
LineToSource lts = this.sourceReferences().stream()
.filter(lts1 -> lts1.includeLine(globalLineNumber))
.findFirst()
.orElseTh... | @Test
public void testSourceAndLineRemapping_pipelineDefinedInSingleFileMultiLine() throws IncompleteSourceWithMetadataException {
final SourceWithMetadata swm = new SourceWithMetadata("file", "/tmp/1", 0, 0, PIPELINE_CONFIG_PART_1);
sut = new PipelineConfig(source, pipelineIdSym, toRubyArray(new So... |
public CharSequence format(Monetary monetary) {
// determine maximum number of decimals that can be visible in the formatted string
// (if all decimal groups were to be used)
int max = minDecimals;
if (decimalGroups != null)
for (int group : decimalGroups)
max... | @Test
public void uBtcRounding() {
assertEquals("0", format(ZERO, 6, 0));
assertEquals("0.00", format(ZERO, 6, 2));
assertEquals("1000000", format(COIN, 6, 0));
assertEquals("1000000", format(COIN, 6, 0, 2));
assertEquals("1000000.0", format(COIN, 6, 1));
assertEqual... |
static void setDefaultEnsemblePlacementPolicy(
ClientConfiguration bkConf,
ServiceConfiguration conf,
MetadataStore store
) {
bkConf.setProperty(BookieRackAffinityMapping.METADATA_STORE_INSTANCE, store);
if (conf.isBookkeeperClientRackawarePolicyEnabled() || conf... | @Test
public void testSetDefaultEnsemblePlacementPolicyRackAwareEnabled() {
ClientConfiguration bkConf = new ClientConfiguration();
ServiceConfiguration conf = new ServiceConfiguration();
MetadataStore store = mock(MetadataStore.class);
assertNull(bkConf.getProperty(REPP_ENABLE_VALI... |
@Override
public final void run() {
long valueCount = collector.getMergingValueCount();
if (valueCount == 0) {
return;
}
runInternal();
assert operationCount > 0 : "No merge operations have been invoked in AbstractContainerMerger";
try {
lon... | @Test
@RequireAssertEnabled
@Category(SlowTest.class)
public void testMergerRun_whenMergeOperationBlocks_thenMergerFinishesEventually() {
TestMergeOperation operation = new TestMergeOperation(BLOCKS);
TestContainerMerger merger = new TestContainerMerger(collector, nodeEngine, operation);
... |
public static void isTrue(boolean expression, String message) {
if (expression == false) {
throw new IllegalArgumentException(message);
}
} | @Test
public void testIsTrueThrow() {
Assertions.assertThrows(IllegalArgumentException.class, () -> Utils.isTrue(false, "foo"));
} |
public static Ip6Prefix valueOf(byte[] address, int prefixLength) {
return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength);
} | @Test
public void testContainsIpAddressIPv6() {
Ip6Prefix ipPrefix;
ipPrefix = Ip6Prefix.valueOf("1111:2222:3333:4444::/120");
assertTrue(ipPrefix.contains(
Ip6Address.valueOf("1111:2222:3333:4444::")));
assertTrue(ipPrefix.contains(
Ip6Address.valueO... |
public static void invoke(Object instance, String methodName)
throws SecurityException, IllegalArgumentException, JMeterException
{
Method m;
try {
m = ClassUtils.getPublicMethod(instance.getClass(), methodName, new Class [] {});
m.invoke(instance, (Object [])null);
... | @Test
public void testInvoke() throws Exception {
Dummy dummy = new Dummy();
ClassTools.invoke(dummy, "callMe");
assertTrue(dummy.wasCalled());
} |
@GET
@Path("/entity-uid/{uid}/")
@Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8)
public TimelineEntity getEntity(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@PathParam("uid") String uId,
@QueryParam("confstoretrieve") String confsToRetrieve,
@Q... | @Test
void testGetEntityDefaultView() throws Exception {
Client client = createClient();
try {
URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/" +
"timeline/clusters/cluster1/apps/app1/entities/app/id_1");
ClientResponse resp = getResponse(client, uri);
TimelineEnti... |
public static boolean matches(MetricsFilter filter, MetricKey key) {
if (filter == null) {
return true;
}
@Nullable String stepName = key.stepName();
if (stepName == null) {
if (!filter.steps().isEmpty()) {
// The filter specifies steps, but the metric is not associated with a step.... | @Test
public void testMatchStringNamespaceFilters() {
// MetricsFilter with a String-namespace + name filter. Without step filter.
// Successful match.
assertTrue(
MetricFiltering.matches(
MetricsFilter.builder()
.addNameFilter(MetricNameFilter.named("myNamespace", "myM... |
public static Type convertType(TypeInfo typeInfo) {
switch (typeInfo.getOdpsType()) {
case BIGINT:
return Type.BIGINT;
case INT:
return Type.INT;
case SMALLINT:
return Type.SMALLINT;
case TINYINT:
ret... | @Test
public void testConvertTypeCaseBinary() {
TypeInfo typeInfo = TypeInfoFactory.BINARY;
Type result = EntityConvertUtils.convertType(typeInfo);
assertEquals(Type.VARBINARY, result);
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateBetween() {
// Given:
final Expression expression1 = new BetweenPredicate(
new IntegerLiteral(4), new IntegerLiteral(3), new IntegerLiteral(8)
);
final Expression expression2 = new BetweenPredicate(
new IntegerLiteral(0), new IntegerLiteral(3), new Integ... |
@Override
public void deactivate(String id, Boolean anonymize) {
userSession.checkLoggedIn().checkIsSystemAdministrator();
checkRequest(!id.equals(userSession.getUuid()), "Self-deactivation is not possible");
userService.deactivate(id, anonymize);
} | @Test
public void deactivate_whenAnonymizeIsNotSpecified_shouldDeactivateUserWithoutAnonymization() throws Exception {
userSession.logIn().setSystemAdministrator();
mockMvc.perform(delete(USER_ENDPOINT + "/userToDelete"))
.andExpect(status().isNoContent());
verify(userService).deactivate("userToDe... |
@Deprecated
@VisibleForTesting
static native void nativeVerifyChunkedSums(
int bytesPerSum, int checksumType,
ByteBuffer sums, int sumsOffset,
ByteBuffer data, int dataOffset, int dataLength,
String fileName, long basePos) throws ChecksumException; | @Test
@SuppressWarnings("deprecation")
public void testNativeVerifyChunkedSumsSuccess() throws ChecksumException {
allocateDirectByteBuffers();
fillDataAndValidChecksums();
NativeCrc32.nativeVerifyChunkedSums(bytesPerChecksum, checksumType.id,
checksums, checksums.position(), data, data.position()... |
public static String post(HttpURLConnection con,
Map<String, String> headers,
String requestBody,
Integer connectTimeoutMs,
Integer readTimeoutMs)
throws IOException, UnretryableException {
handleInput(con, headers, requestBody, connectTimeoutMs, readTimeoutMs);
r... | @Test
public void testErrorResponseIsInvalidJson() throws IOException {
HttpURLConnection mockedCon = createHttpURLConnection("dummy");
when(mockedCon.getInputStream()).thenThrow(new IOException("Can't read"));
when(mockedCon.getErrorStream()).thenReturn(new ByteArrayInputStream(
... |
public static HttpRequest toNettyRequest(RestRequest request) throws Exception
{
HttpMethod nettyMethod = HttpMethod.valueOf(request.getMethod());
URL url = new URL(request.getURI().toString());
String path = url.getFile();
// RFC 2616, section 5.1.2:
// Note that the absolute path cannot be emp... | @Test
public void testRestToNettyRequestWithMultipleCookies() throws Exception
{
RestRequestBuilder restRequestBuilder = new RestRequestBuilder(new URI(ANY_URI));
restRequestBuilder.setCookies(ANY_COOKIES);
RestRequest restRequest = restRequestBuilder.build();
HttpRequest nettyRequest = NettyReque... |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
if(proxy.isSupported(source, target)) {
return proxy.copy(source, target, status, callback, listener);
... | @Test
public void testCopyFileWithRename() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.T... |
@Override
public void transitionToActive(final StreamTask streamTask, final RecordCollector recordCollector, final ThreadCache newCache) {
if (stateManager.taskType() != TaskType.ACTIVE) {
throw new IllegalStateException("Tried to transition processor context to active but the state manager's " ... | @Test
public void localTimestampedKeyValueStoreShouldNotAllowInitOrClose() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.getGlobalStore(anyString())).thenReturn(null);
final TimestampedKeyValueStore<String, Long> timestampedKeyValueS... |
public static HashSet<String> expand(String val) {
HashSet<String> set = new HashSet<>();
Matcher matcher = NUMERIC_RANGE_PATTERN.matcher(val);
if (!matcher.matches()) {
set.add(val);
return set;
}
String prequel = matcher.group(1);
String rangeSta... | @Test
public void testNoExpansionNeeded() {
assertEquals(Collections.singleton("foo"), StringExpander.expand("foo"));
assertEquals(Collections.singleton("bar"), StringExpander.expand("bar"));
assertEquals(Collections.singleton(""), StringExpander.expand(""));
} |
public static void checkNotNull(Object o) {
if (o == null) {
throw new NullPointerException();
}
} | @Test
public void testPreconditionsNull(){
Preconditions.checkNotNull("");
try{
Preconditions.checkNotNull(null);
} catch (NullPointerException e){
assertNull(e.getMessage());
}
Preconditions.checkNotNull("", "Message %s here", 10);
try{
... |
public Span nextSpan(Message message) {
TraceContextOrSamplingFlags extracted =
extractAndClearTraceIdProperties(processorExtractor, message, message);
Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler.
// When an upstream context was not present, lookup keys are unl... | @Test void nextSpan_prefers_b3_header() {
TraceContext incoming = newTraceContext(SamplingFlags.NOT_SAMPLED);
setStringProperty(message, "b3", B3SingleFormat.writeB3SingleFormat(incoming));
Span child;
try (Scope scope = tracing.currentTraceContext().newScope(parent)) {
child = jmsTracing.nextSpa... |
@Override
public void readFully(final byte[] b) throws IOException {
if (read(b) == -1) {
throw new EOFException("End of stream reached");
}
} | @Test
public void testReadFullyForBOffLen() throws Exception {
byte[] readFull = new byte[10];
in.readFully(readFull, 0, 5);
for (int i = 0; i < 5; i++) {
assertEquals(readFull[i], in.data[i]);
}
} |
@Override
public boolean isOperator() {
if (expression != null) {
return expression.isOperator();
}
return false;
} | @Test
public void isOperator() {
when(expr.isAction()).thenReturn(true).thenReturn(false);
assertTrue(test.isAction());
assertFalse(test.isAction());
verify(expr, times(2)).isAction();
verifyNoMoreInteractions(expr);
} |
public long getTableOffset() {
return table_offset;
} | @Test
public void testGetTableOffset() {
assertEquals(TestParameters.VP_TBL_OFFSET, chmLzxcResetTable.getTableOffset());
} |
public synchronized long run(JobConfig jobConfig)
throws JobDoesNotExistException, ResourceExhaustedException {
long jobId = getNewJobId();
run(jobConfig, jobId);
return jobId;
} | @Test
public void runNonExistingJobConfig() throws Exception {
try {
mJobMaster.run(new DummyPlanConfig());
Assert.fail("cannot run non-existing job");
} catch (JobDoesNotExistException e) {
Assert.assertEquals(ExceptionMessage.JOB_DEFINITION_DOES_NOT_EXIST.getMessage("dummy"),
e.g... |
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateFloatingIp(@PathParam("id") String id, InputStream input) throws IOException {
log.trace(String.format(MESSAGE, "UPDATE " + id));
String inputStr = IOUtils.toString(input... | @Test
public void testUpdateFloatingIpWithUpdatingOperation() {
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
mockOpenstackRouterAdminService.updateFloatingIp(anyObject());
replay(mockOpenstackRouterAdminService);
final... |
public List<ChangeStreamRecord> toChangeStreamRecords(
PartitionMetadata partition,
ChangeStreamResultSet resultSet,
ChangeStreamResultSetMetadata resultSetMetadata) {
if (this.isPostgres()) {
// In PostgresQL, change stream records are returned as JsonB.
return Collections.singletonLi... | @Test
public void testMappingInsertJsonRowNewRowToDataChangeRecord() {
final DataChangeRecord dataChangeRecord =
new DataChangeRecord(
"partitionToken",
Timestamp.ofTimeSecondsAndNanos(10L, 20),
"transactionId",
false,
"1",
"tableName... |
@Override
public Object run() throws ZuulException {
// Exit the entries in order.
// The entries can be retrieved from the request context.
SentinelEntryUtils.tryExitFromCurrentContext();
return null;
} | @Test
public void testRun() throws Exception {
SentinelZuulPostFilter sentinelZuulPostFilter = new SentinelZuulPostFilter();
Object result = sentinelZuulPostFilter.run();
Assert.assertNull(result);
} |
@Override
public Input find(String id) throws NotFoundException {
if (!ObjectId.isValid(id)) {
throw new NotFoundException("Input id <" + id + "> is invalid!");
}
final DBObject o = get(org.graylog2.inputs.InputImpl.class, id);
if (o == null) {
throw new NotFo... | @Test
@MongoDBFixtures("InputServiceImplTest.json")
public void findReturnsExistingInput() throws NotFoundException {
final Input input = inputService.find("54e3deadbeefdeadbeef0002");
assertThat(input.getId()).isEqualTo("54e3deadbeefdeadbeef0002");
} |
@Override
public void invoke() throws Exception {
// --------------------------------------------------------------------
// Initialize
// --------------------------------------------------------------------
initInputFormat();
LOG.debug(getLogString("Start registering input ... | @Test
void testCancelDataSourceTask() throws IOException {
int keyCnt = 20;
int valCnt = 4;
super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE);
super.addOutput(new NirvanaOutputList());
File tempTestFile = new File(tempFolder.toFile(), UUID.randomUUID().toString... |
public static boolean isKafkaInvokeBySermant(StackTraceElement[] stackTrace) {
return isInvokeBySermant(KAFKA_CONSUMER_CLASS_NAME, KAFKA_CONSUMER_CONTROLLER_CLASS_NAME, stackTrace);
} | @Test
public void testInvokeBySermantWithNestedInvoke() {
StackTraceElement[] stackTrace = new StackTraceElement[5];
stackTrace[0] = new StackTraceElement("testClass0", "testMethod0", "testFileName0", 0);
stackTrace[1] = new StackTraceElement("testClass1", "testMethod1", "testFileName1", 1);... |
public PrefetchableIterable<T> get() {
checkState(
!isClosed,
"Bag user state is no longer usable because it is closed for %s",
request.getStateKey());
if (isCleared) {
// If we were cleared we should disregard old values.
return PrefetchableIterables.limit(Collections.unmodi... | @Test
public void testGet() throws Exception {
FakeBeamFnStateClient fakeClient =
new FakeBeamFnStateClient(
StringUtf8Coder.of(), ImmutableMap.of(key("A"), asList("A1", "A2", "A3")));
BagUserState<String> userState =
new BagUserState<>(
Caches.noop(), fakeClient, "inst... |
public static void addNumEntriesImmMemTablesMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
... | @Test
public void shouldAddNumEntriesImmutableMemTablesMetric() {
final String name = "num-entries-imm-mem-tables";
final String description = "Total number of entries in the unflushed immutable memtables";
runAndVerifyMutableMetric(
name,
description,
() ... |
public static <T> T getAnnotationValue(AnnotatedElement annotationEle, Class<? extends Annotation> annotationType) throws UtilException {
return getAnnotationValue(annotationEle, annotationType, "value");
} | @Test
public void getAnnotationValueTest() {
final Object value = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest.class);
assertTrue(value.equals("测试") || value.equals("repeat-annotation"));
} |
public void commitAsync(final Map<TopicIdPartition, Acknowledgements> acknowledgementsMap) {
final Cluster cluster = metadata.fetch();
final ResultHandler resultHandler = new ResultHandler(Optional.empty());
sessionHandlers.forEach((nodeId, sessionHandler) -> {
Node node = cluster.n... | @Test
public void testCommitAsync() {
buildRequestManager();
assignFromSubscribed(Collections.singleton(tp0));
// normal fetch
assertEquals(1, sendFetches());
assertFalse(shareConsumeRequestManager.hasCompletedFetches());
client.prepareResponse(fullFetchResponse(ti... |
@Override
public CompletableFuture<TxnOffsetCommitResponseData> commitTransactionalOffsets(
RequestContext context,
TxnOffsetCommitRequestData request,
BufferSupplier bufferSupplier
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(TxnOffsetCommitReq... | @Test
public void testCommitTransactionalOffsetsWhenNotStarted() throws ExecutionException, InterruptedException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
... |
public static PDImageXObject createFromByteArray(PDDocument document, byte[] byteArray, String name) throws IOException
{
FileType fileType = FileTypeDetector.detectFileType(byteArray);
if (fileType == null)
{
throw new IllegalArgumentException("Image type not supported: " + name... | @Test
void testCreateFromByteArray() throws IOException, URISyntaxException
{
testCompareCreatedFromByteArrayWithCreatedByCCITTFactory("ccittg4.tif");
testCompareCreatedFromByteArrayWithCreatedByJPEGFactory("jpeg.jpg");
testCompareCreatedFromByteArrayWithCreatedByJPEGFactory("jpegcmyk.j... |
@Override
public boolean equals(Object toBeCompared) {
if (toBeCompared instanceof ControllerInfo) {
ControllerInfo that = (ControllerInfo) toBeCompared;
return Objects.equals(this.type, that.type) &&
Objects.equals(this.ip, that.ip) &&
Objects... | @Test
public void testEquals() {
String target1 = "ptcp:6653:192.168.1.1";
ControllerInfo controllerInfo1 = new ControllerInfo(target1);
String target2 = "ptcp:6653:192.168.1.1";
ControllerInfo controllerInfo2 = new ControllerInfo(target2);
assertTrue("wrong equals method", c... |
public abstract MySqlSplit toMySqlSplit(); | @Test
public void testRecordBinlogSplitState() throws Exception {
final MySqlBinlogSplit split =
getTestBinlogSplitWithOffset(
BinlogOffset.ofBinlogFilePosition("mysql-bin.000001", 4));
final MySqlBinlogSplitState mySqlSplitState = new MySqlBinlogSplitState(... |
public SchemaMapping fromArrow(Schema arrowSchema) {
List<Field> fields = arrowSchema.getFields();
List<TypeMapping> parquetFields = fromArrow(fields);
MessageType parquetType =
addToBuilder(parquetFields, Types.buildMessage()).named("root");
return new SchemaMapping(arrowSchema, parquetType, pa... | @Test(expected = UnsupportedOperationException.class)
public void testArrowTimeSecondToParquet() {
converter
.fromArrow(new Schema(asList(field("a", new ArrowType.Time(TimeUnit.SECOND, 32)))))
.getParquetSchema();
} |
static BlockStmt getComplexPartialScoreVariableDeclaration(final String variableName, final ComplexPartialScore complexPartialScore) {
final MethodDeclaration methodDeclaration = COMPLEX_PARTIAL_SCORE_TEMPLATE.getMethodsByName(GETKIEPMMLCOMPLEXPARTIALSCORE).get(0).clone();
final BlockStmt complexPartial... | @Test
void getComplexPartialScoreVariableDeclarationWithFieldRef() throws IOException {
final String variableName = "variableName";
FieldRef fieldRef = new FieldRef();
fieldRef.setField("FIELD_REF");
ComplexPartialScore complexPartialScore = new ComplexPartialScore();
complex... |
@Override
public void collect(MetricsEmitter metricsEmitter) {
for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) {
MetricKey metricKey = entry.getKey();
KafkaMetric metric = entry.getValue();
try {
collectMetric(metricsEmitter, metricKey... | @Test
public void testCollectFilterWithDeltaTemporality() {
MetricName name1 = metrics.metricName("nonMeasurable", "group1", tags);
MetricName name2 = metrics.metricName("windowed", "group1", tags);
MetricName name3 = metrics.metricName("cumulative", "group1", tags);
metrics.addMetr... |
@Override
public MatchType convert(@NotNull String type) {
if (type.contains(DELIMITER)) {
String[] matchType = type.split(DELIMITER);
return new MatchType(RateLimitType.valueOf(matchType[0].toUpperCase()), matchType[1]);
}
return new MatchType(RateLimitType.valueOf(t... | @Test
public void testConvertStringTypeHttpMethodOnly() {
MatchType matchType = target.convert("http_method");
assertThat(matchType).isNotNull();
assertThat(matchType.getType()).isEqualByComparingTo(RateLimitType.HTTP_METHOD);
assertThat(matchType.getMatcher()).isNull();
} |
@Override
protected void verifyConditions(ScesimModelDescriptor scesimModelDescriptor,
ScenarioRunnerData scenarioRunnerData,
ExpressionEvaluatorFactory expressionEvaluatorFactory,
Map<String, Object> request... | @Test
public void verifyConditions_scenario1() {
List<InstanceGiven> scenario1Inputs = extractGivenValuesForScenario1();
List<ScenarioExpect> scenario1Outputs = runnerHelper.extractExpectedValues(scenario1.getUnmodifiableFactMappingValues());
ScenarioRunnerData scenarioRunnerData1 = new Sce... |
public Map<String, String> build() {
Map<String, String> builder = new HashMap<>();
configureFileSystem(builder);
configureNetwork(builder);
configureCluster(builder);
configureSecurity(builder);
configureOthers(builder);
LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]",
... | @Test
public void configureSecurity_givenClusterSearchPasswordProvided_addXpackParameters_file_exists() throws Exception {
Props props = minProps(true);
props.set(CLUSTER_SEARCH_PASSWORD.getKey(), "qwerty");
File keystore = temp.newFile("keystore.p12");
File truststore = temp.newFile("truststore.p12")... |
@Override
public void judgeContinueToExecute(final SQLStatement statement) throws SQLException {
ShardingSpherePreconditions.checkState(statement instanceof CommitStatement || statement instanceof RollbackStatement,
() -> new SQLFeatureNotSupportedException("Current transaction is aborted, c... | @Test
void assertJudgeContinueToExecuteWithNotAllowedStatement() {
assertThrows(SQLFeatureNotSupportedException.class, () -> allowedSQLStatementHandler.judgeContinueToExecute(mock(SelectStatement.class)));
} |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
if(!new LocalFindFeature(session).find(file)) {
throw new NotfoundException(file.getAbsolute());
... | @Test(expected = NotfoundException.class)
public void testMoveNotFound() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLogin... |
@Override
public KeyValues getLowCardinalityKeyValues(DubboClientContext context) {
KeyValues keyValues = super.getLowCardinalityKeyValues(context.getInvocation());
return withRemoteHostPort(keyValues, context);
} | @Test
void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("testMethod");
invocation.setAttachment("interface", "com.example.TestService");
invocation.setTargetServiceUniqu... |
public int estimateK(int k, int n) {
return (estimate && (n >= MIN_N))
? Math.min(k, (int)Math.ceil(estimateExactK(k, n, defaultP)))
: k;
} | @Test
void requireThatLargeKAreSane() {
// System.out.println(dumpProbability(10, 0.05));
TopKEstimator idealEstimator = new TopKEstimator(30, 0.9999);
TopKEstimator skewedEstimator = new TopKEstimator(30, 0.9999, 0.05);
int [] K = {10, 20, 40, 80, 100, 200, 400, 800, 1000, 2000, 400... |
@Override
protected boolean isAccessAllowed(final ServletRequest servletRequest,
final ServletResponse servletResponse,
final Object o) {
return false;
} | @Test
public void testIsAccessAllowed() {
Object obj = mock(Object.class);
assertFalse(statelessAuthFilter.isAccessAllowed(httpServletRequest, httpServletResponse, obj));
} |
@Override public Repository getRepository() {
try {
// NOTE: this class formerly used a ranking system to prioritize the providers registered and would check them in order
// of priority for the first non-null repository. In practice, we only ever registered one at a time, spoon or PUC.
// As suc... | @Test
public void testGetRepositorySingleNull() {
KettleRepositoryProvider provider = mock( KettleRepositoryProvider.class );
Collection<KettleRepositoryProvider> providerCollection = new ArrayList<>();
providerCollection.add( provider );
try ( MockedStatic<PluginServiceLoader> pluginServiceLoaderMock... |
public static Set<Class<? extends PipelineOptions>> getRegisteredOptions() {
return Collections.unmodifiableSet(CACHE.get().registeredOptions);
} | @Test
public void testDefaultRegistration() {
assertTrue(PipelineOptionsFactory.getRegisteredOptions().contains(PipelineOptions.class));
} |
@Override
public List<AdminUserDO> getUserList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return userMapper.selectBatchIds(ids);
} | @Test
public void testGetUserList() {
// mock 数据
AdminUserDO user = randomAdminUserDO();
userMapper.insert(user);
// 测试 id 不匹配
userMapper.insert(randomAdminUserDO());
// 准备参数
Collection<Long> ids = singleton(user.getId());
// 调用
List<AdminUser... |
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI.
public long parse(final String text) {
final String date;
final String time;
final String timezone;
if (text.contains("T")) {
date = text.substring(0, text.indexOf('T'));
final String withTimezone = text.substring(text.i... | @Test
public void shouldParseDateWithHourMinute() {
// When:
assertThat(parser.parse("2020-12-02T13:59"), is(fullParse("2020-12-02T13:59:00.000+0000")));
assertThat(parser.parse("2020-12-02T13:59Z"), is(fullParse("2020-12-02T13:59:00.000+0000")));
} |
public static Builder custom() {
return new Builder();
} | @Test(expected = IllegalArgumentException.class)
public void zeroSlidingWindowSizeShouldFail2() {
custom().slidingWindowSize(0).build();
} |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public void updateTenant(TenantSaveReqVO updateReqVO) {
// 校验存在
TenantDO tenant = validateUpdateTenant(updateReqVO.getId());
// 校验租户名称是否重复
validTenantNameDuplicate(updateReqVO.getName(), updateReqVO.getId());
... | @Test
public void testUpdateTenant_success() {
// mock 数据
TenantDO dbTenant = randomPojo(TenantDO.class, o -> o.setStatus(randomCommonStatus()));
tenantMapper.insert(dbTenant);// @Sql: 先插入出一条存在的数据
// 准备参数
TenantSaveReqVO reqVO = randomPojo(TenantSaveReqVO.class, o -> {
... |
protected List<Object> createAndFillList(ArrayNode json, List<Object> toReturn, String className, List<String> genericClasses) {
for (JsonNode node : json) {
if (isSimpleTypeNode(node)) {
String generic = genericClasses.get(genericClasses.size() - 1);
Object value = i... | @Test
public void convertList() {
ArrayNode jsonNodes = new ArrayNode(factory);
ObjectNode objectNode = new ObjectNode(factory);
objectNode.put(VALUE, "data");
jsonNodes.add(objectNode);
List<Object> objects = expressionEvaluator.createAndFillList(jsonNodes, new ArrayList<>(... |
public List<String> build() {
if (columnDefs.isEmpty()) {
throw new IllegalStateException("No column has been defined");
}
switch (dialect.getId()) {
case PostgreSql.ID:
return createPostgresQuery();
case Oracle.ID:
return createOracleQuery();
default:
return ... | @Test
public void update_columns_on_oracle() {
assertThat(createSampleBuilder(new Oracle()).build())
.containsOnly(
"ALTER TABLE issues MODIFY (value NUMERIC (30,20) NULL)",
"ALTER TABLE issues MODIFY (name VARCHAR2 (10 CHAR) NULL)");
} |
public static java.nio.file.Path getTargetPathIfContainsSymbolicPath(java.nio.file.Path path)
throws IOException {
java.nio.file.Path targetPath = path;
java.nio.file.Path suffixPath = Paths.get("");
while (path != null && path.getFileName() != null) {
if (Files.isSymboli... | @Test
void testGetTargetPathContainsMultipleSymbolicPath() throws IOException {
File linked1Dir = TempDirUtils.newFolder(temporaryFolder, "linked1");
java.nio.file.Path symlink1 = Paths.get(temporaryFolder.toString(), "symlink1");
Files.createSymbolicLink(symlink1, linked1Dir.toPath());
... |
public static boolean isExisting(final String jobId) {
return JOBS.containsKey(jobId);
} | @Test
void assertIsExisting() {
assertTrue(PipelineJobRegistry.isExisting("foo_job"));
} |
@Override
public boolean validateTree(ValidationContext validationContext) {
validate(validationContext);
return (onCancelConfig.validateTree(validationContext) && errors.isEmpty() && !configuration.hasErrors());
} | @Test
public void validateTreeShouldVerifyIfCancelTasksHasNestedCancelTask() {
PluggableTask pluggableTask = new PluggableTask(new PluginConfiguration(), new Configuration());
pluggableTask.onCancelConfig = mock(OnCancelConfig.class);
com.thoughtworks.go.domain.Task cancelTask = mock(com.tho... |
public void validateUserHasAdministerIssuesPermission(String projectUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
String userUuid = Objects.requireNonNull(userSession.getUuid());
if (!dbClient.authorizationDao().selectEntityPermissions(dbSession, projectUuid, userUuid).contains(ISSUE... | @Test
public void givenUserDoesNotHaveAdministerIssuesPermission_whenValidateUserHasAdministerIssuesPermission_thenThrowForbiddenException() {
// given
String userUuid = "userUuid";
doReturn(userUuid).when(userSession).getUuid();
String projectUuid = "projectUuid";
DbSession dbSession = mockDbSess... |
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 testUseModulesWithDuplicateModuleName() {
assertThatThrownBy(
() ->
manager.useModules(
CoreModuleFactory.IDENTIFIER, CoreModuleFactory.IDENTIFIER))
.isInstanceOf(ValidationException.cl... |
@VisibleForTesting
void checkDestinationFolderField( String realDestinationFoldernameFieldName, SFTPPutData data ) throws KettleStepException {
realDestinationFoldernameFieldName = environmentSubstitute( realDestinationFoldernameFieldName );
if ( Utils.isEmpty( realDestinationFoldernameFieldName ) ) {
t... | @Test( expected = KettleStepException.class )
public void checkDestinationFolderField_NameIsBlank() throws Exception {
SFTPPutData data = new SFTPPutData();
step.checkDestinationFolderField( "", data );
} |
public static Write write(String url, String token) {
checkNotNull(url, "url is required.");
checkNotNull(token, "token is required.");
return write(StaticValueProvider.of(url), StaticValueProvider.of(token));
} | @Test
@Category(NeedsRunner.class)
public void successfulSplunkIOMultiBatchNoParallelismTest() {
// Create server expectation for success.
mockServerListening(200);
int testPort = mockServerRule.getPort();
String url = Joiner.on(':').join("http://localhost", testPort);
String token = "test-tok... |
public boolean overlapInTime() {
return timeOverlap().isPresent();
} | @Test
public void testOverlapInTime() {
Track<NopHit> fullTrack = Track.of(newArrayList(P1, P2, P3, P4, P5, P6));
Track<NopHit> earlyTrack = Track.of(newArrayList(P1, P2, P3));
Track<NopHit> endTrack = Track.of(newArrayList(P4, P5, P6));
Track<NopHit> endTrack_2 = Track.of(newArrayL... |
public static <T> List<T> sub(List<T> list, int start, int end) {
return ListUtil.sub(list, start, end);
} | @Test
public void subInput1PositiveNegativePositiveOutput1() {
// Arrange
final List<Integer> list = new ArrayList<>();
list.add(null);
final int start = 3;
final int end = -1;
final int step = 2;
// Act
final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result
final List<... |
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) {
if (LOG.isTraceEnabled()) {
LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}"
+ " Used Normalized Resources: {} Total Normalized Resources:... | @Test
public void testCalculateMinUsageWithNoResourcesInTotal() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.emptyMap()));
NormalizedResources usedResources = new NormalizedResources(normalize(Collections.emptyMap()));
double min = resources.calcul... |
@GetMapping("by-product-id/{productId:\\d+}")
public Mono<FavouriteProduct> findFavouriteProductByProductId(Mono<JwtAuthenticationToken> authenticationTokenMono,
@PathVariable("productId") int productId) {
return authenticationTokenMono.flatM... | @Test
void findFavouriteProductsByProductId_ReturnsFavouriteProducts() {
// given
doReturn(Mono.just(
new FavouriteProduct(UUID.fromString("fe87eef6-cbd7-11ee-aeb6-275dac91de02"), 1,
"5f1d5cf8-cbd6-11ee-9579-cf24d050b47c")
)).when(this.favouriteProduct... |
public static byte[] decrypt3DES(byte[] data, byte[] key) {
return desTemplate(data, key, TripleDES_Algorithm, TripleDES_Transformation, false);
} | @Test
public void decrypt3DES() throws Exception {
TestCase.assertTrue(
Arrays.equals(
bytesDataDES3,
EncryptKit.decrypt3DES(bytesResDES3, bytesKeyDES3)
)
);
TestCase.assertTrue(
Arrays.equals(
... |
public int getRefreshClusterMaxPriorityFailedRetrieved() {
return numRefreshClusterMaxPriorityFailedRetrieved.value();
} | @Test
public void testRefreshClusterMaxPriorityFailedRetrieved() {
long totalBadBefore = metrics.getRefreshClusterMaxPriorityFailedRetrieved();
badSubCluster.getRefreshClusterMaxPriorityFailed();
Assert.assertEquals(totalBadBefore + 1, metrics.getRefreshClusterMaxPriorityFailedRetrieved());
} |
@Override
public void writeTo(ByteBuf byteBuf) throws LispWriterException {
WRITER.writeTo(byteBuf, this);
} | @Test
public void testSerialization() throws LispReaderException, LispWriterException, LispParseError {
ByteBuf byteBuf = Unpooled.buffer();
ReplyWriter writer = new ReplyWriter();
writer.writeTo(byteBuf, reply1);
ReplyReader reader = new ReplyReader();
LispMapReply deserial... |
@Override
public PageResult<BrokerageRecordDO> getBrokerageRecordPage(BrokerageRecordPageReqVO pageReqVO) {
return brokerageRecordMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetBrokerageRecordPage() {
// mock 数据
BrokerageRecordDO dbBrokerageRecord = randomPojo(BrokerageRecordDO.class, o -> { // 等会查询到
o.setUserId(null);
o.setBizType(null);
o.setStatus(null);
... |
public Stream<Flow> keepLastVersion(Stream<Flow> stream) {
return keepLastVersionCollector(stream);
} | @Test
void sameRevisionWithDeletedSameRevision() {
Stream<Flow> stream = Stream.of(
create("test2", "test2", 1),
create("test", "test", 1),
create("test", "test2", 2),
create("test", "test3", 3),
create("test", "test2", 2).toDeleted()
);
... |
public static List<ComponentDto> sortComponents(List<ComponentDto> components, ComponentTreeRequest wsRequest, List<MetricDto> metrics,
Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
List<String> sortParameters = wsRequest.getSort();
if (sortParameters == null || sor... | @Test
void sortComponent_whenMetricIsImpactDataType_shouldOrderByTotalAscending() {
components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure"));
ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), true, DATA_IMPACT_METRIC_KEY);... |
public final void containsKey(@Nullable Object key) {
check("keySet()").that(checkNotNull(actual).keySet()).contains(key);
} | @Test
public void containsKey() {
ImmutableMap<String, String> actual = ImmutableMap.of("kurt", "kluever");
assertThat(actual).containsKey("kurt");
} |
public static EnumBuilder<Schema> enumeration(String name) {
return builder().enumeration(name);
} | @Test
void enumWithDefault() {
List<String> symbols = Arrays.asList("a", "b");
String enumDefault = "a";
Schema expected = Schema.createEnum("myenum", null, null, symbols, enumDefault);
expected.addProp("p", "v");
Schema schema = SchemaBuilder.enumeration("myenum").prop("p", "v").defaultSymbol(enu... |
public ProtocolHandler protocol(String protocol) {
ProtocolHandlerWithClassLoader h = handlers.get(protocol);
if (null == h) {
return null;
} else {
return h.getHandler();
}
} | @Test
public void testGetProtocol() {
assertSame(handler1, handlers.protocol(protocol1));
assertSame(handler2, handlers.protocol(protocol2));
assertNull(handlers.protocol(protocol3));
} |
public static Map<String, KiePMMLTableSourceCategory> getClassificationTableBuilders(final RegressionCompilationDTO compilationDTO) {
logger.trace("getRegressionTables {}", compilationDTO.getRegressionTables());
LinkedHashMap<String, KiePMMLTableSourceCategory> toReturn =
KiePMMLRegress... | @Test
void getClassificationTableBuilders() {
RegressionTable regressionTableProf = getRegressionTable(3.5, "professional");
RegressionTable regressionTableCler = getRegressionTable(27.4, "clerical");
OutputField outputFieldCat = getOutputField("CAT-1", ResultFeature.PROBABILITY, "CatPred-1"... |
public boolean hasCwe() {
return !cwe.isEmpty();
} | @Test
@SuppressWarnings("squid:S2699")
public void testHasCwe() {
//already tested, this is just left so the IDE doesn't recreate it.
} |
@Override
public Type classify(final Throwable e) {
Type type = Type.UNKNOWN;
if (e instanceof KsqlFunctionException
|| (e instanceof StreamsException
&& ExceptionUtils.getRootCause(e) instanceof KsqlFunctionException)) {
type = Type.USER;
}
if (type == Type.USER) {
LOG.in... | @Test
public void shouldClassifyWrappedKsqlFunctionExceptionAsUserError() {
// Given:
final Exception e = new StreamsException(new KsqlFunctionException("foo"));
// When:
final Type type = new KsqlFunctionClassifier("").classify(e);
// Then:
assertThat(type, is(Type.USER));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.