focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (bizConfig.isAdminServiceAccessControlEnabled()) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res... | @Test
public void testWithAccessControlEnabledWithNoTokenSpecifiedWithNoTokenPassed() throws Exception {
String someToken = "someToken";
when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true);
when(bizConfig.getAdminServiceAccessTokens()).thenReturn(null);
when(servletRequest.getHeader... |
@Override
public void configure() throws Exception {
server.addEventListener(mbeans());
server.addConnector(plainConnector());
ContextHandlerCollection handlers = new ContextHandlerCollection();
deploymentManager.setContexts(handlers);
webAppContext = createWebAppContext();... | @Test
public void shouldSetErrorHandlerForServer() throws Exception {
jettyServer.configure();
verify(server).addBean(any(JettyCustomErrorPageHandler.class));
} |
@Override
public double read() {
return gaugeSource.read();
} | @Test
public void whenProbeThrowsException() {
metricsRegistry.registerStaticProbe(this, "foo", MANDATORY,
(DoubleProbeFunction) o -> {
throw new RuntimeException();
});
DoubleGauge gauge = metricsRegistry.newDoubleGauge("foo");
double ac... |
public static long now() {
return Instant.now().toEpochMilli();
} | @Test
public void testNow() {
assertThat(TbDate.now()).isCloseTo(Instant.now().toEpochMilli(), Offset.offset(1000L));
} |
@Override
public ParsedSchema fromConnectSchema(final Schema schema) {
// Bug in ProtobufData means `fromConnectSchema` throws on the second invocation if using
// default naming.
return new ProtobufData(new ProtobufDataConfig(updatedConfigs))
.fromConnectSchema(injectSchemaFullName(schema));
} | @Test
public void shouldApplyNullableAsOptional() {
// Given:
givenNullableAsOptional();
// When:
final ParsedSchema schema = schemaTranslator.fromConnectSchema(CONNECT_SCHEMA_WITH_NULLABLE_PRIMITIVES);
// Then:
assertThat(schema.canonicalString(), is("syntax = \"proto3\";\n"
+ "\n"
... |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComProcessInfoPacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_PROCESS_INFO, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
public URLNormalizer lowerCaseSchemeHost() {
URL u = toURL();
url = Pattern.compile(u.getProtocol(),
Pattern.CASE_INSENSITIVE).matcher(url).replaceFirst(
u.getProtocol().toLowerCase());
url = Pattern.compile(u.getHost(),
Pattern.CASE_INSENSITIVE).m... | @Test
public void testLowerCaseSchemeHost() {
s = "HTTP://www.Example.com/Hello.html";
t = "http://www.example.com/Hello.html";
assertEquals(t, n(s).lowerCaseSchemeHost().toString());
} |
@ScalarOperator(LESS_THAN)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThan(@SqlType(StandardTypes.BOOLEAN) boolean left, @SqlType(StandardTypes.BOOLEAN) boolean right)
{
return !left && right;
} | @Test
public void testLessThan()
{
assertFunction("true < true", BOOLEAN, false);
assertFunction("true < false", BOOLEAN, false);
assertFunction("false < true", BOOLEAN, true);
assertFunction("false < false", BOOLEAN, false);
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() == 1) {
final Integer level = data.getIntValue(Data.FORMAT_UINT8, 0);
if (level != null && level <= AlertLevelCallback.ALERT_HIGH) {
onAlertLevelCha... | @Test
public void onAlertLevelChanged_invalid() {
final DataReceivedCallback callback = new AlertLevelDataCallback() {
@Override
public void onAlertLevelChanged(@NonNull final BluetoothDevice device, final int level) {
fail("Invalid data reported as valid");
}
@Override
public void onInvalidDataR... |
@Override
public MetadataReport getMetadataReport(URL url) {
url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY);
String key = url.toServiceString(NAMESPACE_KEY);
MetadataReport metadataReport = serviceStoreMap.get(key);
if (metadataReport != nu... | @Test
void testGetForDiffService() {
URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic");
URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
... |
public static JibContainerBuilder create(
String baseImageReference,
Set<Platform> platforms,
CommonCliOptions commonCliOptions,
ConsoleLogger logger)
throws InvalidImageReferenceException, FileNotFoundException {
if (baseImageReference.startsWith(DOCKER_DAEMON_IMAGE_PREFIX)) {
r... | @Test
public void testCreate_tarBase()
throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException {
JibContainerBuilder containerBuilder =
ContainerBuilders.create(
"tar:///path/to.tar", Collections.emptySet(), mockCommonCliOptions, mockLogger);
BuildContext ... |
@Override
public boolean isEmpty() {
return size() == 0;
} | @Test
public void shouldReturnFalseSomePartIsNotEmpty() {
PipelineConfigs group = new MergePipelineConfigs(
new BasicPipelineConfigs(PipelineConfigMother.pipelineConfig("pipeline1")),
new BasicPipelineConfigs());
assertThat(group.isEmpty(), is(false));
} |
public static String dumpObject(Object object) {
return new Yaml(new YamlParserConstructor(), new CustomRepresenter()).dumpAsMap(object);
} | @Test
void testDumpObject() {
ConfigMetadata configMetadata = new ConfigMetadata();
List<ConfigMetadata.ConfigExportItem> configMetadataItems = new ArrayList<>();
configMetadataItems.add(item1);
configMetadataItems.add(item2);
configMetadata.setMetadata(configMetadataItems);
... |
@VisibleForTesting
void sendNotification(RuneScapeProfile profile, PatchPrediction prediction, FarmingPatch patch)
{
final RuneScapeProfileType profileType = profile.getType();
final StringBuilder stringBuilder = new StringBuilder();
// Same RS account
if (client.getGameState() == GameState.LOGGED_IN && prof... | @Test
public void testHarvestableNotification()
{
RuneScapeProfile runeScapeProfile = new RuneScapeProfile("Adam", RuneScapeProfileType.STANDARD, -1, null);
PatchPrediction patchPrediction = new PatchPrediction(Produce.RANARR, CropState.HARVESTABLE, 0L, 0, 0);
FarmingRegion region = new FarmingRegion("Ardougne... |
public static String prepareUrl(@NonNull String url) {
url = url.trim();
String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive
if (lowerCaseUrl.startsWith("feed://")) {
Log.d(TAG, "Replacing feed:// with http://");
return prepareUrl(ur... | @Test
public void testAntennaPodSubscribeDeeplink() throws UnsupportedEncodingException {
final String feed = "http://example.org/podcast.rss";
assertEquals(feed, UrlChecker.prepareUrl("https://antennapod.org/deeplink/subscribe?url=" + feed));
assertEquals(feed, UrlChecker.prepareUrl("http:/... |
@Override
public void route(final RouteContext routeContext, final SingleRule singleRule) {
if (routeContext.getRouteUnits().isEmpty() || sqlStatement instanceof SelectStatement) {
routeStatement(routeContext, singleRule);
} else {
RouteContext newRouteContext = new RouteCont... | @Test
void assertRouteInSameDataSource() throws SQLException {
SingleStandardRouteEngine engine = new SingleStandardRouteEngine(mockQualifiedTables(), null);
SingleRule singleRule = new SingleRule(new SingleRuleConfiguration(), DefaultDatabase.LOGIC_NAME, new MySQLDatabaseType(), createDataSourceMap... |
public Boolean createNamespace(String namespaceId, String namespaceName, String namespaceDesc)
throws NacosException {
// TODO 获取用kp
if (namespacePersistService.tenantInfoCountByTenantId(namespaceId) > 0) {
throw new NacosApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), Err... | @Test
void testCreateNamespace() throws NacosException {
when(namespacePersistService.tenantInfoCountByTenantId(anyString())).thenReturn(0);
namespaceOperationService.createNamespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC);
verify(namespacePersistService).insertTenantInf... |
@Override
public Double getValue() {
return getRatio().getValue();
} | @Test
public void handlesDivideByZeroIssues() throws Exception {
final RatioGauge divByZero = new RatioGauge() {
@Override
protected Ratio getRatio() {
return Ratio.of(100, 0);
}
};
assertThat(divByZero.getValue())
.isNaN()... |
void fetchRepositoryAndPackageMetaData(GoPluginDescriptor pluginDescriptor) {
try {
RepositoryConfiguration repositoryConfiguration = packageRepositoryExtension.getRepositoryConfiguration(pluginDescriptor.id());
com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfigurati... | @Test
public void shouldThrowExceptionWhenNullRepositoryConfigurationReturned() {
when(packageRepositoryExtension.getRepositoryConfiguration(pluginDescriptor.id())).thenReturn(null);
try {
metadataLoader.fetchRepositoryAndPackageMetaData(pluginDescriptor);
} catch (Exception e) {... |
public static Index simple(String name) {
return new Index(name, false);
} | @Test
public void simple_index_name_must_not_contain_upper_case_char() {
assertThatThrownBy(() -> Index.simple("Issues"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Index name must be lower-case letters or '_all': Issues");
} |
public void onNewMetadataImage(
MetadataImage newImage,
MetadataDelta delta
) {
throwIfNotRunning();
log.debug("Scheduling applying of a new metadata image with offset {}.", newImage.offset());
// Update global image.
metadataImage = newImage;
// Push an eve... | @Test
public void testOnNewMetadataImage() {
TopicPartition tp0 = new TopicPartition("__consumer_offsets", 0);
TopicPartition tp1 = new TopicPartition("__consumer_offsets", 1);
MockTimer timer = new MockTimer();
MockCoordinatorLoader loader = mock(MockCoordinatorLoader.class);
... |
public void destroy() {
synchronized (buffers) {
destroyed = true;
buffers.clear();
buffers.notifyAll();
}
} | @Test
void testDestroy() throws Exception {
BatchShuffleReadBufferPool bufferPool = createBufferPool();
List<MemorySegment> buffers = bufferPool.requestBuffers();
bufferPool.recycle(buffers);
assertThat(bufferPool.isDestroyed()).isFalse();
assertThat(bufferPool.getAvailableB... |
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
log.error("Adding Queue task to thread pool failed.", e);... | @Test
public void testRejectedExecution() {
SyncPutQueuePolicy syncPutQueuePolicy = new SyncPutQueuePolicy();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2,
60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), syncPutQueuePolicy);
threadPoolExecutor.presta... |
public void createMapping(Mapping mapping, boolean replace, boolean ifNotExists, SqlSecurityContext securityContext) {
Mapping resolved = resolveMapping(mapping, securityContext);
String name = resolved.name();
if (ifNotExists) {
relationsStorage.putIfAbsent(name, resolved);
... | @Test
public void when_replacesMapping_then_succeeds() {
// given
Mapping mapping = mapping();
given(connectorCache.forType(mapping.connectorType())).willReturn(connector);
given(connector.typeName()).willReturn(mapping.connectorType());
given(connector.defaultObjectType()).... |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testForwardedSameTargetTwice() {
String[] forwardedFields = {"f0->f2; f1->f2"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsSingleFromStri... |
public T addFromMandatoryProperty(Props props, String propertyName) {
String value = props.nonNullValue(propertyName);
if (!value.isEmpty()) {
String splitRegex = " (?=-)";
List<String> jvmOptions = Arrays.stream(value.split(splitRegex)).map(String::trim).toList();
checkOptionFormat(propertyNa... | @Test
public void addFromMandatoryProperty_checks_against_mandatory_options_is_case_sensitive() {
String[] optionOverrides = {
randomPrefix,
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(1),
randomPrefix + randomValue.substring(2),
randomPrefix + rando... |
@Override
@Deprecated
public String toString() {
final String from = new Throwable().getStackTrace()[1].toString();
LOGGER.warning("Use of toString() on hudson.util.Secret from " + from + ". Prefer getPlainText() or getEncryptedValue() depending your needs. see https://www.jenkins.io/redirect/hu... | @Test
public void testCompatibilityFromString() {
String tagName = Foo.class.getName().replace("$", "_-");
String xml = "<" + tagName + "><password>secret</password></" + tagName + ">";
Foo foo = new Foo();
Jenkins.XSTREAM.fromXML(xml, foo);
assertEquals("secret", Secret.toSt... |
public String toLoggableString(ApiMessage message) {
MetadataRecordType type = MetadataRecordType.fromId(message.apiKey());
switch (type) {
case CONFIG_RECORD: {
if (!configSchema.isSensitive((ConfigRecord) message)) {
return message.toString();
... | @Test
public void testTopicRecordToString() {
assertEquals("TopicRecord(name='foo', topicId=UOovKkohSU6AGdYW33ZUNg)",
REDACTOR.toLoggableString(new TopicRecord().
setTopicId(Uuid.fromString("UOovKkohSU6AGdYW33ZUNg")).
setName("foo")));
} |
@CheckForNull
@Override
public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path projectBaseDir, Set<Path> changedFiles) {
return branchChangedLinesWithFileMovementDetection(targetBranchName, projectBaseDir, toChangedFileByPathsMap(changedFiles));
} | @Test
public void branchChangedLines_should_be_correct_when_change_is_not_committed() throws GitAPIException, IOException {
String fileName = "file-in-first-commit.xoo";
git.branchCreate().setName("b1").call();
git.checkout().setName("b1").call();
// this line is committed
addLineToFile(fileName,... |
public DateTokenConverter<Object> getPrimaryDateTokenConverter() {
Converter<Object> p = headTokenConverter;
while (p != null) {
if (p instanceof DateTokenConverter) {
DateTokenConverter<Object> dtc = (DateTokenConverter<Object>) p;
// only primary converters... | @Test
public void settingTimeZoneOptionHasAnEffect() {
ZoneId tz = ZoneId.of("Australia/Perth");
FileNamePattern fnp = new FileNamePattern("%d{hh, " + tz.getId() + "}", context);
assertEquals(tz, fnp.getPrimaryDateTokenConverter().getZoneId());
} |
public String mapToSqlQuery(OffsetBasedPageRequest pageRequest, Sql table) {
table.with("limit", pageRequest.getLimit());
table.with("offset", pageRequest.getOffset());
return orderClause(pageRequest) + " " + dialect.limitAndOffset();
} | @Test
void sqlOffsetBasedPageRequestMapperMapsOrder() {
OffsetBasedPageRequest offsetBasedPageRequest = Paging.OffsetBasedPage.ascOnScheduledAt(10);
String filter = offsetBasedPageRequestMapper.mapToSqlQuery(offsetBasedPageRequest, jobTable);
verify(jobTable).with("offset", 0L);
ve... |
public static int[] invertPermutation(int... input){
int[] target = new int[input.length];
for(int i = 0 ; i < input.length ; i++){
target[input[i]] = i;
}
return target;
} | @Test
public void testInvertPermutationInt(){
assertArrayEquals(
new int[]{ 2, 4, 3, 0, 1 },
ArrayUtil.invertPermutation(3, 4, 0, 2, 1)
);
} |
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
... | @Test
public void testHashpwInvalidSaltVersion2() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class);
BCrypt.hashpw("foo", "$1a$10$.....................");
} |
public static long producerRecordSizeInBytes(final ProducerRecord<byte[], byte[]> record) {
return recordSizeInBytes(
record.key() == null ? 0 : record.key().length,
record.value() == null ? 0 : record.value().length,
record.topic(),
record.headers()
);
... | @Test
public void shouldComputeSizeInBytesForProducerRecordWithNullKey() {
final ProducerRecord<byte[], byte[]> record = new ProducerRecord<>(
TOPIC,
1,
0L,
null,
VALUE,
HEADERS
);
assertThat(producerRecordSizeInBytes(re... |
public static VersionRange parse(String rangeString) {
validateRangeString(rangeString);
Inclusiveness minVersionInclusiveness =
rangeString.startsWith("[") ? Inclusiveness.INCLUSIVE : Inclusiveness.EXCLUSIVE;
Inclusiveness maxVersionInclusiveness =
rangeString.endsWith("]") ? Inclusiveness... | @Test
public void parse_withoutComma_throwsIllegalArgumentException() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> VersionRange.parse("[1.0]"));
assertThat(exception).hasMessageThat().isEqualTo("Invalid range of versions, got '[1.0]'");
} |
@Override
public RandomAccessReadView createView(long startPosition, long streamLength) throws IOException
{
throw new IOException(getClass().getName() + ".createView isn't supported.");
} | @Test
void testCreateView() throws IOException
{
byte[] values = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20 };
try (RandomAccessReadBuffer randomAccessSource = new RandomAccessReadBuffer(
new ByteArrayInputStream(values));
... |
@Override
public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
Path target;
if(source.attributes().getCustom().containsKey(KEY_DELETE_MARKER)) {
// De... | @Test
public void testMove() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path test = new S3TouchFeature(session, acl... |
@VisibleForTesting
static Object convertAvroField(Object avroValue, Schema schema) {
if (avroValue == null) {
return null;
}
switch (schema.getType()) {
case NULL:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
... | @Test
public void testConvertAvroEnum() {
Object converted = BaseJdbcAutoSchemaSink.convertAvroField("e1", createFieldAndGetSchema((builder) ->
builder.name("field").type().enumeration("myenum").symbols("e1", "e2").noDefault()));
Assert.assertEquals(converted, "e1");
} |
public static Set<String> getFieldsForRecordExtractor(@Nullable IngestionConfig ingestionConfig, Schema schema) {
Set<String> fieldsForRecordExtractor = new HashSet<>();
if (null != ingestionConfig && (null != ingestionConfig.getSchemaConformingTransformerConfig()
|| null != ingestionConfig.getSchemaCo... | @Test
public void testExtractFieldsAggregationConfig() {
IngestionConfig ingestionConfig = new IngestionConfig();
Schema schema = new Schema();
ingestionConfig.setAggregationConfigs(Collections.singletonList(new AggregationConfig("d1", "SUM(s1)")));
Set<String> fields = IngestionUtils.getFieldsForRec... |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitSSSWithEmptyInput() {
String[] out = JOrphanUtils.split("", ",", "x");
assertEquals(0, out.length);
} |
public static RpcService startRemoteMetricsRpcService(
Configuration configuration,
String externalAddress,
@Nullable String bindAddress,
RpcSystem rpcSystem)
throws Exception {
final String portRange = configuration.get(MetricOptions.QUERY_SERVICE_POR... | @Test
void testStartMetricActorSystemRespectsThreadPriority() throws Exception {
final Configuration configuration = new Configuration();
final int expectedThreadPriority = 3;
configuration.set(MetricOptions.QUERY_SERVICE_THREAD_PRIORITY, expectedThreadPriority);
final RpcService rp... |
public QueryObjectBundle rewriteQuery(@Language("SQL") String query, QueryConfiguration queryConfiguration, ClusterType clusterType)
{
return rewriteQuery(query, queryConfiguration, clusterType, false);
} | @Test
public void testRewriteDecimal()
{
QueryBundle queryBundle = getQueryRewriter().rewriteQuery("SELECT decimal '1.2', decimal '1.2' d", CONFIGURATION, CONTROL);
assertCreateTableAs(queryBundle.getQuery(), "SELECT\n" +
" CAST(decimal '1.2' AS double)\n" +
", C... |
@Override
public Node upload(final Path file, final Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final ThreadPool pool = ThreadPoolFactory.get("multipart", con... | @Test
public void testTripleCryptUploadMultipleParts() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final SDSDirectS3UploadFeature feature = new SDSDirectS3UploadFeature(session, nodeid, new SDSDirectS3WriteFeature(session, nodeid));
final Path room = n... |
@Override
public synchronized void write(int b) throws IOException {
checkNotClosed();
file.writeLock().lock();
try {
if (append) {
pos = file.sizeWithoutLocking();
}
file.write(pos++, (byte) b);
file.setLastModifiedTime(fileSystemState.now());
} finally {
file.... | @Test
public void testWrite_singleByte_overwriting() throws IOException {
JimfsOutputStream out = newOutputStream(false);
addBytesToStore(out, 9, 8, 7, 6, 5, 4, 3);
out.write(1);
out.write(2);
out.write(3);
assertStoreContains(out, 1, 2, 3, 6, 5, 4, 3);
} |
@Udf(description = "Returns the INT base raised to the INT exponent.")
public Double power(
@UdfParameter(
value = "base",
description = "the base of the power."
) final Integer base,
@UdfParameter(
value = "exponent",
... | @Test
public void shouldHandleNegativeBase() {
assertThat(udf.power(-15, 2), closeTo(225.0, 0.000000000000001));
assertThat(udf.power(-15L, 2L), closeTo(225.0, 0.000000000000001));
assertThat(udf.power(-15.0, 2.0), closeTo(225.0, 0.000000000000001));
assertThat(udf.power(-15, 3), closeTo(-3375.0, 0.00... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertCompressedObjectMessageToAmqpMessageUnknownEncodingGetsDataSection() throws Exception {
ActiveMQObjectMessage outbound = createObjectMessage(TEST_OBJECT_VALUE, true);
outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_UNKNOWN);
outbound.onSend();
... |
static public void addOnConsoleListenerInstance(Context context, OnConsoleStatusListener onConsoleStatusListener) {
onConsoleStatusListener.setContext(context);
boolean effectivelyAdded = context.getStatusManager().add(onConsoleStatusListener);
if (effectivelyAdded) {
onConsoleStatus... | @Test
public void addOnConsoleListenerInstanceShouldNotStartSecondListener() {
OnConsoleStatusListener ocl0 = new OnConsoleStatusListener();
OnConsoleStatusListener ocl1 = new OnConsoleStatusListener();
StatusListenerConfigHelper.addOnConsoleListenerInstance(context, ocl0);
{
... |
static Set<PipelineOptionSpec> getOptionSpecs(
Class<? extends PipelineOptions> optionsInterface, boolean skipHidden) {
Iterable<Method> methods = ReflectHelpers.getClosureOfMethodsOnInterface(optionsInterface);
Multimap<String, Method> propsToGetters = getPropertyNamesToGetters(methods);
ImmutableSe... | @Test
public void testGetOptionSpecs() throws NoSuchMethodException {
Set<PipelineOptionSpec> properties =
PipelineOptionsReflector.getOptionSpecs(SimpleOptions.class, true);
assertThat(
properties,
Matchers.hasItems(
PipelineOptionSpec.of(
SimpleOptions.cl... |
@Udf
public String extractFragment(
@UdfParameter(
value = "input",
description = "a valid URL to extract a fragment from")
final String input) {
return UrlParser.extract(input, URI::getFragment);
} | @Test
public void shouldThrowExceptionForMalformedURL() {
// When:
final KsqlException e = assertThrows(
KsqlException.class,
() -> extractUdf.extractFragment("http://257.1/bogus/[url")
);
// Then:
assertThat(e.getMessage(), containsString("URL input has invalid syntax: http://257... |
@SuppressWarnings({ "MethodLength", "DuplicatedCode" })
public String build()
{
sb.setLength(0);
if (null != prefix && !prefix.isEmpty())
{
sb.append(prefix).append(':');
}
sb.append(ChannelUri.AERON_SCHEME).append(':').append(media).append('?');
ap... | @Test
void shouldBuildChannelBuilderUsingExistingStringWithAllTheFields()
{
final String uri = "aeron-spy:aeron:udp?endpoint=127.0.0.1:0|interface=127.0.0.1|control=127.0.0.2:0|" +
"control-mode=manual|tags=2,4|alias=foo|cc=cubic|fc=min|reliable=false|ttl=16|mtu=8992|" +
"term-le... |
@Override
public double getAndIncrement() {
return getAndAdd(1);
} | @Test
public void testGetAndIncrement() {
RAtomicDouble al = redisson.getAtomicDouble("test");
assertThat(al.getAndIncrement()).isEqualTo(0);
assertThat(al.get()).isEqualTo(1);
} |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertDecodeWithTsrange() {
MppTableData tableData = new MppTableData();
tableData.setTableName("public.test");
tableData.setOpType("INSERT");
tableData.setColumnsName(new String[]{"data"});
tableData.setColumnsType(new String[]{"tsrange"});
tableData.setCo... |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldCoerceToBooleans() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of(
new BooleanLiteral(true),
new StringLiteral("FaLsE"),
BOOL_EXPRESSION
);
// When:
final Result result = CoercionUtil.coerceUserList(expressions, typeManag... |
public static int decodeConsecutiveOctets(StringBuilder dest, String s, int start)
{
final int n = s.length();
if (start >= n)
{
throw new IllegalArgumentException("Cannot decode from index " + start + " of a length-" + n + " string");
}
if (s.charAt(start) != '%')
{
throw new Il... | @Test(dataProvider = "validConsecutiveOctetData")
public void testDecodeValidConsecutiveOctets(String encoded, int startIndex, String expected, int expectedCharsConsumed)
{
StringBuilder result = new StringBuilder();
int numCharsConsumed = URIDecoderUtils.decodeConsecutiveOctets(result, encoded, startIndex)... |
public FEELFnResult<String> invoke(@ParameterName("string") String string, @ParameterName("start position") Number start) {
return invoke(string, start, null);
} | @Test
void invokeLengthNegative() {
FunctionTestUtil.assertResultError(substringFunction.invoke("test", 1, -3), InvalidParametersEvent.class);
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefi... | @Test
public void testConvertUnsupported() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("aaa").dataType("aaa").build();
try {
OracleTypeConverter.INSTANCE.convert(typeDefine);
Assertions.fail();
} catch (SeaT... |
@Override
public void deleteTopics(final Collection<String> topicsToDelete) {
if (topicsToDelete.isEmpty()) {
return;
}
final DeleteTopicsResult deleteTopicsResult = adminClient.get().deleteTopics(topicsToDelete);
final Map<String, KafkaFuture<Void>> results = deleteTopicsResult.topicNameValues... | @Test
@SuppressWarnings("unchecked")
public void shouldFailToDeleteOnTopicAuthorizationException() {
// Given:
when(adminClient.deleteTopics(any(Collection.class)))
.thenAnswer(deleteTopicsResult(new TopicAuthorizationException("error")));
// When:
final Exception e = assertThrows(
... |
public static int age(Date birthday, Date dateToCompare) {
Assert.notNull(birthday, "Birthday can not be null !");
if (null == dateToCompare) {
dateToCompare = date();
}
return age(birthday.getTime(), dateToCompare.getTime());
} | @Test
public void ageTest() {
final String d1 = "2000-02-29";
final String d2 = "2018-02-28";
final int age = DateUtil.age(DateUtil.parseDate(d1), DateUtil.parseDate(d2));
// issue#I6E6ZG,法定生日当天不算年龄,从第二天开始计算
assertEquals(17, age);
} |
public static int tryConfigReadLock(String groupKey) {
// Lock failed by default.
int lockResult = -1;
// Try to get lock times, max value: 10;
for (int i = TRY_GET_LOCK_TIMES; i >= 0; --i) {
lockResult = ConfigCacheService.tryReadLock(groupKey);
... | @Test
void testTryConfigReadLock() throws Exception {
String dataId = "123testTryConfigReadLock";
String group = "1234";
String tenant = "1234";
CacheItem cacheItem = Mockito.mock(CacheItem.class);
SimpleReadWriteLock lock = Mockito.mock(SimpleReadWriteLock.class);
Mo... |
public static List<String> mergeValues(
ExtensionDirector extensionDirector, Class<?> type, String cfg, List<String> def) {
List<String> defaults = new ArrayList<>();
if (def != null) {
for (String name : def) {
if (extensionDirector.getExtensionLoader(type).hasEx... | @Test
void testMergeValuesDeleteDefault() {
List<String> merged = ConfigUtils.mergeValues(
ApplicationModel.defaultModel().getExtensionDirector(),
ThreadPool.class,
"-default",
asList("fixed", "default.limited", "cached"));
assertEquals... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<ListTopics> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final KafkaTopicClient client = serviceContext.getTopicClient();... | @Test
public void shouldListKafkaTopicsIncludingInternalTopics() {
// Given:
engine.givenKafkaTopic("topic1");
engine.givenKafkaTopic("topic2");
engine.givenKafkaTopic("_confluent_any_topic");
// When:
final KafkaTopicsList topicsList =
(KafkaTopicsList) CustomExecutors.LIST_TOPICS.ex... |
@Override
public Deserializer deserializer(String topic, Target type) {
return new Deserializer() {
@SneakyThrows
@Override
public DeserializeResult deserialize(RecordHeaders headers, byte[] data) {
try (var reader = new DataFileReader<>(new SeekableByteArrayInput(data), new GenericDatum... | @Test
void deserializerParsesAvroDataWithEmbeddedSchema() throws Exception {
Schema schema = new Schema.Parser().parse("""
{
"type": "record",
"name": "TestAvroRecord",
"fields": [
{ "name": "field1", "type": "string" },
{ "name": "field2", "type": "in... |
public static String convertToBitcoinURI(Address address, Coin amount,
String label, String message) {
return convertToBitcoinURI(address.network(), address.toString(), amount, label, message);
} | @Test
public void testConvertToBitcoinURI() {
Address goodAddress = AddressParser.getDefault(MAINNET).parseAddress(MAINNET_GOOD_ADDRESS);
// simple example
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=12.34&label=Hello&message=AMessage", BitcoinURI.convertToBitcoinURI(g... |
@SuppressWarnings("checkstyle:npathcomplexity")
public PartitionServiceState getPartitionServiceState() {
PartitionServiceState state = getPartitionTableState();
if (state != SAFE) {
return state;
}
if (!checkAndTriggerReplicaSync()) {
return REPLICA_NOT_SYN... | @Test
public void shouldNotBeSafe_whenReplicasAreNotSync() {
Config config = new Config();
ServiceConfig serviceConfig = TestMigrationAwareService.createServiceConfig(1);
ConfigAccessor.getServicesConfig(config).addServiceConfig(serviceConfig);
TestHazelcastInstanceFactory factory =... |
public static List<Interval> normalize(List<Interval> intervals) {
if (intervals.size() <= 1) {
return intervals;
}
List<Interval> valid =
intervals.stream().filter(Interval::isValid).collect(Collectors.toList());
if (valid.size() <= 1) {
return valid;
}
// 2 or more interva... | @Test
public void normalizeMerge() {
List<Interval> i;
i = IntervalUtils.normalize(Arrays.asList(Interval.between(1, 3), Interval.between(2, 4)));
Assert.assertEquals(1, i.size());
Assert.assertEquals(Interval.between(1, 4), i.get(0));
i = IntervalUtils.normalize(Arrays.asList(Interval.between(2... |
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) {
SourceConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!ex... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "DiscoverTriggerer class cannot be updated for batchsources")
public void testMergeDifferentBatchTriggerer() {
SourceConfig sourceConfig = createSourceConfigWithBatch();
BatchSourceConfig batchSourceConfig =... |
static boolean shouldRefresh(AwsTemporaryCredentials credentials) {
Instant expiration = Optional.ofNullable(credentials).map(AwsTemporaryCredentials::expiration).orElse(Instant.EPOCH);
return Duration.between(Instant.now(), expiration).toMinutes() < MIN_EXPIRY.toMinutes();
} | @Test
void refreshes_correctly() {
Clock clock = Clock.systemUTC();
// Does not require refresh when expires in 10 minutes
assertFalse(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(10)))));
// Requires refresh when expires in 3 minutes
a... |
public static String replaceAll(CharSequence content, String regex, String replacementTemplate) {
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
return replaceAll(content, pattern, replacementTemplate);
} | @Test
public void replaceAllTest2() {
//此处把1234替换为 ->1234<-
final String replaceAll = ReUtil.replaceAll(this.content, "(\\d+)", parameters -> "->" + parameters.group(1) + "<-");
assertEquals("ZZZaaabbbccc中文->1234<-", replaceAll);
} |
@SuppressWarnings({"checkstyle:NPathComplexity", "checkstyle:CyclomaticComplexity"})
@Override
public void shutdown() {
log.info("ksqlDB shutdown called");
try {
pullQueryMetrics.ifPresent(PullQueryExecutorMetrics::close);
} catch (final Exception e) {
log.error("Exception while waiting for... | @Test
public void shouldCloseServiceContextOnClose() {
// When:
app.shutdown();
// Then:
verify(serviceContext).close();
} |
@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) {
String handle = rule.getHandle();
RewriteHandle rewriteHandle = RewritePluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.g... | @Test
public void testRewritePlugin() {
RuleData data = new RuleData();
data.setHandle("{\"regex\":\"\",\"replace\":\"\"}");
RewriteHandle rewriteHandle = GsonUtils.getGson().fromJson(data.getHandle(), RewriteHandle.class);
RewritePluginDataHandler.CACHED_HANDLE.get().cachedHandle(Ca... |
@Override
public void expireConnectorTableColumnStatistics(Table table, List<String> columns) {
if (table == null || columns == null) {
return;
}
List<ConnectorTableColumnKey> allKeys = Lists.newArrayList();
for (String column : columns) {
ConnectorTableColumn... | @Test
public void testExpireConnectorTableColumnStatistics() {
Table table = connectContext.getGlobalStateMgr().getMetadataMgr().getTable("hive0", "partitioned_db", "t1");
CachedStatisticStorage cachedStatisticStorage = new CachedStatisticStorage();
try {
cachedStatisticStorage.e... |
@Override
public boolean supportsSchemasInIndexDefinitions() {
return false;
} | @Test
void assertSupportsSchemasInIndexDefinitions() {
assertFalse(metaData.supportsSchemasInIndexDefinitions());
} |
public static long download(String url, OutputStream out, boolean isCloseOut) {
return download(url, out, isCloseOut, null);
} | @Test
@Disabled
public void getTest5() {
String url2 = "http://storage.chancecloud.com.cn/20200413_%E7%B2%A4B12313_386.pdf";
final ByteArrayOutputStream os2 = new ByteArrayOutputStream();
HttpUtil.download(url2, os2, false);
url2 = "http://storage.chancecloud.com.cn/20200413_粤B12313_386.pdf";
HttpUtil.down... |
@Override
public TaskConfig convertJsonToTaskConfig(String configJson) {
final TaskConfig taskConfig = new TaskConfig();
ArrayList<String> exceptions = new ArrayList<>();
try {
Map<String, Object> configMap = (Map) GSON.fromJson(configJson, Object.class);
if (configMa... | @Test
public void shouldKeepTheConfigInTheOrderOfDisplayOrder(){
String json = "{\"URL\":{\"default-value\":\"\",\"secure\":false,\"required\":true,\"display-name\":\"Url\",\"display-order\":\"0\"}," +
"\"PASSWORD\":{\"display-order\":\"2\"}," +
"\"USER\":{\"default-value\":\... |
@Override
public String getDataSource() {
return DataSourceConstant.MYSQL;
} | @Test
void testGetDataSource() {
String sql = configInfoMapperByMySql.getDataSource();
assertEquals(DataSourceConstant.MYSQL, sql);
} |
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
String token = invoker.getUrl().getParameter(TOKEN_KEY);
if (ConfigUtils.isNotEmpty(token)) {
Class<?> serviceType = invoker.getInterface();
String remoteToken = (String) inv.getObjectAtt... | @Test
void testInvokeWithWrongToken() throws Exception {
Assertions.assertThrows(RpcException.class, () -> {
String token = "token";
Invoker invoker = Mockito.mock(Invoker.class);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" +... |
public static RemoteFileInputFormat getHdfsFileFormat(FileFormat format) {
switch (format) {
case ORC:
return RemoteFileInputFormat.ORC;
case PARQUET:
return RemoteFileInputFormat.PARQUET;
default:
throw new StarRocksConnectorEx... | @Test
public void testGetHdfsFileFormat() {
RemoteFileInputFormat fileFormat = IcebergApiConverter.getHdfsFileFormat(FileFormat.PARQUET);
Assert.assertTrue(fileFormat.equals(RemoteFileInputFormat.PARQUET));
Assert.assertThrows("Unexpected file format: %s", StarRocksConnectorException.class, ... |
public static ILogger getLogger(@Nonnull Class<?> clazz) {
checkNotNull(clazz, "class must not be null");
return getLoggerInternal(clazz.getName());
} | @Test
public void getLogger_thenLog4j2_thenReturnLog4j2Logger() {
isolatedLoggingRule.setLoggingType(LOGGING_TYPE_LOG4J2);
assertInstanceOf(Log4j2Factory.Log4j2Logger.class, Logger.getLogger(getClass()));
} |
public void resetReadTimeout() {
if (readerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {
lastReadTime = ticksInNanos();
reading = false;
}
} | @Test
public void testResetReader() throws Exception {
final TestableIdleStateHandler idleStateHandler = new TestableIdleStateHandler(
false, 1L, 0L, 0L, TimeUnit.SECONDS);
Action action = new Action() {
@Override
public void run(EmbeddedChannel channel) thro... |
@Override
public Cursor<Tuple> zScan(byte[] key, ScanOptions options) {
return new KeyBoundCursor<Tuple>(key, 0, options) {
private RedisClient client;
@Override
protected ScanIteration<Tuple> doScan(byte[] key, long cursorId, ScanOptions options) {
if (... | @Test
public void testZScan() {
connection.zAdd("key".getBytes(), 1, "value1".getBytes());
connection.zAdd("key".getBytes(), 2, "value2".getBytes());
Cursor<RedisZSetCommands.Tuple> t = connection.zScan("key".getBytes(), ScanOptions.scanOptions().build());
assertThat(t.hasNext()).is... |
public Integer doCall() throws Exception {
List<Row> rows = new ArrayList<>();
List<Integration> integrations = client(Integration.class).list().getItems();
integrations
.forEach(integration -> {
Row row = new Row();
row.name = integration... | @Test
public void shouldListIntegrationsEmpty() throws Exception {
createCommand().doCall();
Assertions.assertEquals("", printer.getOutput());
} |
@GET
@Path("/entity-uid/{uid}/")
@Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8)
public TimelineEntity getEntity(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@PathParam("uid") String uId,
@QueryParam("confstoretrieve") String confsToRetrieve,
@Q... | @Test
void testGetEntitiesByEventFilters() throws Exception {
Client client = createClient();
try {
URI uri = URI.create("http://localhost:" + serverPort + "/ws/v2/" +
"timeline/clusters/cluster1/apps/app1/entities/app?" +
"eventfilters=event_2,event_4");
ClientResponse resp = ... |
@Deprecated
@Override
public void init(final ProcessorContext context,
final StateStore root) {
this.context = context instanceof InternalProcessorContext ? (InternalProcessorContext) context : null;
taskId = context.taskId();
initStoreSerde(context);
streams... | @SuppressWarnings("deprecation")
@Test
public void shouldDelegateDeprecatedInit() {
setUp();
final MeteredKeyValueStore<String, String> outer = new MeteredKeyValueStore<>(
inner,
STORE_TYPE,
new MockTime(),
Serdes.String(),
Serdes.Strin... |
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
char subCommand = safeReadLine(reader).charAt(0);
String returnCommand = null;
if (subCommand == GET_UNKNOWN_SUB_COMMAND_NAME) {
returnCommand = getUnknownMember(reader);
}... | @Test
public void testMember() {
String inputCommand1 = ReflectionCommand.GET_MEMBER_SUB_COMMAND_NAME + "\n" + "java.lang.String\n" + "valueOf"
+ "\ne\n";
String inputCommand2 = ReflectionCommand.GET_MEMBER_SUB_COMMAND_NAME + "\n" + "java.lang.String\n" + "length"
+ "\ne\n";
String inputCommand3 = Reflec... |
@Override
public double score(int[] truth, int[] prediction) {
return of(truth, prediction, strategy);
} | @Test
public void testWeighted() {
System.out.println("Weighted-Recall");
int[] truth = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0... |
protected synchronized void update(final String md5, final long lastModifyTime) {
this.md5 = md5;
this.lastModifyTime = lastModifyTime;
} | @Test
public void testUpdate() {
String group = "default";
String json = "{\"name\":\"shenyu\"}";
String md51 = "8e8a3a2fdbd4368f169aa88c5fdce5a1";
ConfigDataCache cache = new ConfigDataCache(group, json, md51, 0);
assertEquals(cache.getMd5(), md51);
assertEquals(cach... |
@Override
public TransactionRule build(final TransactionRuleConfiguration ruleConfig, final Map<String, ShardingSphereDatabase> databases, final ConfigurationProperties props) {
return new TransactionRule(ruleConfig, databases);
} | @Test
void assertBuild() {
TransactionRuleConfiguration ruleConfig = new TransactionRuleConfiguration("LOCAL", "provider", new Properties());
ShardingSphereDatabase database = new ShardingSphereDatabase("logic_db", null, new ResourceMetaData(createDataSourceMap()),
new RuleMetaData(C... |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
return copy(source, segmentService.list(source), target, status, callback, listener);
} | @Test
public void testCopyManifestSameBucket() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path originFolder = new Path(container, UUID.randomUUID().toString(), Enum... |
@Override
public void verify(String value) {
long l = Long.parseLong(value);
if (l < min || l > max) {
throw new RuntimeException(format("value is not in range(%d, %d)", min, max));
}
} | @Test
public void verify_MinValue_NoExceptionThrown() {
longRangeAttribute.verify("0");
} |
public void setClusters(Map<String, ClusterMetadata> clusters) {
this.clusters = clusters;
} | @Test
void testSetClusters() {
Map<String, ClusterMetadata> clusters = new HashMap<>();
clusters.put("key", clusterMetadata);
serviceMetadata.setClusters(clusters);
Map<String, ClusterMetadata> map = serviceMetadata.getClusters();
assertNotNull(map);
assertEq... |
@Override
public byte[] decompress(byte[] src) throws IOException {
byte[] result = src;
byte[] uncompressData = new byte[src.length];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
ZstdInputStream zstdInputStream = new ZstdInputStream(byteArrayInputStream... | @Test(expected = IOException.class)
public void testDecompressWithInvalidData() throws IOException {
byte[] invalidData = new byte[] {-1, -1, -1, -1};
ZstdCompressor compressor = new ZstdCompressor();
compressor.decompress(invalidData);
} |
public static synchronized YangXmlUtils getInstance() {
if (instance == null) {
instance = new YangXmlUtils();
}
return instance;
} | @Test
public void testGetXmlUtilsInstance() throws ConfigurationException {
YangXmlUtils instance1 = YangXmlUtils.getInstance();
YangXmlUtils instance2 = YangXmlUtils.getInstance();
assertEquals("Duplicate instance", instance1, instance2);
} |
public static List<String> readLines(String path, Charset charset) {
List<String> strList = new ArrayList<>();
ClassPathResource classPathResource = new ClassPathResource(path);
try (
InputStreamReader in = new InputStreamReader(classPathResource.getInputStream(), charset);
... | @Test
public void assertReadLines() {
String testFilePath = "test/test_utf8.txt";
List<String> readLines = FileUtil.readLines(testFilePath, StandardCharsets.UTF_8);
Assert.assertEquals(3, readLines.size());
} |
public static void setField(
final Object object, final String fieldName, final Object fieldNewValue) {
try {
traverseClassHierarchy(
object.getClass(),
NoSuchFieldException.class,
(InsideTraversal<Void>)
traversalClass -> {
Field field = trave... | @Test
public void setFieldReflectively_givesHelpfulExceptions() {
ExampleDescendant example = new ExampleDescendant();
try {
ReflectionHelpers.setField(example, "nonExistent", 6);
fail("Expected exception not thrown");
} catch (RuntimeException e) {
if (!e.getMessage().contains("nonExist... |
public ASN1Sequence signedPipFromPplist(List<PolymorphicPseudonymType> response) {
for (PolymorphicPseudonymType polymorphicPseudonymType : response) {
ASN1Sequence sequence;
try {
sequence = (ASN1Sequence) ASN1Sequence.fromByteArray(polymorphicPseudonymType.getValue());
... | @Test()
public void signedPipFromPplistNoPipTest() throws IOException {
List<PolymorphicPseudonymType> pplist = new ArrayList<>();
pplist.add(new PolymorphicPseudonymType() {
{
value = pp.getEncoded();
}
});
IllegalArgumentException ex = asser... |
public boolean isComplete() {
return !ruleMetaData.getRules().isEmpty() && !resourceMetaData.getStorageUnits().isEmpty();
} | @Test
void assertIsComplete() {
ResourceMetaData resourceMetaData = new ResourceMetaData(Collections.singletonMap("ds", new MockedDataSource()));
RuleMetaData ruleMetaData = new RuleMetaData(Collections.singleton(mock(ShardingSphereRule.class)));
assertTrue(new ShardingSphereDatabase("foo_db... |
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
return helper.interpret(session, st, context);
} | @Test
void should_fail_when_executing_a_removed_prepared_statement() {
// Given
String prepareFirst = "@prepare[to_be_removed]=INSERT INTO zeppelin.users(login,deceased) " +
"VALUES(?,?)";
interpreter.interpret(prepareFirst, intrContext);
String removePrepared = "@remove_prepare[to_be_removed]... |
@Override
public RouteContext route(final ShardingRule shardingRule) {
RouteContext result = new RouteContext();
Collection<DataNode> dataNodes = getDataNodes(shardingRule, shardingRule.getShardingTable(logicTableName));
result.getOriginalDataNodes().addAll(originalDataNodes);
for (D... | @Test
void assertRouteByMixedWithHintTable() {
SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class).defaultAnswer(RETURNS_DEEP_STUBS));
when(((TableAvailable) sqlStatementContext).getTablesContext().getTableNames()).thenReturn... |
public static String prepareUrl(@NonNull String url) {
url = url.trim();
String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive
if (lowerCaseUrl.startsWith("feed://")) {
Log.d(TAG, "Replacing feed:// with http://");
return prepareUrl(ur... | @Test
public void testProtocolRelativeUrlIsRelativeHttps() {
final String in = "//example.com";
final String inBase = "https://examplebase.com";
final String out = UrlChecker.prepareUrl(in, inBase);
assertEquals("https://example.com", out);
} |
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "... | @Test
public void getTypeNameInputPositiveOutputNotNull35() {
// Arrange
final int type = 2;
// Act
final String actual = LogEvent.getTypeName(type);
// Assert result
Assert.assertEquals("Query", actual);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.