focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public CompletableFuture<JobClient> submitJob(
JobGraph jobGraph, ClassLoader userCodeClassloader) throws Exception {
MiniClusterConfiguration miniClusterConfig =
getMiniClusterConfig(jobGraph.getMaximumParallelism());
MiniCluster miniCluster = miniClusterFactory.apply(miniCl... | @Test
void testJobClientSavepoint() throws Exception {
PerJobMiniClusterFactory perJobMiniClusterFactory = initializeMiniCluster();
JobClient jobClient =
perJobMiniClusterFactory
.submitJob(getCancellableJobGraph(), ClassLoader.getSystemClassLoader())
... |
public static <T> T getLast(Collection<T> collection) {
return get(collection, -1);
} | @Test
public void getLastTest() {
// 测试:空数组返回null而不是报错
final List<String> test = CollUtil.newArrayList();
final String last = CollUtil.getLast(test);
assertNull(last);
} |
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Bytes key, final long earliestSessionEndTime, final long latestSessionStartTime) {
return wrapped().findSessions(key, earliestSessionEndTime, latestSessionStartTime);
} | @Test
public void shouldDelegateToUnderlyingStoreWhenFindingSessions() {
store.findSessions(bytesKey, 0, 1);
verify(inner).findSessions(bytesKey, 0, 1);
} |
public static Object get(Object object, int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
r... | @Test
void testGetCollection2() {
assertThrows(IndexOutOfBoundsException.class, () -> {
CollectionUtils.get(Collections.emptySet(), -1);
});
} |
@Override
public boolean isInitializedAndRunning() {
synchronized (lock) {
return jobMasterServiceFuture.isDone()
&& !jobMasterServiceFuture.isCompletedExceptionally()
&& isRunning;
}
} | @Test
void testIsInitialized() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
jobMasterServiceFuture.complete(new TestingJobMasterServ... |
public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) {
if (fqjt.isArray()) {
// if array, then calculate the name of the base (non-array) type
// then add the array indicators back in
String fqn = fqjt.getFullyQualifiedName();
... | @Test
void testGenericTypeBaseTypeImportedImported() {
Interface interfaze = new Interface(new FullyQualifiedJavaType("com.foo.UserMapper"));
interfaze.addImportedType(new FullyQualifiedJavaType("java.util.Map"));
FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("java.util.Map<java... |
@Override
public void close() {
if (asyncCheckpointState.compareAndSet(
AsyncCheckpointState.RUNNING, AsyncCheckpointState.DISCARDED)) {
try {
final Tuple2<Long, Long> tuple = cleanup();
reportAbortedSnapshotStats(tuple.f0, tuple.f1);
... | @Test
void testReportIncompleteStats() {
long checkpointId = 1000L;
TestEnvironment env = new TestEnvironment();
new AsyncCheckpointRunnable(
new HashMap<>(),
new CheckpointMetaData(checkpointId, 1),
new CheckpointMetric... |
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName,
@Nullable Integer pageNumber, @Nullable Integer pageSize) {
String url = format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s",
gitlabUrl,
proj... | @Test
public void throws_ISE_when_get_projects_not_http_200() {
MockResponse projects = new MockResponse()
.setResponseCode(500)
.setBody("test");
server.enqueue(projects);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 2))
.isInstanceOf(IllegalArgumen... |
@Udf
public boolean check(@UdfParameter(description = "The input JSON string") final String input) {
if (input == null) {
return false;
}
try {
return !UdfJsonMapper.parseJson(input).isMissingNode();
} catch (KsqlFunctionException e) {
return false;
}
} | @Test
public void shouldInterpretNumber() {
assertTrue(udf.check("1"));
} |
private void getOpenApi() {
this.getOpenApi(Locale.getDefault());
} | @Test
void preLoadingModeShouldNotOverwriteServers() throws InterruptedException {
doCallRealMethod().when(openAPIService).updateServers(any());
when(openAPIService.getCachedOpenAPI(any())).thenCallRealMethod();
doAnswer(new CallsRealMethods()).when(openAPIService).setServersPresent(true);
doAnswer(new CallsRe... |
public static UPrimitiveType create(TypeKind typeKind) {
checkArgument(
isDeFactoPrimitive(typeKind), "Non-primitive type %s passed to UPrimitiveType", typeKind);
return new AutoValue_UPrimitiveType(typeKind);
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(UPrimitiveType.create(TypeKind.INT), UPrimitiveType.INT)
.addEqualityGroup(UPrimitiveType.create(TypeKind.LONG), UPrimitiveType.LONG)
.addEqualityGroup(UPrimitiveType.create(TypeKind.DOUBLE), UPrimitiveType.DOUBLE)
... |
@Override
public T get(int idx) {
if (idx < 0) {
throw new IndexOutOfBoundsException();
}
int base = 0;
Iterator<List<T>> it = chunks.iterator();
while (it.hasNext()) {
List<T> list = it.next();
int size = list.size();
if (idx < base + size) {
return list.get(idx - ... | @Test
public void testGet() throws Exception {
final int NUM_ELEMS = 100001;
ChunkedArrayList<Integer> list = new ChunkedArrayList<Integer>();
for (int i = 0; i < NUM_ELEMS; i++) {
list.add(i);
}
Assert.assertEquals(Integer.valueOf(100), list.get(100));
Assert.assertEquals(Integer.value... |
public List<AnalyzedInstruction> getAnalyzedInstructions() {
return analyzedInstructions.getValues();
} | @Test
public void testInstanceOfNarrowingAfterMove_dalvik() throws IOException {
MethodImplementationBuilder builder = new MethodImplementationBuilder(3);
builder.addInstruction(new BuilderInstruction12x(Opcode.MOVE_OBJECT, 1, 2));
builder.addInstruction(new BuilderInstruction22c(Opcode.INS... |
private void resolveNativeEntityLookupTable(EntityDescriptor entityDescriptor,
InputWithExtractors inputWithExtractors,
MutableGraph<EntityDescriptor> mutableGraph) {
final Stream<String> extractorLookupNames = inpu... | @Test
@MongoDBFixtures("InputFacadeTest.json")
public void resolveNativeEntityLookupTable() throws NotFoundException {
when(lookupuptableBuilder.lookupTable("whois")).thenReturn(lookupuptableBuilder);
when(lookupuptableBuilder.lookupTable("tor-exit-node-list")).thenReturn(lookupuptableBuilder);
... |
@Override
public CRTask deserialize(JsonElement json,
Type type,
JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN);
} | @Test
public void shouldInstantiateATaskForTypeFetch() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "fetch");
jsonObject.addProperty(TypeAdapter.ARTIFACT_ORIGIN, "gocd");
taskTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext);
... |
public static String trim(final String str) {
return str == null ? null : str.trim();
} | @Test
public void testTrim() {
assertThat(StringUtils.trim(null)).isNull();
assertThat(StringUtils.trim("abc")).isEqualTo("abc");
assertThat(StringUtils.trim("")).isEqualTo("");
assertThat(StringUtils.trim(" ")).isEqualTo("");
} |
@Override
public void setConf(Configuration conf) {
super.setConf(conf);
resourcesHandler = getResourcesHandler(conf);
containerSchedPriorityIsSet = false;
if (conf.get(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY)
!= null) {
containerSchedPriorityIsSet = true;
containe... | @Test
public void testNonSecureRunAsSubmitter() throws Exception {
Assume.assumeTrue(shouldRun());
Assume.assumeFalse(UserGroupInformation.isSecurityEnabled());
String expectedRunAsUser = appSubmitter;
conf.set(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS, "false");
exec.setConf(conf);
File... |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 0 && "size".equals(methodName)) {
return SelLong.of(val == null ? 0 : val.size());
} else if (args.length == 1 && "get".equals(methodName)) {
if (!val.containsKey((SelString) args[0])) {
return NULL;
... | @Test(expected = ClassCastException.class)
public void testCallGetNullKey() {
orig.call("get", new SelType[] {SelType.NULL});
} |
public static HazelcastInstance newHazelcastInstance(Config config) {
if (config == null) {
config = Config.load();
}
return newHazelcastInstance(
config,
config.getInstanceName(),
new DefaultNodeContext()
);
} | @Test(expected = ExpectedRuntimeException.class)
public void test_NewInstance_failed_beforeNodeShutdown() throws Exception {
NodeContext context = new TestNodeContext() {
@Override
public NodeExtension createNodeExtension(Node node) {
NodeExtension nodeExtension = sup... |
@Override
public void beginRound() {
logger.info(LOG_PREFIX + "=========================================beginRound");
} | @Test
public void testBeginRound() {
defaultMonitorListener.beginRound();
} |
@Override
protected void doExecute() {
if (vpls == null) {
vpls = get(Vpls.class);
}
if (interfaceService == null) {
interfaceService = get(InterfaceService.class);
}
VplsCommandEnum enumCommand = VplsCommandEnum.enumFromString(command);
if (e... | @Test
public void testShowOne() {
((TestVpls) vplsCommand.vpls).initSampleData();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setOut(ps);
vplsCommand.command = VplsCommandEnum.SHOW.toString();
vplsCommand.vp... |
@CanIgnoreReturnValue
public PrefItem addValue(String key, String value) {
mValues.put(validKey(key), value);
return this;
} | @Test(expected = java.lang.IllegalArgumentException.class)
public void testFailsIfKeyHasSpaces() {
mPrefItem.addValue("key ", "value");
} |
@Override
public Mono<ClearRegistrationLockResponse> clearRegistrationLock(final ClearRegistrationLockRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticat... | @Test
void clearRegistrationLockLinkedDevice() {
getMockAuthenticationInterceptor().setAuthenticatedDevice(AUTHENTICATED_ACI, (byte) (Device.PRIMARY_ID + 1));
//noinspection ResultOfMethodCallIgnored
GrpcTestUtils.assertStatusException(Status.PERMISSION_DENIED,
() -> authenticatedServiceStub().cl... |
@Override
public <OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> process(
OneInputStreamProcessFunction<T, OUT> processFunction) {
validateStates(
processFunction.usesStates(),
new HashSet<>(
Arrays.asList(
... | @Test
void testProcessTwoOutput() throws Exception {
ExecutionEnvironmentImpl env = StreamTestUtils.getEnv();
NonKeyedPartitionStreamImpl<Integer> stream =
new NonKeyedPartitionStreamImpl<>(
env, new TestingTransformation<>("t1", Types.INT, 1));
NonKey... |
@VisibleForTesting
static Properties extractCommonsHikariProperties(Properties properties) {
Properties result = new Properties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
if (!ALLOWED_SONAR_PROPERTIES.contains(key)) {
if (DEPREC... | @Test
@UseDataProvider("sonarJdbcAndHikariProperties")
public void shouldThrowISEIfDuplicatedResolvedPropertiesWithDifferentValue(String jdbcProperty, String hikariProperty) {
Properties props = new Properties();
props.setProperty(jdbcProperty, "100");
props.setProperty(hikariProperty, "200");
asse... |
public GenericRecord convert(String json, Schema schema) {
try {
Map<String, Object> jsonObjectMap = mapper.readValue(json, Map.class);
return convertJsonToAvro(jsonObjectMap, schema, shouldSanitize, invalidCharMask);
} catch (IOException e) {
throw new HoodieIOException(e.getMessage(), e);
... | @Test
public void conversionWithFieldNameSanitization() throws IOException {
String sanitizedSchemaString = "{\"namespace\": \"example.avro\", \"type\": \"record\", \"name\": \"User\", \"fields\": [{\"name\": \"__name\", \"type\": \"string\"}, "
+ "{\"name\": \"favorite__number\", \"type\": \"int\"}, {\"n... |
@Override
public Map<String, String> getAnnotations() {
return flinkConfig
.getOptional(KubernetesConfigOptions.JOB_MANAGER_ANNOTATIONS)
.orElse(Collections.emptyMap());
} | @Test
void testGetEmptyAnnotations() {
assertThat(kubernetesJobManagerParameters.getAnnotations()).isEmpty();
} |
static boolean equalWithinTolerance(long left, long right, long tolerance) {
try {
// subtractExact is always desugared.
@SuppressWarnings("Java7ApiChecker")
long absDiff = Math.abs(subtractExact(left, right));
return 0 <= absDiff && absDiff <= Math.abs(tolerance);
} catch (ArithmeticExc... | @Test
public void equalsDifferentTypes() {
assertThat(equalWithinTolerance(1.3d, 1.3f, 0.00000000000001d)).isFalse();
assertThat(equalWithinTolerance(1.3f, 1.3d, 0.00000000000001f)).isFalse();
} |
public static int findLevel(Level expectedLevel) {
int count = 0;
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
Level logLevel = logList.get(i).getLogLevel();
if (logLevel.equals(expectedLevel)) {
count++;
... | @Test
void testFindLevel() {
Log log = mock(Log.class);
DubboAppender.logList.add(log);
when(log.getLogLevel()).thenReturn(Level.ERROR);
assertThat(LogUtil.findLevel(Level.ERROR), equalTo(1));
assertThat(LogUtil.findLevel(Level.INFO), equalTo(0));
} |
@Override
public void connect() throws IllegalStateException, IOException {
if (isConnected()) {
throw new IllegalStateException("Already connected");
}
InetSocketAddress address = this.address;
if (address == null) {
address = new InetSocketAddress(hostname, ... | @Test
public void doesNotAllowDoubleConnections() throws Exception {
graphite.connect();
try {
graphite.connect();
failBecauseExceptionWasNotThrown(IllegalStateException.class);
} catch (IllegalStateException e) {
assertThat(e.getMessage())
... |
public static Builder builder() {
return new AutoValue_HttpHeaders.Builder();
} | @Test
public void builderAddHeader_withNullValue_throwsNullPointerException() {
assertThrows(
NullPointerException.class, () -> HttpHeaders.builder().addHeader("test_header", null));
} |
public Domain subtract(Domain other)
{
checkCompatibility(other);
return new Domain(values.subtract(other.getValues()), this.isNullAllowed() && !other.isNullAllowed());
} | @Test
public void testSubtract()
{
assertEquals(
Domain.all(BIGINT).subtract(Domain.all(BIGINT)),
Domain.none(BIGINT));
assertEquals(
Domain.all(BIGINT).subtract(Domain.none(BIGINT)),
Domain.all(BIGINT));
assertEquals(
... |
public BulkChange(Saveable saveable) {
this.parent = current();
this.saveable = saveable;
// remember who allocated this object in case
// someone forgot to call save() at the end.
allocator = new Exception();
// in effect at construction
INSCOPE.set(this);
} | @Test
public void bulkChange() throws Exception {
Point pt = new Point();
BulkChange bc = new BulkChange(pt);
try {
pt.set(0, 0);
} finally {
bc.commit();
}
assertEquals(1, pt.saveCount);
} |
@VisibleForTesting
public List<ProjectionContext> planRemoteAssignments(Assignments assignments, VariableAllocator variableAllocator)
{
ImmutableList.Builder<List<ProjectionContext>> assignmentProjections = ImmutableList.builder();
for (Map.Entry<VariableReferenceExpression, RowExpression> entry... | @Test
void testSpecialForm()
{
PlanBuilder planBuilder = new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), getMetadata());
planBuilder.variable("x", INTEGER);
planBuilder.variable("y", INTEGER);
PlanRemoteProjections rule = new PlanRemoteProjections(getFunctionAndTypeMana... |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatSelectWithLowerCaseAlias() {
final String statementString = "CREATE STREAM S AS SELECT address AS `foO` FROM address;";
final Statement statement = parseSingle(statementString);
assertThat(SqlFormatter.formatSql(statement),
equalTo("CREATE STREAM S AS SELECT"
... |
@Override
public void update() {
if (patrollingLeft) {
position -= 1;
if (position == PATROLLING_LEFT_BOUNDING) {
patrollingLeft = false;
}
} else {
position += 1;
if (position == PATROLLING_RIGHT_BOUNDING) {
patrollingLeft = true;
}
}
logger.info("S... | @Test
void testUpdateForReverseDirectionFromRightToLeft() {
skeleton.patrollingLeft = false;
skeleton.setPosition(99);
skeleton.update();
assertEquals(100, skeleton.getPosition());
assertTrue(skeleton.patrollingLeft);
} |
@Override
public boolean addAll(Collection<? extends E> c) {
for (E e : c) {
add(e);
}
return true;
} | @Test
public void testAddAll() {
queue.addAll(asList(23, 42));
assertEquals(2, queue.size());
assertContains(queue, 23);
assertContains(queue, 42);
} |
@VisibleForTesting
static void initKeyStore(Properties consumerProps) {
Path keyStorePath = getKeyStorePath(consumerProps);
if (Files.exists(keyStorePath)) {
deleteFile(keyStorePath);
}
LOGGER.info("Initializing the SSL key store");
try {
// Create the key store path
createFile(k... | @Test
public void testInitKeyStore()
throws CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException,
IOException, KeyStoreException {
Properties consumerProps = new Properties();
setKeyStoreProps(consumerProps);
// should not throw any excepti... |
public int getInt(@NotNull final String key) throws InvalidSettingException {
try {
return Integer.parseInt(getString(key));
} catch (NumberFormatException ex) {
throw new InvalidSettingException("Could not convert property '" + key + "' to an int.", ex);
}
} | @Test
public void testGetInt() throws InvalidSettingException {
String key = "SomeNumber";
int expResult = 85;
getSettings().setString(key, "85");
int result = getSettings().getInt(key);
Assert.assertEquals(expResult, result);
} |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(ap... | @Test
public void status_GREEN_when_two_GREEN_application_node_and_any_number_of_other_is_GREEN() {
Set<NodeHealth> nodeHealths = of(
// at least 1 extra GREEN
of(appNodeHealth(GREEN)),
// 0 to 10 GREEN
randomNumberOfAppNodeHealthOfAnyStatus(GREEN),
// 2 GREEN
nodeHealths(GREEN... |
public static MethodDeclaration addMethod(final MethodDeclaration methodTemplate,
final ClassOrInterfaceDeclaration tableTemplate,
final String methodName) {
final BlockStmt body =
methodTemplate.getBody(... | @Test
void addMethod() {
final MethodDeclaration methodTemplate = new MethodDeclaration();
methodTemplate.setName("methodTemplate");
final BlockStmt body = new BlockStmt();
methodTemplate.setBody(body);
final String methodName = "METHOD_NAME";
final ClassOrInterfaceDe... |
@VisibleForTesting
void validateEmailUnique(Long id, String email) {
if (StrUtil.isBlank(email)) {
return;
}
AdminUserDO user = userMapper.selectByEmail(email);
if (user == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的用户
if (id == null... | @Test
public void testValidateEmailUnique_emailExistsForCreate() {
// 准备参数
String email = randomString();
// mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
// 调用,校验异常
assertServiceException(() -> userService.validateEmailUnique(null, email),
... |
public boolean initAndAddIssue(Issue issue) {
DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent();
if (noSonar(inputComponent, issue)) {
return false;
}
ActiveRule activeRule = activeRules.find(issue.ruleKey());
if (activeRule == null) {
... | @Test
public void should_accept_issues_on_no_sonar_rules() {
// The "No Sonar" rule logs violations on the lines that are flagged with "NOSONAR" !!
activeRulesBuilder.addRule(new NewActiveRule.Builder()
.setRuleKey(NOSONAR_RULE_KEY)
.setSeverity(Severity.INFO)
.setQProfileKey("qp-1")
.... |
@SuppressWarnings("unchecked")
public static <T extends SpecificRecord> TypeInformation<Row> convertToTypeInfo(
Class<T> avroClass) {
return convertToTypeInfo(avroClass, true);
} | @Test
void testTimestampsSchemaToTypeInfoNewMapping() {
final Tuple4<Class<? extends SpecificRecord>, SpecificRecord, GenericRecord, Row> testData =
AvroTestUtils.getTimestampTestData();
String schemaStr = testData.f1.getSchema().toString();
TypeInformation<Row> typeInfo = Av... |
public static List<KeyProvider> getProviders(Configuration conf
) throws IOException {
List<KeyProvider> result = new ArrayList<KeyProvider>();
for(String path: conf.getStringCollection(KEY_PROVIDER_PATH)) {
try {
URI uri = new URI(path);
KeyP... | @Test
public void testFactoryErrors() throws Exception {
Configuration conf = new Configuration();
conf.set(KeyProviderFactory.KEY_PROVIDER_PATH, "unknown:///");
try {
List<KeyProvider> providers = KeyProviderFactory.getProviders(conf);
assertTrue("should throw!", false);
} catch (IOExcept... |
public QueryCacheConfig setEvictionConfig(EvictionConfig evictionConfig) {
checkNotNull(evictionConfig, "evictionConfig cannot be null");
this.evictionConfig = evictionConfig;
return this;
} | @Test(expected = NullPointerException.class)
public void testSetEvictionConfig_throwsException_whenNull() {
QueryCacheConfig config = new QueryCacheConfig();
config.setEvictionConfig(null);
} |
public FEELFnResult<List<Object>> invoke(@ParameterName( "list" ) List list, @ParameterName( "position" ) BigDecimal position) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
if ( position == null ) {
... | @Test
void invokePositionZero() {
FunctionTestUtil.assertResultError(removeFunction.invoke(Collections.singletonList(1), BigDecimal.ZERO),
InvalidParametersEvent.class);
} |
public CompletableFuture<Account> removeDevice(final Account account, final byte deviceId) {
if (deviceId == Device.PRIMARY_ID) {
throw new IllegalArgumentException("Cannot remove primary device");
}
return accountLockManager.withLockAsync(List.of(account.getNumber()),
() -> removeDevice(acco... | @Test
void testRemoveDevice() {
final Device primaryDevice = new Device();
primaryDevice.setId(Device.PRIMARY_ID);
final Device linkedDevice = new Device();
linkedDevice.setId((byte) (Device.PRIMARY_ID + 1));
Account account = AccountsHelper.generateTestAccount("+14152222222", List.of(primaryDev... |
@Override
public boolean isSupport(URL address) {
return dubboCertManager != null && dubboCertManager.isConnected();
} | @Test
void testEnable1() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (na... |
@VisibleForTesting
static void createDocumentationFile(
String title,
DocumentingRestEndpoint restEndpoint,
RestAPIVersion apiVersion,
Path outputFile)
throws IOException {
final OpenAPI openApi = createDocumentation(title, restEndpoint, apiVersion... | @Test
void testExcludeFromDocumentation(@TempDir Path tmpDir) throws Exception {
final Path file = tmpDir.resolve("openapi_spec.yaml");
OpenApiSpecGenerator.createDocumentationFile(
"title",
DocumentingRestEndpoint.forRestHandlerSpecifications(
... |
public static MessageHeaders createAfnemersberichtAanDGLHeaders(Map<String, Object> additionalHeaders) {
validateHeaders(additionalHeaders);
Map<String, Object> headersMap = createBasicHeaderMap();
headersMap.put(nl.logius.digid.digilevering.lib.model.Headers.X_AUX_ACTION, "BRPAfnemersberichtAa... | @Test
public void testReceiverHeaderPresent() {
Map<String, Object> map = new HashMap<>();
map.put(Headers.X_AUX_SENDER_ID, "senderId");
assertThrows(IllegalArgumentException.class, () -> HeaderUtil.createAfnemersberichtAanDGLHeaders(map), "x_aux_receiver_id receiver header is mandatory");
... |
public Builder toBuilder() {
Builder result = new Builder();
result.flags = flags;
result.traceIdHigh = traceIdHigh;
result.traceId = traceId;
return result;
} | @Test void canUsePrimitiveOverloads_false() {
base = base.toBuilder().debug(true).build();
TraceIdContext primitives = base.toBuilder()
.sampled(false)
.debug(false)
.build();
TraceIdContext objects = base.toBuilder()
.sampled(Boolean.FALSE)
.debug(Boolean.FALSE)
.build... |
public int toInt(String name) {
return toInt(name, 0);
} | @Test
public void testToInt_String() {
System.out.println("toInt");
int expResult;
int result;
Properties props = new Properties();
props.put("value1", "123");
props.put("value2", "-54");
props.put("empty", "");
props.put("str", "abc");
props.... |
@JsonCreator
public static RefinementInfo of(
@JsonProperty(value = "outputRefinement", required = true)
final OutputRefinement outputRefinement
) {
return new RefinementInfo(outputRefinement);
} | @Test
public void shouldImplementEquals() {
new EqualsTester()
.addEqualityGroup(
RefinementInfo.of(OutputRefinement.FINAL),
RefinementInfo.of(OutputRefinement.FINAL)
)
.addEqualityGroup(
RefinementInfo.of(OutputRefinement.CHANGES)
)
.tes... |
public static byte[] serializeOrDiscard(StateObject stateObject) throws Exception {
try {
return InstantiationUtil.serializeObject(stateObject);
} catch (Exception e) {
try {
stateObject.discardState();
} catch (Exception discardException) {
... | @Test
void testSerializeOrDiscardFailureHandling() throws Exception {
final AtomicBoolean discardCalled = new AtomicBoolean(false);
final StateObject original =
new FailingSerializationStateObject(() -> discardCalled.set(true));
assertThatThrownBy(() -> StateHandleStoreUtils... |
@Override
public boolean shouldHandle(String key) {
return super.shouldHandle(key) && RouterConstant.ROUTER_KEY_PREFIX.equals(key);
} | @Test
public void testShouldHandle() {
Assert.assertTrue(handler.shouldHandle("servicecomb.routeRule"));
Assert.assertFalse(handler.shouldHandle("servicecomb.routeRule.foo"));
} |
@Override
public void processWatermark(Instant watermark, OpEmitter<OutT> emitter) {
// propagate watermark immediately if no bundle is in progress and all the previous bundles have
// completed.
if (!isBundleStarted() && pendingBundleCount.get() == 0) {
LOG.debug("Propagating watermark: {} directly... | @Test
public void testProcessWatermarkWhenNoBundleInProgress() {
Instant now = Instant.now();
OpEmitter<String> mockEmitter = mock(OpEmitter.class);
bundleManager.processWatermark(now, mockEmitter);
verify(bundleProgressListener, times(1)).onWatermark(now, mockEmitter);
} |
@Override
public void trackFragmentAppViewScreen() {
} | @Test
public void trackFragmentAppViewScreen() {
mSensorsAPI.trackFragmentAppViewScreen();
Assert.assertFalse(mSensorsAPI.isTrackFragmentAppViewScreenEnabled());
} |
@Override
public Session createSession(QueryId queryId, SessionContext context, WarningCollectorFactory warningCollectorFactory, Optional<AuthorizedIdentity> authorizedIdentity)
{
Identity identity = context.getIdentity();
if (authorizedIdentity.isPresent()) {
identity = new Identity... | @Test
public void testCreateSession()
{
HttpRequestSessionContext context = new HttpRequestSessionContext(TEST_REQUEST, new SqlParserOptions());
QuerySessionSupplier sessionSupplier = new QuerySessionSupplier(
createTestTransactionManager(),
new AllowAllAccessCont... |
@Override
public AuthenticationResult authenticate(final ChannelHandlerContext context, final PacketPayload payload) {
if (SSL_REQUEST_PAYLOAD_LENGTH == payload.getByteBuf().markReaderIndex().readInt() && SSL_REQUEST_CODE == payload.getByteBuf().readInt()) {
if (ProxySSLContext.getInstance().isS... | @Test
void assertSSLWilling() {
ByteBuf byteBuf = createByteBuf(8, 8);
byteBuf.writeInt(8);
byteBuf.writeInt(80877103);
PacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8);
ChannelHandlerContext context = mock(ChannelHandlerContext.class, RETU... |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testReadFieldsBasic() {
String[] readFields = {"*"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
SemanticPropUtil.getSemanticPropsSingleFromString(
sp, null, null, readFields, intType, intType);
FieldSet fs = sp.getReadFields(0)... |
public static Object getRequestWithoutData(Object message) {
if (logger.isDebugEnabled()) {
return message;
}
if (message instanceof Request) {
Request request = (Request) message;
request.setData(null);
return request;
} else if (message i... | @Test
void test() {
Request request = new Request(1);
request.setData(new Object());
Request requestWithoutData = (Request) PayloadDropper.getRequestWithoutData(request);
Assertions.assertEquals(requestWithoutData.getId(), request.getId());
Assertions.assertNull(requestWithou... |
public static Wrapper getWrapper(Class<?> c) {
while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic class.
{
c = c.getSuperclass();
}
if (c == Object.class) {
return OBJECT_WRAPPER;
}
return ConcurrentHashMapUtils.computeIfAbsen... | @Test
void testWrapPrimitive() throws Exception {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
Wrapper.getWrapper(Byte.TYPE);
});
} |
public void addStripAction(@NonNull StripActionProvider provider, boolean highPriority) {
for (var stripActionView : mStripActionViews) {
if (stripActionView.getTag(PROVIDER_TAG_ID) == provider) {
return;
}
}
var actionView = provider.inflateActionView(this);
if (actionView.getParen... | @Test
public void testDoubleAddDoesNotAddAgain() {
View view = new View(mUnderTest.getContext());
KeyboardViewContainerView.StripActionProvider provider =
Mockito.mock(KeyboardViewContainerView.StripActionProvider.class);
Mockito.doReturn(view).when(provider).inflateActionView(any());
mUnderT... |
public static <T> T loadObject(String content, Class<T> type) {
return new Yaml(new YamlParserConstructor(), new CustomRepresenter()).loadAs(content, type);
} | @Test
void testNotSupportType() {
assertThrows(ConstructorException.class, () -> {
YamlParserUtil.loadObject("name: test", YamlTest.class);
});
} |
void initServletContext(ServletContext context) {
assert context != null;
this.servletContext = context;
final String serverInfo = servletContext.getServerInfo();
jboss = serverInfo.contains("JBoss") || serverInfo.contains("WildFly");
glassfish = serverInfo.contains("GlassFish")
|| serverInfo.contains("Su... | @Test
public void testInitServletContext() {
final String[] servers = { "JBoss", "WildFly", "GlassFish",
"Sun Java System Application Server", "WebLogic", };
for (final String serverName : servers) {
final ServletContext servletContext = createNiceMock(ServletContext.class);
expect(servletContext.getServ... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
boolean satisfied = false;
// No trading history or no position opened, no loss
if (tradingRecord != null) {
Position currentPosition = tradingRecord.getCurrentPosition();
if (currentPositi... | @Test
public void isSatisfiedWorksForBuy() {
final TradingRecord tradingRecord = new BaseTradingRecord(Trade.TradeType.BUY);
final Num tradedAmount = numOf(1);
// 5% stop-loss
StopLossRule rule = new StopLossRule(closePrice, numOf(5));
assertFalse(rule.isSatisfied(0, null))... |
public void close() {
commandConsumer.close();
commandTopicBackup.close();
} | @Test
public void shouldCloseAllResources() {
// When:
commandTopic.close();
//Then:
verify(commandConsumer).close();
} |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_only_once() {
TextBlock original = new TextBlock(1, 10);
duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(10, 11), new TextBlock(11, 12));
duplicationRepository.addDuplication(FILE_1_REF, new T... |
@Override
public void run() {
if (processor != null) {
processor.execute();
} else {
if (!beforeHook()) {
logger.info("before-feature hook returned [false], aborting: {}", this);
} else {
scenarios.forEachRemaining(this::processScen... | @Test
void testOutline() {
run("outline.feature");
} |
DecodedJWT verifyJWT(PublicKey publicKey,
String publicKeyAlg,
DecodedJWT jwt) throws AuthenticationException {
if (publicKeyAlg == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new... | @Test(dataProvider = "supportedAlgorithms")
public void testThatSupportedAlgsWork(SignatureAlgorithm alg) throws AuthenticationException {
KeyPair keyPair = Keys.keyPairFor(alg);
DefaultJwtBuilder defaultJwtBuilder = new DefaultJwtBuilder();
addValidMandatoryClaims(defaultJwtBuilder, basicPr... |
public Expression toPredicate(TupleDomain<String> tupleDomain)
{
if (tupleDomain.isNone()) {
return FALSE_LITERAL;
}
Map<String, Domain> domains = tupleDomain.getDomains().get();
return domains.entrySet().stream()
.sorted(comparing(entry -> entry.getKey()... | @Test
public void testToPredicate()
{
TupleDomain<String> tupleDomain;
tupleDomain = withColumnDomains(ImmutableMap.of(C_BIGINT, Domain.notNull(BIGINT)));
assertEquals(toPredicate(tupleDomain), isNotNull(C_BIGINT));
tupleDomain = withColumnDomains(ImmutableMap.of(C_BIGINT, Doma... |
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
ThreadContext.unbindSubject();
final boolean secure = requestContext.getSecurityContext().isSecure();
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
final Map<String... | @Test
public void filterWithBasicAuthAndSessionIdShouldCreateShiroSecurityContextWithSessionIdToken() throws Exception {
final MultivaluedHashMap<String, String> headers = new MultivaluedHashMap<>();
final String credentials = Base64.getEncoder().encodeToString("test:session".getBytes(StandardCharse... |
@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 shouldCreateMigrationsTable() {
// When:
final int status = command.command(config, cfg -> client);
// Then:
assertThat(status, is(0));
verify(client).executeStatement(EXPECTED_CTAS_STATEMENT);
} |
@Override
public int run(String[] argv) {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-safemode".equals(cmd)) {
if (argv.length != 2) ... | @Test
public void testAllowSnapshotWhenTrashExists() throws Exception {
final Path dirPath = new Path("/ssdir3");
final Path trashRoot = new Path(dirPath, ".Trash");
final DistributedFileSystem dfs = cluster.getFileSystem();
final DFSAdmin dfsAdmin = new DFSAdmin(conf);
// Case 1: trash directory... |
@DeleteMapping("/batch")
@RequiresPermissions("system:api:delete")
public ShenyuAdminResult deleteApis(@RequestBody @NotEmpty final List<@NotBlank String> ids) {
final String result = apiService.delete(ids);
if (StringUtils.isNoneBlank(result)) {
return ShenyuAdminResult.error(result... | @Test
public void testDeleteApis() throws Exception {
given(this.apiService.delete(Collections.singletonList("123"))).willReturn(StringUtils.EMPTY);
this.mockMvc.perform(MockMvcRequestBuilders.delete("/api/batch")
.contentType(MediaType.APPLICATION_JSON)
... |
@Override
public Num calculate(BarSeries series, Position position) {
return isBreakEvenPosition(position) ? series.one() : series.zero();
} | @Test
public void calculateWithOneLongPosition() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
Position position = new Position(Trade.buyAt(0, series), Trade.sellAt(3, series));
assertNumEquals(1, getCriterion().calculate(series, position));
} |
@Override
public Cursor<byte[]> scan(RedisClusterNode node, ScanOptions options) {
return new ScanCursor<byte[]>(0, options) {
private RedisClient client = getEntry(node);
@Override
protected ScanIteration<byte[]> doScan(long cursorId, ScanOptions options) {... | @Test
public void testScan() {
for (int i = 0; i < 1000; i++) {
connection.set(("" + i).getBytes(StandardCharsets.UTF_8), ("" + i).getBytes(StandardCharsets.UTF_8));
}
Cursor<byte[]> b = connection.scan(ScanOptions.scanOptions().build());
int counter = 0;
while (... |
public StatementProxy(AbstractConnectionProxy connectionWrapper, T targetStatement, String targetSQL)
throws SQLException {
super(connectionWrapper, targetStatement, targetSQL);
} | @Test
public void testStatementProxy() {
Assertions.assertNotNull(statementProxy);
} |
static Properties resolveProducerProperties(Map<String, String> options, Object keySchema, Object valueSchema) {
Properties properties = from(options);
withSerdeProducerProperties(true, options, keySchema, properties);
withSerdeProducerProperties(false, options, valueSchema, properties);
... | @Test
public void test_producerProperties_json() {
// key
assertThat(resolveProducerProperties(Map.of(OPTION_KEY_FORMAT, JSON_FLAT_FORMAT)))
.containsExactlyEntriesOf(Map.of(KEY_SERIALIZER, ByteArraySerializer.class.getCanonicalName()));
// value
assertThat(resolvePr... |
@Override
public long getTick() {
return THREAD_MX_BEAN.getCurrentThreadCpuTime();
} | @Test
public void cpuTimeClock() {
final CpuTimeClock clock = new CpuTimeClock();
assertThat((double) clock.getTime())
.isEqualTo(System.currentTimeMillis(),
offset(250D));
assertThat((double) clock.getTick())
.isEqualTo(ManagementFac... |
@VisibleForTesting
static Map<Severity, List<String>> checkNoticeFile(
Map<String, Set<Dependency>> modulesWithShadedDependencies,
String moduleName,
@Nullable NoticeContents noticeContents) {
final Map<Severity, List<String>> problemsBySeverity = new HashMap<>();
... | @Test
void testCheckNoticeFileRejectsMissingDependency() {
final String moduleName = "test";
final Map<String, Set<Dependency>> bundleDependencies = new HashMap<>();
bundleDependencies.put(
moduleName, Collections.singleton(Dependency.create("a", "b", "c", null)));
a... |
@Override
public void run() {
try {
// We kill containers until the kernel reports the OOM situation resolved
// Note: If the kernel has a delay this may kill more than necessary
while (true) {
String status = cgroups.getCGroupParam(
CGroupsHandler.CGroupController.MEMORY,
... | @Test
public void testKillGuaranteedContainerWithKillFailuresUponOOM()
throws Exception {
ConcurrentHashMap<ContainerId, Container> containers =
new ConcurrentHashMap<>();
Container c1 = createContainer(1, false, 1L, true);
containers.put(c1.getContainerId(), c1);
Container c2 = createCo... |
public static Set<String> getRequirementsForCategoryAndLevel(String category, int level) {
return OWASP_ASVS_40_REQUIREMENTS_BY_LEVEL.get(level).stream()
.filter(req -> req.startsWith(category + "."))
.collect(Collectors.toSet());
} | @Test
void owaspAsvs40_requirements_by_category_and_level_check() {
assertEquals(0, getRequirementsForCategoryAndLevel(OwaspAsvs.C1, 1).size());
assertEquals(31, getRequirementsForCategoryAndLevel(OwaspAsvs.C2, 1).size());
assertEquals(12, getRequirementsForCategoryAndLevel(OwaspAsvs.C3, 1).size());
a... |
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
} | @Test
public void testWithLettersComingFromLog4j() {
// Letters: p = level and c = logger
pl.setPattern("%d %p [%t] %c{30} - %m%n");
pl.start();
String val = pl.doLayout(getEventObject());
// 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some
// message
String regex = C... |
public static void scheduleLongPolling(Runnable runnable, long initialDelay, long delay, TimeUnit unit) {
LONG_POLLING_EXECUTOR.scheduleWithFixedDelay(runnable, initialDelay, delay, unit);
} | @Test
void testScheduleLongPollingV2() throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger();
Runnable runnable = atomicInteger::incrementAndGet;
ConfigExecutor.scheduleLongPolling(runnable, 20, TimeUnit.MILLISECONDS);
ass... |
@Override
public void onEvent(Event event) {
if (EnvUtil.getStandaloneMode()) {
return;
}
if (event instanceof ClientEvent.ClientVerifyFailedEvent) {
syncToVerifyFailedServer((ClientEvent.ClientVerifyFailedEvent) event);
} else {
syncToAllServer((C... | @Test
void testOnClientChangedEventWithoutClient() {
distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(null));
verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong());
verify(distroProtocol, never()).sync(any(), any());
} |
@CheckForNull
public String getDescriptionAsHtml(RuleDto ruleDto) {
if (ruleDto.getDescriptionFormat() == null) {
return null;
}
Collection<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = ruleDto.getRuleDescriptionSectionDtos();
return retrieveDescription(ruleDescriptionSectionDtos, Obje... | @Test
public void getHtmlDescriptionAsIs() {
RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.HTML).addRuleDescriptionSectionDto(HTML_SECTION).setType(RuleType.BUG);
String html = ruleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(html).isEqualTo(HTML_SECTION.getContent());
... |
@Override
public NvdApiProcessor call() throws Exception {
if (jsonFile.getName().endsWith(".jsonarray.gz")) {
try (InputStream fis = Files.newInputStream(jsonFile.toPath());
InputStream is = new BufferedInputStream(new GZIPInputStream(fis));
CveItemSource<DefCv... | @Test
public void unspecifiedFileName() throws Exception {
try (CveDB cve = new CveDB(getSettings())) {
File file = File.createTempFile("test", "test");
writeFileString(file, "");
NvdApiProcessor processor = new NvdApiProcessor(null, file);
processor.call();
... |
public static <T> Iterator<Class<T>> classIterator(Class<T> expectedType, String factoryId, ClassLoader classLoader) {
Set<ServiceDefinition> serviceDefinitions = getServiceDefinitions(factoryId, classLoader);
return new ClassIterator<>(serviceDefinitions, expectedType);
} | @Test
public void testMultipleClassloaderLoadsTheSameClass() throws Exception {
ClassLoader parent = this.getClass().getClassLoader();
//child classloader will steal bytecode from the parent and will define classes on its own
ClassLoader childLoader = new StealingClassloader(parent);
... |
@Override
public String toString() {
return pf.format(ratioValue());
} | @Test
public void testToString() {
NumberFormat pf = DecimalFormat.getPercentInstance(); //Varies by machine
pf.setMaximumFractionDigits(3);
assertEquals(pf.format(0.12345f), MilliPct.ofMilliPct(12345).toString());
assertEquals(pf.format(-0.12345f), MilliPct.ofMilliPct(-12345).toStri... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldUseValidationErrorKeyAnnotationForFieldNameInCaseOfException() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant", "nant");
FetchTask task = new FetchTask(new CaseInsensitiveString("cruise"), new CaseInsensitiveString("dev"), ne... |
static @Nullable <T extends PluginConfig> T getPluginConfig(
Map<String, Object> params, Class<T> configClass) {
// Validate configClass
if (configClass == null) {
throw new IllegalArgumentException("Config class must be not null!");
}
List<Field> allFields = new ArrayList<>();
Class<?> ... | @Test
public void testBuildingPluginConfigFromParamsMap() {
try {
ServiceNowSourceConfig config =
PluginConfigInstantiationUtils.getPluginConfig(
TEST_SERVICE_NOW_PARAMS_MAP, ServiceNowSourceConfig.class);
assertNotNull(config);
validateServiceNowConfigObject(TEST_SERVICE... |
@Nullable
public Float getFloatValue(@FloatFormat final int formatType,
@IntRange(from = 0) final int offset) {
if ((offset + getTypeLen(formatType)) > size()) return null;
switch (formatType) {
case FORMAT_SFLOAT -> {
if (mValue[offset + 1] == 0x07 && mValue[offset] == (byte) 0xFE)
return F... | @Test
public void setValue_SFLOAT_cutPrecision() {
final MutableData data = new MutableData(new byte[2]);
data.setValue(1000400f, Data.FORMAT_SFLOAT, 0);
final float value = data.getFloatValue(Data.FORMAT_SFLOAT, 0);
assertEquals(1000000f, value, 0.00);
} |
public boolean cleanTable() {
boolean allRemoved = true;
Set<String> removedPaths = new HashSet<>();
for (PhysicalPartition partition : table.getAllPhysicalPartitions()) {
try {
WarehouseManager manager = GlobalStateMgr.getCurrentState().getWarehouseMgr();
... | @Test
public void testShardNotFound(@Mocked LakeTable table,
@Mocked PhysicalPartition partition,
@Mocked MaterializedIndex index,
@Mocked LakeTablet tablet,
@Mocked LakeService la... |
@VisibleForTesting
static DefaultIssue toDefaultIssue(IssueCache.Issue next) {
DefaultIssue defaultIssue = new DefaultIssue();
defaultIssue.setKey(next.getKey());
defaultIssue.setType(RuleType.valueOf(next.getRuleType()));
defaultIssue.setComponentUuid(next.hasComponentUuid() ? next.getComponentUuid()... | @Test
public void toDefaultIssue_whenRuleDescriptionContextKeyAbsent_shouldNotSetItInDefaultIssue() {
IssueCache.Issue issue = prepareIssueWithCompulsoryFields()
.build();
DefaultIssue defaultIssue = ProtobufIssueDiskCache.toDefaultIssue(issue);
assertThat(defaultIssue.getRuleDescriptionContextKey... |
public Msg putShortString(String data)
{
if (data == null) {
return this;
}
ByteBuffer dup = buf.duplicate();
dup.position(writeIndex);
writeIndex += Wire.putShortString(dup, data);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testPutStringLongerThan255InBuilder()
{
final Msg.Builder msg = new Msg.Builder();
char[] charArray = new char[256];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
msg.putShortString(str);
... |
Meter.Type getMetricsType(String remaining) {
String type = StringHelper.before(remaining, ":");
return type == null
? DEFAULT_METER_TYPE
: MicrometerUtils.getByName(type);
} | @Test
public void testGetMetricsTypeNotFound() {
assertThrows(RuntimeCamelException.class,
() -> component.getMetricsType("unknown-metrics:metrics-name"));
} |
public String getSplunkEndpoint() {
return this.splunkEndpoint;
} | @Test
public void testDefaultEndpoint() {
SplunkHECConfiguration config = new SplunkHECConfiguration();
assertEquals("/services/collector/event", config.getSplunkEndpoint());
} |
@Override
public void write(String entry) throws IOException {
final LoggingEvent event = new LoggingEvent();
event.setLevel(Level.INFO);
event.setLoggerName("http.request");
event.setMessage(entry);
event.setTimeStamp(System.currentTimeMillis());
event.setLoggerConte... | @Test
void logsRequestsToTheAppenders() throws Exception {
final String requestLine = "1, 2 buckle my shoe";
slf4jRequestLog.write(requestLine);
final ArgumentCaptor<ILoggingEvent> captor = ArgumentCaptor.forClass(ILoggingEvent.class);
verify(appender, timeout(1000)).doAppend(captor.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.