focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public long getDictDataCountByDictType(String dictType) {
return dictDataMapper.selectCountByDictType(dictType);
} | @Test
public void testGetDictDataCountByDictType() {
// mock 数据
dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai")));
dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("tudou")));
dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai")));
//... |
void notifyPendingReceivedCallback(final Message<T> message, Exception exception) {
if (pendingReceives.isEmpty()) {
return;
}
// fetch receivedCallback from queue
final CompletableFuture<Message<T>> receivedFuture = nextPendingReceive();
if (receivedFuture == null) ... | @Test(invocationTimeOut = 1000)
public void testNotifyPendingReceivedCallback_EmptyQueueNotThrowsException() {
consumer.notifyPendingReceivedCallback(null, null);
} |
protected boolean tryProcess0(@Nonnull Object item) throws Exception {
return tryProcess(0, item);
} | @Test
public void when_tryProcess0_then_delegatesToTryProcess() throws Exception {
// When
boolean done = p.tryProcess0(MOCK_ITEM);
// Then
assertTrue(done);
p.validateReceptionOfItem(ORDINAL_0, MOCK_ITEM);
} |
public static long parseRelativeTime(String relTime) throws IOException {
if (relTime.length() < 2) {
throw new IOException("Unable to parse relative time value of " + relTime
+ ": too short");
}
String ttlString = relTime.substring(0, relTime.length()-1);
long ttl;
try {
ttl =... | @Test(timeout=5000)
public void testRelativeTimeConversion() throws Exception {
try {
DFSUtil.parseRelativeTime("1");
} catch (IOException e) {
assertExceptionContains("too short", e);
}
try {
DFSUtil.parseRelativeTime("1z");
} catch (IOException e) {
assertExceptionContain... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertBytes() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("BLOB").dataType("BLOB").build();
Column column = SapHanaTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), co... |
public static L2ModificationInstruction modVlanId(VlanId vlanId) {
checkNotNull(vlanId, "VLAN id cannot be null");
return new L2ModificationInstruction.ModVlanIdInstruction(vlanId);
} | @Test
public void testModVlanIdMethod() {
final Instruction instruction = Instructions.modVlanId(vlanId1);
final L2ModificationInstruction.ModVlanIdInstruction modEtherInstruction =
checkAndConvert(instruction,
Instruction.Type.L2MODIFICATION,
... |
public void updateGlobalWhiteAddrsConfig(final String addr, final String globalWhiteAddrs, String aclFileFullPath,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
UpdateGlobalWhiteAddrsConfigRequestHeader requestHeader = new Update... | @Test(expected = AssertionError.class)
public void testUpdateGlobalWhiteAddrsConfig() throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
mqClientAPI.updateGlobalWhiteAddrsConfig(defaultNsAddr, "", "", defaultTimeout);
} |
public static boolean toBoolean(String valueStr) {
if (StrUtil.isNotBlank(valueStr)) {
valueStr = valueStr.trim().toLowerCase();
return TRUE_SET.contains(valueStr);
}
return false;
} | @Test
public void toBooleanTest() {
assertTrue(BooleanUtil.toBoolean("true"));
assertTrue(BooleanUtil.toBoolean("yes"));
assertTrue(BooleanUtil.toBoolean("t"));
assertTrue(BooleanUtil.toBoolean("OK"));
assertTrue(BooleanUtil.toBoolean("1"));
assertTrue(BooleanUtil.toBoolean("On"));
assertTrue(BooleanUtil... |
static Set<Set<Integer>> computeStronglyConnectedComponents(
final int numVertex, final List<List<Integer>> outEdges) {
final Set<Set<Integer>> stronglyConnectedComponents = new HashSet<>();
// a vertex will be added into this stack when it is visited for the first time
final Deque<... | @Test
void testLargeGraph() {
final int n = 100000;
final List<List<Integer>> edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
edges.add(Collections.singletonList((i + 1) % n));
}
final Set<Set<Integer>> result = computeStronglyConnectedComponents(n, edge... |
@Override
public void release() {
try {
ioExecutor.shutdown();
if (!ioExecutor.awaitTermination(5L, TimeUnit.MINUTES)) {
throw new TimeoutException("Timeout to shutdown the flush thread.");
}
dataFileChannel.close();
} catch (Exception ... | @Test
void testRelease() {
AtomicBoolean isReleased = new AtomicBoolean(false);
TestingProducerMergedPartitionFileIndex partitionFileIndex =
new TestingProducerMergedPartitionFileIndex.Builder()
.setIndexFilePath(new File(tempFolder.toFile(), "testIndex").toPa... |
@Override
protected void validateDataImpl(TenantId tenantId, TenantProfile tenantProfile) {
validateString("Tenant profile name", tenantProfile.getName());
if (tenantProfile.getProfileData() == null) {
throw new DataValidationException("Tenant profile data should be specified!");
... | @Test
void testValidateNameInvocation() {
TenantProfile tenantProfile = new TenantProfile();
tenantProfile.setName("Sandbox");
TenantProfileData tenantProfileData = new TenantProfileData();
tenantProfileData.setConfiguration(new DefaultTenantProfileConfiguration());
tenantPro... |
@Override
public TimestampedKeyValueStore<K, V> build() {
KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof TimestampedBytesStore)) {
if (store.persistent()) {
store = new KeyValueToTimestampedKeyValueByteStoreAdapter(store);
} e... | @Test
public void shouldHaveMeteredStoreAsOuterStore() {
setUp();
final TimestampedKeyValueStore<String, String> store = builder.build();
assertThat(store, instanceOf(MeteredTimestampedKeyValueStore.class));
} |
protected WordComposer getCurrentComposedWord() {
return mWord;
} | @Test
public void testSuggestionsRestartHappyPathWhenDisabled() {
simulateFinishInputFlow();
SharedPrefsHelper.setPrefsValue(R.string.settings_key_allow_suggestions_restart, false);
simulateOnStartInputFlow();
mAnySoftKeyboardUnderTest.simulateTextTyping("hell yes");
Assert.assertEquals(
... |
@Override
public Stream<HoodieInstant> getCandidateInstants(HoodieTableMetaClient metaClient, HoodieInstant currentInstant,
Option<HoodieInstant> lastSuccessfulInstant) {
HoodieActiveTimeline activeTimeline = metaClient.reloadActiveTimeline();
if (Clustering... | @Test
public void testConcurrentWritesWithInterleavingSuccessfulReplace() throws Exception {
createCommit(metaClient.createNewInstantTime(), metaClient);
HoodieActiveTimeline timeline = metaClient.getActiveTimeline();
// consider commits before this are all successful
Option<HoodieInstant> lastSuccess... |
public static Criterion matchOduSignalType(OduSignalType signalType) {
return new OduSignalTypeCriterion(signalType);
} | @Test
public void testMatchOduSignalTypeMethod() {
OduSignalType oduSigType = OduSignalType.ODU2;
Criterion matchoduSignalType = Criteria.matchOduSignalType(oduSigType);
OduSignalTypeCriterion oduSignalTypeCriterion =
checkAndConvert(matchoduSignalType,
... |
public static TransformExecutorService serial(ExecutorService executor) {
return new SerialTransformExecutor(executor);
} | @Test
public void serialScheduleTwoWaitsForFirstToComplete() {
@SuppressWarnings("unchecked")
DirectTransformExecutor<Object> first = mock(DirectTransformExecutor.class);
@SuppressWarnings("unchecked")
DirectTransformExecutor<Object> second = mock(DirectTransformExecutor.class);
TransformExecutor... |
public List<SubjectAlternativeName> getSubjectAlternativeNames() {
return getExtensions()
.map(extensions -> GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName))
.map(SubjectAlternativeName::fromGeneralNames)
.orElse(List.of());
} | @Test
void can_read_subject_alternative_names() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
SubjectAlternativeName san1 = new SubjectAlternativeName(DNS, "san1.com");
SubjectAlternativeName san2 = new Su... |
@Override
public BackgroundException map(final IOException e) {
final StringBuilder buffer = new StringBuilder();
this.append(buffer, e.getMessage());
if(e instanceof FTPConnectionClosedException) {
return new ConnectionRefusedException(buffer.toString(), e);
}
if... | @Test
public void testSocketTimeout() {
assertEquals(ConnectionTimeoutException.class, new FTPExceptionMappingService()
.map(new SocketTimeoutException()).getClass());
assertEquals(ConnectionTimeoutException.class, new FTPExceptionMappingService()
.map("message", new SocketTi... |
@Override
public Set<String> requiredPermissions() {
// When there are no streams the event processor will search in all streams so we need to require the
// generic stream permission.
if (streams().isEmpty()) {
return Collections.singleton(RestPermissions.STREAMS_READ);
... | @Test
@MongoDBFixtures("aggregation-processors.json")
public void requiredPermissions() {
assertThat(dbService.get("54e3deadbeefdeadbeefaffe")).get().satisfies(definition ->
assertThat(definition.config().requiredPermissions()).containsOnly("streams:read:stream-a", "streams:read:stream-b... |
public ResourceProfile subtract(final ResourceProfile other) {
checkNotNull(other, "Cannot subtract with null resources");
if (equals(ANY) || other.equals(ANY)) {
return ANY;
}
if (this.equals(UNKNOWN) || other.equals(UNKNOWN)) {
return UNKNOWN;
}
... | @Test
void testSubtract() {
final ResourceProfile rp1 =
ResourceProfile.newBuilder()
.setCpuCores(1.0)
.setTaskHeapMemoryMB(100)
.setTaskOffHeapMemoryMB(100)
.setManagedMemoryMB(100)
... |
@Override
public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException {
final AttributedList<Path> children = new AttributedList<>();
if(replies.isEmpty()) {
return children;
}
// At least one entry successfully parsed... | @Test(expected = FTPInvalidListException.class)
public void testMlsdPdir() throws Exception {
Path path = new Path(
"/www", EnumSet.of(Path.Type.directory));
String[] replies = new String[]{
"Type=pdir;Perm=e;Unique=keVO1+d?3; ..", //skipped
};
new FT... |
@SuppressWarnings("unchecked")
@Override
protected Object createObject(ValueWrapper<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) {
// simple types
if (initialInstance.isValid() && !(initialInstance.getValue() instanceof Map)) {
... | @Test
public void createObject_directMappingSimpleTypeNull() {
Map<List<String>, Object> params = new HashMap<>();
params.put(List.of(), null);
ValueWrapper<Object> initialInstance = runnerHelper.getDirectMapping(params);
Object objectRaw = runnerHelper.createObject(initialInstance,... |
public static void checkPhysicalLogicalTypeCompatible(
LogicalType physicalFieldType,
LogicalType logicalFieldType,
String physicalFieldName,
String logicalFieldName,
boolean isSource) {
if (isSource) {
checkIfCompatible(
... | @Test
void testCheckPhysicalLogicalTypeCompatible() {
TableSchema tableSchema =
TableSchema.builder()
.field("a", DataTypes.VARCHAR(2))
.field("b", DataTypes.DECIMAL(20, 2))
.build();
TableSink tableSink = new Te... |
public void callLogout() {
call("logout", null);
} | @Test
public void callLogout() {
SensorsDataAPI sensorsDataAPI = SAHelper.initSensors(mApplication);
sensorsDataAPI.addFunctionListener(new SAFunctionListener() {
@Override
public void call(String function, JSONObject args) {
Assert.assertEquals("logout", func... |
@Override
public byte[] serialize(final String topic, final List<?> data) {
if (data == null) {
return null;
}
try {
final StringWriter stringWriter = new StringWriter();
final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
csvPrinter.printRecord(() -> new FieldI... | @Test
public void shouldSerializeNegativeDecimalWithAsStringWithPaddedZeros() {
// Given:
givenSingleColumnSerializer(SqlTypes.decimal(4, 3));
final List<?> values = Collections.singletonList(new BigDecimal("-1.120"));
// When:
final byte[] bytes = serializer.serialize("", values);
// Then:... |
public static String generateFileName(String string) {
string = StringUtils.stripAccents(string);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isSpaceChar(c)
&& (buf.lengt... | @Test
public void testFeedTitleContainsApostrophe() {
String result = FileNameGenerator.generateFileName("Feed's Title ...");
assertEquals("Feeds Title", result);
} |
@ScalarOperator(SUBTRACT)
@SqlType(StandardTypes.TINYINT)
public static long subtract(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right)
{
try {
return SignedBytes.checkedCast(left - right);
}
catch (IllegalArgumentException e) {
... | @Test
public void testSubtract()
{
assertFunction("TINYINT'37' - TINYINT'37'", TINYINT, (byte) 0);
assertFunction("TINYINT'37' - TINYINT'17'", TINYINT, (byte) (37 - 17));
assertFunction("TINYINT'17' - TINYINT'37'", TINYINT, (byte) (17 - 37));
assertFunction("TINYINT'17' - TINYINT... |
public static void checkValidProjectId(String idToCheck) {
if (idToCheck.length() < MIN_PROJECT_ID_LENGTH) {
throw new IllegalArgumentException("Project ID " + idToCheck + " cannot be empty.");
}
if (idToCheck.length() > MAX_PROJECT_ID_LENGTH) {
throw new IllegalArgumentException(
"Pro... | @Test
public void testCheckValidProjectIdWhenIdIsValid() {
checkValidProjectId("'project-id-9'!");
} |
public static IRubyObject deep(final Ruby runtime, final Object input) {
if (input == null) {
return runtime.getNil();
}
final Class<?> cls = input.getClass();
final Rubyfier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return con... | @Test
public void testDeepWithString() {
Object result = Rubyfier.deep(RubyUtil.RUBY, "foo");
assertEquals(RubyString.class, result.getClass());
assertEquals("foo", result.toString());
} |
public static int calAvgBucketNumOfRecentPartitions(OlapTable olapTable, int recentPartitionNum,
boolean enableAutoTabletDistribution) {
// 1. If the partition is less than recentPartitionNum, use backendNum to speculate the bucketNum
// Or the ... | @Test
public void testCalAvgBucketNumOfRecentPartitions_CalculateByDataSize() {
List<Partition> partitions = new ArrayList<>();
partitions.add(partition);
when(olapTable.getPartitions()).thenReturn(partitions);
when(olapTable.getRecentPartitions(anyInt())).thenReturn(partitions);
... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldFindMiddleVarargWithSomeNullValues() {
// Given:
givenFunctions(
function(EXPECTED, 1, INT, STRING_VARARGS, STRING)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(Arrays.asList(
SqlArgument.of(SqlTypes.INTEGER), null, SqlArgument.of... |
@Override
public int getWorkerMaxCount() {
return workerThreadCount;
} | @Test
public void getWorkerMaxCount_returns_10_whichever_the_value_returned_by_WorkerCountProvider() {
int value = randomValidWorkerCount();
workerCountProvider.set(value);
assertThat(new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider).getWorkerMaxCount()).isEqualTo(10);
} |
public String serial() {
return get(SERIAL, null);
} | @Test
public void testSetSerial() {
SW_BDC.serial(SERIAL_NEW);
assertEquals("Incorrect serial", SERIAL_NEW, SW_BDC.serial());
} |
public XmlStreamInfo information() throws IOException {
if (information.problem != null) {
return information;
}
if (XMLStreamConstants.START_DOCUMENT != reader.getEventType()) {
information.problem = new IllegalStateException("Expected START_DOCUMENT");
retu... | @Test
public void emptyDocument() throws IOException {
XmlStreamDetector detector = new XmlStreamDetector(new ByteArrayInputStream(new byte[0]));
assertFalse(detector.information().isValid());
} |
public void checkExecutePrerequisites(final ExecutionContext executionContext) {
ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext)));
} | @Test
void assertCheckExecutePrerequisitesWhenExecuteDDLInXATransaction() {
ExecutionContext executionContext = new ExecutionContext(
new QueryContext(createMySQLCreateTableStatementContext(), "", Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMe... |
public Arrangement(String[] datas) {
this.datas = datas;
} | @Test
public void arrangementTest() {
long result = Arrangement.count(4, 2);
assertEquals(12, result);
result = Arrangement.count(4, 1);
assertEquals(4, result);
result = Arrangement.count(4, 0);
assertEquals(1, result);
long resultAll = Arrangement.countAll(4);
assertEquals(64, resultAll);
} |
public static PennTreebankPOS tag(String word) {
for (int i = 0; i < REGEX.length; i++) {
if (REGEX[i].matcher(word).matches()) {
return REGEX_POS[i];
}
}
return null;
} | @Test
public void testTag() {
System.out.println("tag");
assertEquals(PennTreebankPOS.CD, RegexPOSTagger.tag("123"));
assertEquals(PennTreebankPOS.CD, RegexPOSTagger.tag("1234567890"));
assertEquals(PennTreebankPOS.CD, RegexPOSTagger.tag("123.45"));
assertEquals(PennTreebankP... |
public static TableElements parse(final String schema, final TypeRegistry typeRegistry) {
return new SchemaParser(typeRegistry).parse(schema);
} | @Test
public void shouldThrowOnReservedWord() {
// Given:
final String schema = "CREATE INTEGER";
// Expect:
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> parser.parse(schema)
);
// Then:
assertThat(e.getMessage(), containsString("Error parsing... |
@ProcessElement
public ProcessContinuation processElement(
@Element PartitionMetadata partition,
RestrictionTracker<TimestampRange, com.google.cloud.Timestamp> tracker,
OutputReceiver<DataChangeRecord> receiver,
ManualWatermarkEstimator<Instant> watermarkEstimator,
BundleFinalizer bundle... | @Test
public void testQueryChangeStreamMode() {
when(queryChangeStreamAction.run(any(), any(), any(), any(), any()))
.thenReturn(ProcessContinuation.stop());
final ProcessContinuation result =
doFn.processElement(partition, tracker, receiver, watermarkEstimator, bundleFinalizer);
assertE... |
@Override
public ConfigDef config() {
return CONFIG_DEF;
} | @Test
public void testConnectorConfigValidation() {
List<ConfigValue> configValues = connector.config().validate(sinkProperties);
for (ConfigValue val : configValues) {
assertEquals(0, val.errorMessages().size(), "Config property errors: " + val.errorMessages());
}
} |
@Override
public MongoPaginationHelper<T> grandTotalFilter(Bson grandTotalFilter) {
return new DefaultMongoPaginationHelper<>(collection, filter, sort, perPage, includeGrandTotal,
grandTotalFilter, collation);
} | @Test
void testGrandTotalFilter() {
final Bson filter = Filters.in("name", "A", "B", "C");
assertThat(paginationHelper.includeGrandTotal(true).grandTotalFilter(filter).page(1).grandTotal())
.isEqualTo(paginationHelper.includeGrandTotal(true).grandTotalFilter(filter).page(1, alwaysTru... |
protected Map<String, String[]> generateParameterMap(MultiValuedTreeMap<String, String> qs, ContainerConfig config) {
Map<String, String[]> output;
Map<String, List<String>> formEncodedParams = getFormUrlEncodedParametersMap();
if (qs == null) {
// Just transform the List<String> v... | @Test
void parameterMap_generateParameterMap_formEncodedAndQueryString() {
AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(formEncodedAndQueryString, mockContext, null, config);
Map<String, String[]> paramMap = null;
try {
paramMap = request.generateParameter... |
public Printed<K, V> withKeyValueMapper(final KeyValueMapper<? super K, ? super V, String> mapper) {
Objects.requireNonNull(mapper, "mapper can't be null");
this.mapper = mapper;
return this;
} | @Test
public void shouldThrowNullPointerExceptionIfMapperIsNull() {
assertThrows(NullPointerException.class, () -> sysOutPrinter.withKeyValueMapper(null));
} |
@Override
public AuthorizationPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
Capabilities capabilities = capabilities(descriptor.id());
PluggableInstanceSettings authConfigSettings = authConfigSettings(descriptor.id());
PluggableInstanceSettings roleSettings = roleSettings(descri... | @Test
public void shouldBuildPluginInfoWithImage() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
Image icon = new Image("content_type", "data", "hash");
when(extension.getIcon(descriptor.id())).thenReturn(icon);
AuthorizationPluginInfo plugin... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<ListQueries> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final RemoteHostExecutor remoteHostExecutor = RemoteHostExecuto... | @Test
public void shouldIncludeUnresponsiveIfShowQueriesExtendedFutureThrowsException() {
// Given
when(sessionProperties.getInternalRequest()).thenReturn(false);
final ConfiguredStatement<?> showQueries = engine.configure("SHOW QUERIES EXTENDED;");
final PersistentQueryMetadata metadata = givenPersis... |
public boolean isAuthCredentials() {
return StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password);
} | @Test
void authenticated_cluster_connection() {
// when
ClusterConnection connection = ClusterConnection.builder()
.contactPoints("127.0.0.1")
.port(29042)
.localDatacenter("dc1")
.username("will")
.password("will-password")
.bu... |
@Udf(description = "Returns a new string encoded using the outputEncoding ")
public String encode(
@UdfParameter(
description = "The source string. If null, then function returns null.") final String str,
@UdfParameter(
description = "The input encoding."
+ " If null, the... | @Test
public void shouldEncodeUtf8ToAscii() {
assertThat(udf.encode("Example!", "utf8", "ascii"), is("Example!"));
assertThat(udf.encode("Plant trees", "utf8", "ascii"), is("Plant trees"));
assertThat(udf.encode("1 + 1 = 1", "utf8", "ascii"), is("1 + 1 = 1"));
assertThat(udf.encode("Ελλάδα", "utf8", "... |
@Override
public T readFrom(
Class<T> cls, Type type, Annotation[] anns, MediaType mt,
MultivaluedMap<String, String> headers, InputStream is)
throws IOException,
WebApplicationException {
DataFormat format = getValidDataFormat(mt);
try {
@... | @Test
public void testReadFrom() throws Exception {
DataFormatProvider<Book> p = new DataFormatProvider<>();
p.setFormat("text/plain", new TestDataFormat());
ByteArrayInputStream bis = new ByteArrayInputStream("dataformat".getBytes());
Book b = p.readFrom(Book.class, Book.class, new... |
public GoConfigHolder loadConfigHolder(final String content, Callback callback) throws Exception {
CruiseConfig configForEdit;
CruiseConfig config;
LOGGER.debug("[Config Save] Loading config holder");
configForEdit = deserializeConfig(content);
if (callback != null) callback.call... | @Test
void shouldLoadHgConfigWithBranchAttributePostSchemaVersion123() throws Exception {
String content = config(
"""
<config-repos>
<config-repo id="Test" pluginId="cd.go.json">
<hg url="https://domain.com"... |
public Database getDb() throws MetaNotFoundException {
// get db
Database db = GlobalStateMgr.getCurrentState().getDb(dbId);
if (db == null) {
throw new MetaNotFoundException("Database " + dbId + " already has been deleted");
}
return db;
} | @Test
public void testGetDbNotExists(@Mocked GlobalStateMgr globalStateMgr) {
LoadJob loadJob = new BrokerLoadJob();
Deencapsulation.setField(loadJob, "dbId", 1L);
new Expectations() {
{
globalStateMgr.getDb(1L);
minTimes = 0;
resul... |
private RemotingCommand getAllSubscriptionGroup(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
String content = this.brokerController.getSubscriptionGroupManager().encode();
... | @Test
public void testGetAllSubscriptionGroup() throws RemotingCommandException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_SUBSCRIPTIONGROUP_CONFIG, null);
RemotingCommand response = adminBrokerProcessor.processRequest(handlerContext, request);
asser... |
@Override
public void doRun() {
if (isServerInPreflightMode.get()) {
// we don't want to automatically trigger CSRs during preflight, don't run it if the preflight is still not finished or skipped
LOG.debug("Datanode still in preflight mode, skipping cert renewal task");
... | @Test
void testExpiringInFarFuture() throws Exception {
final DatanodeKeystore datanodeKeystore = datanodeKeystore(Duration.ofDays(30));
final CsrRequester csrRequester = Mockito.mock(CsrRequester.class);
final DataNodeCertRenewalPeriodical periodical = new DataNodeCertRenewalPeriodical(data... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final JsonNode event;
try {
event = objectMapper.readTree(payload);
if (event == null || event.isMissingNode()) {
throw new ... | @Test
public void decodeMessagesHandlesGenericBeatWithKubernetes() throws Exception {
final Message message = codec.decode(messageFromJson("generic-with-kubernetes.json"));
assertThat(message).isNotNull();
assertThat(message.getMessage()).isEqualTo("-");
assertThat(message.getSource(... |
AwsCredentials credentials() {
if (!StringUtil.isNullOrEmptyAfterTrim(awsConfig.getAccessKey())) {
return AwsCredentials.builder()
.setAccessKey(awsConfig.getAccessKey())
.setSecretKey(awsConfig.getSecretKey())
.build();
}
if (!StringUt... | @Test
public void credentialsEcs() {
// given
AwsConfig awsConfig = AwsConfig.builder().build();
given(awsMetadataApi.credentialsEcs()).willReturn(CREDENTIALS);
given(environment.isRunningOnEcs()).willReturn(true);
AwsCredentialsProvider credentialsProvider = new AwsCredentia... |
public <T extends S3ClientBuilder> void applyServiceConfigurations(T builder) {
builder
.dualstackEnabled(isDualStackEnabled)
.serviceConfiguration(
S3Configuration.builder()
.pathStyleAccessEnabled(isPathStyleAccess)
.useArnRegionEnabled(isUseArnRegionEna... | @Test
public void testApplyS3ServiceConfigurations() {
Map<String, String> properties = Maps.newHashMap();
properties.put(S3FileIOProperties.DUALSTACK_ENABLED, "true");
properties.put(S3FileIOProperties.PATH_STYLE_ACCESS, "true");
properties.put(S3FileIOProperties.USE_ARN_REGION_ENABLED, "true");
... |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetUncleCountByBlockNumber() throws Exception {
web3j.ethGetUncleCountByBlockNumber(DefaultBlockParameter.valueOf(Numeric.toBigInt("0xe8")))
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_getUncleCountByBlockNumber\","
... |
public boolean[] decodeBoolArray(final byte[] parameterBytes, final boolean isBinary) {
ShardingSpherePreconditions.checkState(!isBinary, () -> new UnsupportedSQLOperationException("binary mode"));
String parameterValue = new String(parameterBytes, StandardCharsets.UTF_8);
Collection<String> par... | @Test
void assertParseBoolArrayNormalTextMode() {
boolean[] actual = DECODER.decodeBoolArray("{\"true\",\"false\"}".getBytes(), false);
assertThat(actual.length, is(2));
assertTrue(actual[0]);
assertFalse(actual[1]);
} |
@Override
public HttpResponseOutputStream<File> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final DelayedHttpEntityCallable<File> command = new DelayedHttpEntityCallable<File>(file) {
@Override
public File call(f... | @Test
public void testWriteWithLock() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random())... |
@Override
public void createRouter(Router osRouter) {
checkNotNull(osRouter, ERR_NULL_ROUTER);
checkArgument(!Strings.isNullOrEmpty(osRouter.getId()), ERR_NULL_ROUTER_ID);
osRouterStore.createRouter(osRouter);
log.info(String.format(MSG_ROUTER, deriveResourceName(osRouter), MSG_CREA... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateRouter() {
target.createRouter(ROUTER);
target.createRouter(ROUTER);
} |
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("response_example")
.setDescription("Display web service response example")
.setResponseExample(getClass().getResource("response_example-example.json"))
.setSince("4.4... | @Test
public void response_example() {
MetricWs metricWs = new MetricWs();
metricWs.define(context);
newRequest()
.setParam("controller", "api/metric")
.setParam("action", "create")
.execute()
.assertJson(getClass(), "response_example.json");
} |
@ConstantFunction(name = "hours_sub", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true)
public static ConstantOperator hoursSub(ConstantOperator date, ConstantOperator hour) {
return ConstantOperator.createDatetimeOrNull(date.getDatetime().minusHours(hour.getInt()));
} | @Test
public void hoursSub() {
assertEquals("2015-03-22T23:23:55",
ScalarOperatorFunctions.hoursSub(O_DT_20150323_092355, O_INT_10).getDatetime().toString());
} |
@Override
public OUT nextRecord(OUT record) throws IOException {
OUT returnRecord = null;
do {
returnRecord = super.nextRecord(record);
} while (returnRecord == null && !reachedEnd());
return returnRecord;
} | @Test
void testReadSparseWithMask() {
try {
final String fileContent =
"111&&222&&333&&444&&555&&666&&777&&888&&999&&000&&\n"
+ "000&&999&&888&&777&&666&&555&&444&&333&&222&&111&&";
final FileInputSplit split = createTempFile(fileConten... |
@Override
public VplsData getVpls(String vplsName) {
requireNonNull(vplsName);
return vplsStore.getVpls(vplsName);
} | @Test
public void testGetVpls() {
VplsData vplsData = VplsData.of(VPLS1);
vplsData.state(ADDED);
vplsStore.addVpls(vplsData);
VplsData result = vplsManager.getVpls(VPLS1);
assertEquals(vplsData, result);
result = vplsManager.getVpls(VPLS2);
assertNull(result... |
@Override
public String upgradeFirmwareOndemand(String target) {
DriverHandler handler = handler();
NetconfController controller = handler.get(NetconfController.class);
MastershipService mastershipService = handler.get(MastershipService.class);
DeviceId ncDeviceId = handler.data().de... | @Test
public void testValidOndemandFirmwareUpgrade() throws Exception {
String reply;
String target;
for (int i = ZERO; i < VALID_ONDEMAND_FWDL_TCS.length; i++) {
target = VALID_ONDEMAND_FWDL_TCS[i];
currentKey = i;
reply = voltConfig.upgradeFirmwareOndem... |
public static JibContainerBuilder toJibContainerBuilder(
ArtifactProcessor processor,
CommonCliOptions commonCliOptions,
CommonContainerConfigCliOptions commonContainerConfigCliOptions,
ConsoleLogger logger)
throws IOException, InvalidImageReferenceException {
String baseImage = common... | @Test
public void testToJibContainerBuilder_nonJettyBaseImageSpecifiedAndNoEntrypoint()
throws IOException, InvalidImageReferenceException {
JibContainerBuilder containerBuilder =
WarFiles.toJibContainerBuilder(
mockStandardWarExplodedProcessor,
mockCommonCliOptions,
... |
public Future<Void> singlePodDeploymentRollingUpdate(Reconciliation reconciliation, String namespace, String name, long operationTimeoutMs) {
return podOperations.listAsync(namespace, Labels.EMPTY.withStrimziName(name))
.compose(pods -> {
if (pods != null && !pods.isEmpty()) ... | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testSinglePodDeploymentRollingUpdateWithMissingPod(VertxTestContext context) {
String depName = "my-dep";
String podName = depName + "-123456";
// Mock Pod handling
KubernetesResourceList mockPodResourceList = mock(... |
public String getPassword() {
if(StringUtils.isEmpty(password)) {
if(this.isAnonymousLogin()) {
return PreferencesFactory.get().getProperty("connection.login.anon.pass");
}
}
return password;
} | @Test
public void testAnonymous() {
Credentials c = new Credentials("anonymous", "");
assertEquals("cyberduck@example.net", c.getPassword());
} |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the number of milliseconds since 1970-01-01 00:00:00 UTC/GMT."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'."
+ " The system default time... | @Test
public void shouldThrowOnNullDateFormat() {
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udf.stringToTimestamp("2021-12-01", null)
);
// Then:
assertThat(e.getMessage(), Matchers.containsString("Failed to parse timestamp '2021-12-01' with formatter 'null'... |
public static <K, V> Cache<K, V> noop() {
return forMaximumBytes(0L);
} | @Test
public void testNoopCache() throws Exception {
Cache<String, String> cache = Caches.noop();
cache.put("key", "value");
assertNull(cache.peek("key"));
assertEquals("value", cache.computeIfAbsent("key", (unused) -> "value"));
assertNull(cache.peek("key"));
} |
public static boolean isGetDeviceInfo(String androidId, String oaid) {
try {
return !TextUtils.isEmpty(androidId) ||
!TextUtils.isEmpty(oaid);
} catch (Exception e) {
SALog.printStackTrace(e);
}
return false;
} | @Test
public void isGetDeviceInfo() {
} |
public String delayedServiceResponse() {
try {
return this.delayedService.attemptRequest();
} catch (RemoteServiceException e) {
return e.getMessage();
}
} | @Test
void testDelayedRemoteResponseSuccess() {
var delayedService = new DelayedRemoteService(System.nanoTime()-2*1000*1000*1000, 2);
var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000,
1,
2 * 1000 * 1000 * 1000);
var monitoringService = new MonitoringServic... |
@VisibleForTesting
protected void tombstone() {
var now = System.currentTimeMillis();
if (now - lastTombstonedAt < tombstoneDelayInMillis) {
return;
}
var lastSuccessfulTombstonedAt = lastTombstonedAt;
lastTombstonedAt = now; // dedup first
brokerLoadDataS... | @Test
public void testTombstone() throws IllegalAccessException, InterruptedException {
var target = spy(new BrokerLoadDataReporter(pulsar, broker, store));
target.handleEvent(bundle,
new ServiceUnitStateData(ServiceUnitState.Assigning, broker, VERSION_ID_INIT), null);
veri... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
new SwiftAttributesFinderFeature(session).find(file, listener);
return true;
}
catch(N... | @Test
public void testFindContainer() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
assertTrue(new SwiftFindFeature(session).find(container));
} |
@Override
public int compareTo(DateTimeStamp dateTimeStamp) {
return comparator.compare(this,dateTimeStamp);
} | @Test
void testCompareLessThan() {
DateTimeStamp smaller = new DateTimeStamp("2018-04-04T09:10:00.586-0100");
DateTimeStamp greater = new DateTimeStamp("2018-04-04T10:10:00.587-0100");
assertEquals(-1, smaller.compareTo(greater));
} |
public void markAsUnchanged(DefaultInputFile file) {
if (isFeatureActive()) {
if (file.status() != InputFile.Status.SAME) {
LOG.error("File '{}' was marked as unchanged but its status is {}", file.getProjectRelativePath(), file.status());
} else {
LOG.debug("File '{}' marked as unchanged... | @Test
public void not_active_if_property_not_defined() {
UnchangedFilesHandler handler = new UnchangedFilesHandler(new MapSettings().asConfig(), defaultBranchConfig, executingSensorContext);
handler.markAsUnchanged(file);
verifyNoInteractions(file);
assertThat(logTester.logs()).isEmpty();
} |
@Override
public void audit(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule) {
Collection<ShardingAuditStrategyConfiguration> auditStrategies = getShardingAuditStrategies(queryContext.getSqlStatementContext(), rule);
... | @Test
void assertCheckSuccess() {
RuleMetaData globalRuleMetaData = mock(RuleMetaData.class);
new ShardingSQLAuditor().audit(new QueryContext(sqlStatementContext, "", Collections.emptyList(), hintValueContext, mockConnectionContext(), mock(ShardingSphereMetaData.class)),
globalRuleMe... |
public static String getDoneFileName(JobIndexInfo indexInfo)
throws IOException {
return getDoneFileName(indexInfo,
JHAdminConfig.DEFAULT_MR_HS_JOBNAME_LIMIT);
} | @Test
public void testUserNamePercentEncoding() throws IOException {
JobIndexInfo info = new JobIndexInfo();
JobID oldJobId = JobID.forName(JOB_ID);
JobId jobId = TypeConverter.toYarn(oldJobId);
info.setJobId(jobId);
info.setSubmitTime(Long.parseLong(SUBMIT_TIME));
info.setUser(USER_NAME_WITH_... |
CompletableFuture<Void> beginExecute(
@Nonnull List<? extends Tasklet> tasklets,
@Nonnull CompletableFuture<Void> cancellationFuture,
@Nonnull ClassLoader jobClassLoader
) {
final ExecutionTracker executionTracker = new ExecutionTracker(tasklets.size(), cancellationFuture... | @Test
public void when_tryCompleteOnReturnedFuture_then_fails() {
// Given
final MockTasklet t = new MockTasklet().callsBeforeDone(Integer.MAX_VALUE);
CompletableFuture<Void> f = tes.beginExecute(singletonList(t), cancellationFuture, classLoader);
// When - Then
assertThrows... |
protected boolean isLoggerSafe(ILoggingEvent event) {
for (String safeLogger : SAFE_LOGGERS) {
if (event.getLoggerName().startsWith(safeLogger)) {
return true;
}
}
return false;
} | @Test
void isLoggerSafeShouldReturnFalseWhenLoggerNameDoesNotStartWithSafeLogger() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
CRLFLogConverter converter = new CRLFLogConverter();
boolean result = c... |
@Override
public Optional<ProtobufSystemInfo.SystemInfo> retrieveSystemInfo() {
return call(SystemInfoActionClient.INSTANCE);
} | @Test
public void retrieveSystemInfo_returns_absent_if_process_is_down() {
Optional<ProtobufSystemInfo.SystemInfo> info = underTest.retrieveSystemInfo();
assertThat(info).isEmpty();
} |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Server ID", server.getId());
setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel());
... | @Test
public void toProtobuf_whenNoAllowsToSignUpEnabledIdentityProviders_shouldWriteNothing() {
when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(emptyList());
ProtobufSystemInfo.Section protobuf = underTest.toProtobuf();
assertThatAttributeDoesNotExist(protobuf, "Exte... |
@Override
public void remove(String name) {
this.indexSpecs.remove(name);
} | @Test
void remove() {
var specs = new DefaultIndexSpecs();
var nameSpec = primaryKeyIndexSpec(FakeExtension.class);
specs.add(nameSpec);
assertThat(specs.contains(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME)).isTrue();
specs.remove(PrimaryKeySpecUtils.PRIMARY_INDEX_NAME);
... |
@Override
public void uncaughtException(Thread t, Throwable e) {
if(ShutdownHookManager.get().isShutdownInProgress()) {
LOG.error("Thread " + t + " threw an Throwable, but we are shutting " +
"down, so ignoring this", e);
} else if(e instanceof Error) {
try {
LOG.error(FATAL,
... | @Test
void testUncaughtExceptionHandlerWithRuntimeException()
throws InterruptedException {
final YarnUncaughtExceptionHandler spyYarnHandler = spy(exHandler);
final YarnRuntimeException yarnException = new YarnRuntimeException(
"test-yarn-runtime-exception");
final Thread yarnThread = new T... |
public void updateTopicRouteInfoFromNameServer() {
Set<String> topicList = new HashSet<>();
// Consumer
{
for (Entry<String, MQConsumerInner> entry : this.consumerTable.entrySet()) {
MQConsumerInner impl = entry.getValue();
if (impl != null) {
... | @Test
public void testUpdateTopicRouteInfoFromNameServer() throws RemotingException, InterruptedException, MQClientException {
brokerAddrTable.put(defaultBroker, createBrokerAddrMap());
consumerTable.put(group, createMQConsumerInner());
DefaultMQProducer defaultMQProducer = mock(DefaultMQPro... |
public static void addShutdownHook(Runnable runnable) {
Runtime.getRuntime().addShutdownHook(new Thread(runnable));
} | @Test
void testAddShutdownHook() {
Runnable shutdownHook = () -> {
};
ThreadUtils.addShutdownHook(shutdownHook);
// It seems no way to check it.
} |
@Override
public Map<RedisClusterNode, Collection<RedisClusterNode>> clusterGetMasterSlaveMap() {
Iterable<RedisClusterNode> res = clusterGetNodes();
Set<RedisClusterNode> masters = new HashSet<RedisClusterNode>();
for (Iterator<RedisClusterNode> iterator = res.iterator(); iterator.... | @Test
public void testClusterGetMasterSlaveMap() {
Map<RedisClusterNode, Collection<RedisClusterNode>> map = connection.clusterGetMasterSlaveMap();
assertThat(map).hasSize(3);
for (Collection<RedisClusterNode> slaves : map.values()) {
assertThat(slaves).hasSize(1);
}
... |
@ConstantFunction.List(list = {
@ConstantFunction(name = "years_add", argTypes = {DATETIME,
INT}, returnType = DATETIME, isMonotonic = true),
@ConstantFunction(name = "years_add", argTypes = {DATE, INT}, returnType = DATE, isMonotonic = true)
})
public static Constant... | @Test
public void yearsAdd() {
assertEquals("2025-03-23T09:23:55",
ScalarOperatorFunctions.yearsAdd(O_DT_20150323_092355, O_INT_10).getDatetime().toString());
} |
public final void isAtMost(int other) {
isAtMost((long) other);
} | @Test
public void isAtMost_int() {
expectFailureWhenTestingThat(2L).isAtMost(1);
assertThat(2L).isAtMost(2);
assertThat(2L).isAtMost(3);
} |
public Properties createProperties(Props props, File logDir) {
Log4JPropertiesBuilder log4JPropertiesBuilder = new Log4JPropertiesBuilder(props);
RootLoggerConfig config = newRootLoggerConfigBuilder()
.setNodeNameField(getNodeNameWhenCluster(props))
.setProcessId(ProcessId.ELASTICSEARCH)
.buil... | @Test
public void createProperties_sets_root_logger_to_process_property_over_global_property_if_both_set() throws IOException {
File logDir = temporaryFolder.newFolder();
Properties properties = underTest.createProperties(
newProps(
"sonar.log.level", "DEBUG",
"sonar.log.level.es", "TRAC... |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM
&& event.getType() != ChatMessageType.GAMEMESSAGE
&& event.getType() != ChatMessageType.MESBOX)
{
return;
}
final var msg = event.getMessage();
if (WOOD_CUT_PATTERN.matcher(msg).matches())
{
... | @Test
public void testBirdsNest()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", BIRDS_NEST_MESSAGE, "", 0);
when(woodcuttingConfig.showNestNotification()).thenReturn(Notification.ON);
woodcuttingPlugin.onChatMessage(chatMessage);
verify(notifier).notify(Notification.ON, "... |
public static List<Integer> asIntegerList(@Nonnull int[] array) {
checkNotNull(array, "null array");
return new AbstractList<>() {
@Override
public Integer get(int index) {
return array[index];
}
@Override
public int size() {
... | @Test(expected = NullPointerException.class)
public void testToIntegerList_whenNull() {
asIntegerList(null);
} |
public void triggerRemoveAll(final String selectorId) {
synchronized (lock) {
healthyUpstream.remove(selectorId);
unhealthyUpstream.remove(selectorId);
}
} | @Test
public void testTriggerRemoveAll() {
final String selectorId = "s1";
Upstream upstream = mock(Upstream.class);
healthCheckTask.triggerAddOne(selectorId, upstream);
healthCheckTask.triggerRemoveAll(selectorId);
assertFalse(healthCheckTask.getHealthyUpstream().containsKey... |
public static String formatDate(Date date, String format) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
} | @Test
public void testFormatDate() {
Date currentDate = DateUtil.getCurrentDate();
String dateStr = DateUtil.formatDate(currentDate, "yyyy-MM-dd HH:mm:ss");
Assertions.assertNotNull(dateStr);
} |
public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
if (index + substring.length() > str.length()) {
return false;
}
for (int i = 0; i < substring.length(); i++) {
if (str.charAt(index + i) != substring.charAt(i)) {
... | @Test
public void testSubstringMatchReturningTrue() {
StringBuffer stringBuffer = new StringBuffer("ZP~>xz1;");
assertTrue(StringUtil.substringMatch(stringBuffer, 0, stringBuffer));
} |
public static boolean isCollectionOrMap(String className) {
return isCollection(className) || isMap(className);
} | @Test
public void isCollectionOrMap() {
assertThat(listValues).allMatch(ScenarioSimulationSharedUtils::isCollectionOrMap);
assertThat(mapValues).allMatch(ScenarioSimulationSharedUtils::isCollectionOrMap);
assertThat(ScenarioSimulationSharedUtils.isCollectionOrMap(Collection.class.getCanonica... |
@Override
public void ignoreAutoTrackFragment(Class<?> fragment) {
} | @Test
public void ignoreAutoTrackFragment() {
mSensorsAPI.ignoreAutoTrackFragment(DialogFragment.class);
Assert.assertFalse(mSensorsAPI.isFragmentAutoTrackAppViewScreen(DialogFragment.class));
} |
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new HiddenHttpMethodFilter() {
@Override
@NonNull
public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) {
return chain.filter(exchange... | @Test
public void testHiddenHttpMethodFilter() {
applicationContextRunner.run(context -> {
HiddenHttpMethodFilter hiddenHttpMethodFilter = context.getBean("hiddenHttpMethodFilter", HiddenHttpMethodFilter.class);
hiddenHttpMethodFilter.filter(mock(ServerWebExchange.class), mock(WebFil... |
@NonNull
public String processShownotes() {
String shownotes = rawShownotes;
if (TextUtils.isEmpty(shownotes)) {
Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message");
shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno... | @Test
public void testProcessShownotesAddTimecodeBrackets() {
final String timeStr = "10:11";
final long time = 3600 * 1000 * 10 + 60 * 1000 * 11;
String shownotes = "<p> Some test text with a timecode [" + timeStr + "] here.</p>";
ShownotesCleaner t = new ShownotesCleaner(context, ... |
public TreeCache start() throws Exception {
Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started");
if (createParentNodes) {
client.createContainers(root.path);
}
client.getConnectionStateListenable().addListener(connectionSt... | @Test
public void testDeleteThenCreateRoot() throws Exception {
client.create().forPath("/test");
client.create().forPath("/test/foo", "one".getBytes());
cache = newTreeCacheWithListeners(client, "/test/foo");
cache.start();
assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test... |
@Override
protected boolean isSecure(String key) {
ArtifactPluginInfo pluginInfo = metadataStore().getPluginInfo(getPluginId());
if (pluginInfo == null
|| pluginInfo.getStoreConfigSettings() == null
|| pluginInfo.getStoreConfigSettings().getConfiguration(key) == null... | @Test
public void postConstruct_shouldEncryptSecureConfigurations() {
final PluggableInstanceSettings storeConfig = new PluggableInstanceSettings(
List.of(new PluginConfiguration("password", new Metadata(true, true)))
);
final ArtifactPluginInfo pluginInfo = new ArtifactPlug... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.