focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public ConfigResponse resolveConfig(GetConfigRequest req, ConfigResponseFactory responseFactory) {
long start = System.currentTimeMillis();
metricUpdater.incrementRequests();
ConfigKey<?> configKey = req.getConfigKey();
String defMd5 = req.getRequestDefMd5();
if (defMd5 == null |... | @Test
public void require_that_configs_are_cached() {
ConfigResponse response = handler.resolveConfig(createRequest(ModelConfig.CONFIG_DEF_NAME, ModelConfig.CONFIG_DEF_NAMESPACE, ModelConfig.CONFIG_DEF_SCHEMA));
assertNotNull(response);
ConfigResponse cached_response = handler.resolveConfig(... |
@Override
public void updateCommentVisible(ProductCommentUpdateVisibleReqVO updateReqVO) {
// 校验评论是否存在
validateCommentExists(updateReqVO.getId());
// 更新可见状态
productCommentMapper.updateById(new ProductCommentDO().setId(updateReqVO.getId())
.setVisible(updateReqVO.getV... | @Test
public void testUpdateCommentVisible_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
o.setVisible(Boolean.TRUE);
});
productCommentMapper.insert(productComment);
Long productCommentId = productComment.getId... |
public String toMysqlColumnTypeString() {
return "unknown";
} | @Test
public void testMysqlColumnType() {
Object[][] testCases = new Object[][] {
{ScalarType.createType(PrimitiveType.BOOLEAN), "tinyint(1)"},
{ScalarType.createType(PrimitiveType.LARGEINT), "bigint(20) unsigned"},
{ScalarType.createDecimalV3NarrowestType(18,... |
@Override
public void persistEphemeral(final String key, final String value) {
try {
if (isExisted(key)) {
client.delete().deletingChildrenIfNeeded().forPath(key);
}
client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(key, valu... | @Test
void assertPersistEphemeralExist() throws Exception {
when(existsBuilder.forPath("/test/ephemeral")).thenReturn(new Stat());
when(protect.withMode(CreateMode.EPHEMERAL)).thenReturn(protect);
REPOSITORY.persistEphemeral("/test/ephemeral", "value4");
verify(backgroundVersionable)... |
public KafkaFuture<Void> partitionResult(final TopicPartition partition) {
if (!partitions.contains(partition)) {
throw new IllegalArgumentException("Partition " + partition + " was not included in the original request");
}
final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>()... | @Test
public void testPartitionMissingInRequestErrorConstructor() throws InterruptedException, ExecutionException {
DeleteConsumerGroupOffsetsResult partitionLevelErrorResult = createAndVerifyPartitionLevelError();
assertThrows(IllegalArgumentException.class, () -> partitionLevelErrorResult.partitio... |
public static <T> PaginatedResponse<T> create(String listKey, PaginatedList<T> paginatedList) {
return new PaginatedResponse<>(listKey, paginatedList, null, null);
} | @Test
public void serialize() throws Exception {
final ImmutableList<String> values = ImmutableList.of("hello", "world");
final PaginatedList<String> paginatedList = new PaginatedList<>(values, values.size(), 1, 10);
final PaginatedResponse<String> response = PaginatedResponse.create("foo", ... |
@Override
public int launch(AgentLaunchDescriptor descriptor) {
LogConfigurator logConfigurator = new LogConfigurator("agent-launcher-logback.xml");
return logConfigurator.runWithLogger(() -> doLaunch(descriptor));
} | @Test
@DisabledOnOs(OS.WINDOWS)
public void shouldDownload_AgentJar_IfTheCurrentJarIsStale() throws Exception {
TEST_AGENT_LAUNCHER.copyTo(AGENT_LAUNCHER_JAR);
File staleJar = randomFile(AGENT_BINARY_JAR);
long original = staleJar.length();
new AgentLauncherImpl().launch(launchDe... |
public static void main(String[] args) throws IOException
{
File file = new File("src/main/resources/org/apache/pdfbox/examples/rendering/",
"custom-render-demo.pdf");
try (PDDocument doc = Loader.loadPDF(file))
{
PDFRenderer renderer = new M... | @Test
void testCustomPageDrawer() throws IOException
{
CustomPageDrawer.main(new String[]{});
BufferedImage bim = ImageIO.read(new File("target","custom-render.png"));
Assertions.assertNotNull(bim);
} |
@Override
public RemoteEnvironment createEnvironment(Environment environment, String workerId)
throws Exception {
Preconditions.checkState(
environment
.getUrn()
.equals(BeamUrns.getUrn(RunnerApi.StandardEnvironments.Environments.PROCESS)),
"The passed environment doe... | @Test
public void createsCorrectEnvironment() throws Exception {
RemoteEnvironment handle = factory.createEnvironment(ENVIRONMENT, "workerId");
assertThat(handle.getInstructionRequestHandler(), is(client));
assertThat(handle.getEnvironment(), equalTo(ENVIRONMENT));
Mockito.verify(processManager).start... |
@Override
protected ClickHouseLogCollectClient getLogConsumeClient() {
return LoggingClickHousePluginDataHandler.getClickHouseLogCollectClient();
} | @Test
public void testGetLogConsumeClient() {
LogConsumeClient logConsumeClient = new ClickHouseLogCollector().getLogConsumeClient();
Assertions.assertEquals(ClickHouseLogCollectClient.class, logConsumeClient.getClass());
} |
public StructType bind(StructType inputSchema) {
if (binding != null && binding.get().inputSchema == inputSchema) {
return binding.get().xschema;
}
Formula formula = expand(inputSchema);
Binding binding = new Binding();
binding.inputSchema = inputSchema;
Li... | @Test
public void testBind() {
System.out.println("bind");
Formula formula = Formula.of("revenue", dot(), cross("water", "sowing_density") , mul("humidity", "wind"), delete("wind"));
StructType inputSchema = DataTypes.struct(
new StructField("revenue", DataTypes.DoubleType, ... |
@Override
public void updateDataSourceConfig(DataSourceConfigSaveReqVO updateReqVO) {
// 校验存在
validateDataSourceConfigExists(updateReqVO.getId());
DataSourceConfigDO updateObj = BeanUtils.toBean(updateReqVO, DataSourceConfigDO.class);
validateConnectionOK(updateObj);
// 更新
... | @Test
public void testUpdateDataSourceConfig_success() {
try (MockedStatic<JdbcUtils> databaseUtilsMock = mockStatic(JdbcUtils.class)) {
// mock 数据
DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class);
dataSourceConfigMapper.insert(dbDataSourceConf... |
@Override
public Map<Errors, Integer> errorCounts() {
if (data.errorCode() != Errors.NONE.code())
// Minor optimization since the top-level error applies to all partitions
return Collections.singletonMap(error(), data.partitionErrors().size() + 1);
Map<Errors, Integer> errors... | @Test
public void testErrorCountsFromGetErrorResponse() {
List<StopReplicaTopicState> topicStates = new ArrayList<>();
topicStates.add(new StopReplicaTopicState()
.setTopicName("foo")
.setPartitionStates(Arrays.asList(
new StopReplicaPartitionState().setPartit... |
@VisibleForTesting
List<Image> getCachedBaseImages()
throws IOException, CacheCorruptedException, BadContainerConfigurationFormatException,
LayerCountMismatchException, UnlistedPlatformInManifestListException,
PlatformNotFoundInBaseImageException {
ImageReference baseImage = buildContext... | @Test
public void testGetCachedBaseImages_emptyCache()
throws InvalidImageReferenceException, IOException, CacheCorruptedException,
UnlistedPlatformInManifestListException, PlatformNotFoundInBaseImageException,
BadContainerConfigurationFormatException, LayerCountMismatchException {
Image... |
@Override
public void onStateElection(Job job, JobState newState) {
if (isNotFailed(newState) || isJobNotFoundException(newState) || isProblematicExceptionAndMustNotRetry(newState) || maxAmountOfRetriesReached(job))
return;
job.scheduleAt(now().plusSeconds(getSecondsToAdd(job)), String.... | @Test
void skipsIfStateIsNotFailed() {
final Job job = anEnqueuedJob().build();
applyDefaultJobFilter(job);
int beforeVersion = job.getJobStates().size();
retryFilter.onStateElection(job, job.getJobState());
int afterVersion = job.getJobStates().size();
assertThat(a... |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
... | @Test
public void testUninstallAndInstallIntent() {
List<Intent> intentsToUninstall = createFlowObjectiveIntents();
List<Intent> intentsToInstall = createAnotherFlowObjectiveIntents();
IntentData toInstall = new IntentData(createP2PIntent(),
Inte... |
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address,
long id, long length, RequestType type, OutStreamOptions options)
throws IOException {
long chunkSize = context.getClusterConf()
.getBytes(PropertyKey.USER_STREAMING_WRITER_CHUNK_SIZE_BYTES);
CloseableRe... | @Test(timeout = 1000 * 60)
public void writeFileUnknownLength() throws Exception {
long checksumActual;
Future<Long> checksumExpected;
long length = CHUNK_SIZE * 1024;
try (DataWriter writer = create(Long.MAX_VALUE)) {
checksumExpected = writeFile(writer, length, 10, length / 3);
checksumE... |
static SerializableFunction<Double, Double> getResultUpdaterFunction(final RegressionModel.NormalizationMethod normalizationMethod) {
if (UNSUPPORTED_NORMALIZATION_METHODS.contains(normalizationMethod)) {
return null;
} else {
return getResultUpdaterSupportedFunction(normalizatio... | @Test
void getResultUpdaterUnsupportedFunction() {
UNSUPPORTED_NORMALIZATION_METHODS.forEach(normalizationMethod ->
assertThat(KiePMMLRegressionTableFactory.getResultUpdaterFunction(normalizationMethod)).isNull());
} |
@ScalarOperator(LESS_THAN)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThan(@SqlType("unknown") boolean left, @SqlType("unknown") boolean right)
{
throw new AssertionError("value of unknown type should all be NULL");
} | @Test
public void testLessThan()
{
assertFunction("NULL < NULL", BOOLEAN, null);
} |
public static Map<String, URI> uploadOutputFiles(RunContext runContext, Path outputDir) throws IOException {
// upload output files
Map<String, URI> uploaded = new HashMap<>();
try (Stream<Path> walk = Files.walk(outputDir)) {
walk
.filter(Files::isRegularFile)
... | @Test
void uploadOutputFiles() throws IOException {
var runContext = runContextFactory.of();
Path path = Path.of("/tmp/unittest/file.txt");
if (!path.toFile().exists()) {
Files.createFile(path);
}
var outputFiles = ScriptService.uploadOutputFiles(runContext, Path... |
@Description("Binomial cdf given numberOfTrials, successProbability, and a value")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double binomialCdf(
@SqlType(StandardTypes.INTEGER) long numberOfTrials,
@SqlType(StandardTypes.DOUBLE) double successProbability,
... | @Test
public void testBinomialCdf()
{
assertFunction("binomial_cdf(5, 0.5, 5)", DOUBLE, 1.0);
assertFunction("binomial_cdf(5, 0.5, 0)", DOUBLE, 0.03125);
assertFunction("binomial_cdf(5, 0.5, 3)", DOUBLE, 0.8125);
assertFunction("binomial_cdf(20, 1.0, 0)", DOUBLE, 0.0);
a... |
public static SqlToConnectTypeConverter sqlToConnectConverter() {
return SQL_TO_CONNECT_CONVERTER;
} | @Test
public void shouldConvertRegularStructFromSqlToConnect() {
// Given:
SqlStruct sqlStruct = SqlStruct.builder()
.field("foo", SqlPrimitiveType.of(SqlBaseType.STRING))
.field("bar", SqlPrimitiveType.of(SqlBaseType.BOOLEAN))
.field("baz", SqlPrimitiveType.of(SqlBaseType.INTEGER))
... |
@Override
public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) {
final PlanNode source = getSource();
final SchemaKStream<?> schemaKStream = source.buildStream(buildContext);
final QueryContext.Stacker contextStacker = buildContext.buildNodeContext(getId().toString());
return sch... | @Test
public void shouldBuildOutputNodeForInsertIntoAvroFromNonAvro() {
// Given:
givenInsertIntoNode();
KeyFormat.nonWindowed(
FormatInfo.of(
FormatFactory.AVRO.name(),
ImmutableMap.of(ConnectProperties.FULL_SCHEMA_NAME, "key-name")
),
SerdeFeatures.of()
... |
public void updateAll() throws InterruptedException {
LOGGER.debug("DAILY UPDATE ALL");
var extensions = repositories.findAllPublicIds();
var extensionPublicIdsMap = extensions.stream()
.filter(e -> StringUtils.isNotEmpty(e.getPublicId()))
.collect(Collectors.toMa... | @Test
public void testUpdateAllChange() throws InterruptedException {
var namespaceName1 = "foo";
var namespacePublicId1 = UUID.randomUUID().toString();
var extensionName1 = "bar";
var extensionPublicId1 = UUID.randomUUID().toString();
var namespace1 = new Namespace();
... |
@Override
public void getConfig(ZookeeperServerConfig.Builder builder) {
ConfigServer[] configServers = getConfigServers();
int[] zookeeperIds = getConfigServerZookeeperIds();
if (configServers.length != zookeeperIds.length) {
throw new IllegalArgumentException(String.format("Nu... | @Test
void zookeeperConfig_only_config_servers_set_hosted() {
TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of());
ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions);
assertZookeeperServerProperty(config.server(), Zooke... |
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> stream,
final StreamFilter<K> step,
final RuntimeBuildContext buildContext) {
return build(stream, step, buildContext, SqlPredicate::new);
} | @Test
public void shouldUseCorrectNameForProcessingLogger() {
// When:
step.build(planBuilder, planInfo);
// Then:
verify(buildContext).getProcessingLogger(queryContext);
} |
public static Field getDeclaredField(Class<?> clazz, String fieldName) throws SecurityException {
if (null == clazz || StrUtil.isBlank(fieldName)) {
return null;
}
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
// e.printStackTrace();
}
return null;
} | @Test
public void getDeclaredField() {
Field noField = ClassUtil.getDeclaredField(TestSubClass.class, "noField");
assertNull(noField);
// 获取不到父类字段
Field field = ClassUtil.getDeclaredField(TestSubClass.class, "field");
assertNull(field);
Field subField = ClassUtil.getDeclaredField(TestSubClass.class, "sub... |
@Deprecated
public static SegwitAddress fromBech32(@Nullable NetworkParameters params, String bech32)
throws AddressFormatException {
return (SegwitAddress) AddressParser.getLegacy(params).parseAddress(bech32);
} | @Test(expected = AddressFormatException.WrongNetwork.class)
public void fromBech32_wrongNetwork() {
SegwitAddress.fromBech32("bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj", TESTNET);
} |
public Map<MediaType, List<Parser>> findDuplicateParsers(ParseContext context) {
Map<MediaType, Parser> types = new HashMap<>();
Map<MediaType, List<Parser>> duplicates = new HashMap<>();
for (Parser parser : parsers) {
for (MediaType type : parser.getSupportedTypes(context)) {
... | @Test
@SuppressWarnings("serial")
public void testFindDuplicateParsers() {
Parser a = new EmptyParser() {
public Set<MediaType> getSupportedTypes(ParseContext context) {
return Collections.singleton(MediaType.TEXT_PLAIN);
}
};
Parser b = new EmptyP... |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
// 1.1 校验积分功能是否开启
int givePointPerYuan = Optional.ofNullable(memberConfigApi.getConfig())
.filter(config -> BooleanUtil.isTrue(config.getPointTradeDeductEnable()))
.map... | @Test
public void testCalculate() {
// 准备参数
TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
.setUserId(233L)
.setItems(asList(
new TradePriceCalculateReqBO.Item().setSkuId(10L).setCount(2).setSelected(true), // 全局积分
... |
@Override
public TransferStatus prepare(final Path file, final Local local, final TransferStatus parent, final ProgressListener progress) throws BackgroundException {
final TransferStatus status = super.prepare(file, local, parent, progress);
if(status.isSegmented()) {
for(TransferStatus... | @Test
public void testPrepareDirectoryExistsFalse() throws Exception {
final Host host = new Host(new TestProtocol());
final NullSession session = new NullTransferSession(host);
ResumeFilter f = new ResumeFilter(new DisabledDownloadSymlinkResolver(), session,
new DownloadFilterOp... |
@VisibleForTesting
static IssueCache.Issue toProto(IssueCache.Issue.Builder builder, DefaultIssue defaultIssue) {
builder.clear();
builder.setKey(defaultIssue.key());
builder.setRuleType(defaultIssue.type().getDbConstant());
ofNullable(defaultIssue.getCleanCodeAttribute()).ifPresent(value -> builder.s... | @Test
public void toProto_whenRuleDescriptionContextKeyIsSet_shouldCopyToIssueProto() {
DefaultIssue defaultIssue = createDefaultIssueWithMandatoryFields();
defaultIssue.addImpact(SoftwareQuality.MAINTAINABILITY, Severity.HIGH);
defaultIssue.addImpact(SoftwareQuality.RELIABILITY, Severity.LOW);
Issue... |
@Override
public int count(String term) {
MutableInt count = freq.get(term);
return count == null ? 0 : count.value;
} | @Test
public void testGetTermFrequency() {
System.out.println("getTermFrequency");
assertEquals(27, corpus.count("romantic"));
} |
public static int computeMaxLEPower2(int num) {
num |= (num >>> 1);
num |= (num >>> 2);
num |= (num >>> 4);
num |= (num >>> 8);
num |= (num >>> 16);
return num - (num >>> 1);
} | @Test
public void testComputeMaxLEPower2() {
Assert.assertEquals(0, Utils.computeMaxLEPower2(0));
for (int i = 1; i < 10000; i++) {
int out = Utils.computeMaxLEPower2(i);
// The number i belongs to the range [out, out*2).
Assert.assertTrue(out <= i);
... |
@VisibleForTesting
public static int getNumericPrecision(DataType dataType) {
if (dataType.is(DataTypeFamily.EXACT_NUMERIC)) {
if (dataType.is(DataTypeRoot.TINYINT)) {
return 3;
} else if (dataType.is(DataTypeRoot.SMALLINT)) {
return 5;
} e... | @Test
public void testGetNumericPrecision() {
Assertions.assertThat(SchemaUtils.getNumericPrecision(DataTypes.TINYINT())).isEqualTo(3);
Assertions.assertThat(SchemaUtils.getNumericPrecision(DataTypes.SMALLINT())).isEqualTo(5);
Assertions.assertThat(SchemaUtils.getNumericPrecision(DataTypes.I... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理
public void updateNotifyTemplate(NotifyTemplateSaveReqVO updateReqVO) {
// 校验存在
validateNotifyTemplateExists(updateReqVO.getId());
// 校验站内信编码是否重复... | @Test
public void testUpdateNotifyTemplate_success() {
// mock 数据
NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class);
notifyTemplateMapper.insert(dbNotifyTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
NotifyTemplateSaveReqVO reqVO = randomPojo(NotifyTemplateSaveRe... |
public static boolean isPrimitives(Class<?> cls) {
while (cls.isArray()) {
cls = cls.getComponentType();
}
return isPrimitive(cls);
} | @Test
void testIsPrimitives() {
assertTrue(ReflectUtils.isPrimitives(boolean[].class));
assertTrue(ReflectUtils.isPrimitives(byte.class));
assertFalse(ReflectUtils.isPrimitive(Map[].class));
} |
@Override
List<DiscoveryNode> resolveNodes() {
if (serviceName != null && !serviceName.isEmpty()) {
logger.fine("Using service name to discover nodes.");
return getSimpleDiscoveryNodes(client.endpointsByName(serviceName));
} else if (serviceLabel != null && !serviceLabel.isEm... | @Test
public void resolveWithServiceLabelWhenNodeWithServiceLabel() {
// given
List<Endpoint> endpoints = createEndpoints(2);
given(client.endpointsByServiceLabel(SERVICE_LABEL, SERVICE_LABEL_VALUE)).willReturn(endpoints);
KubernetesApiEndpointResolver sut = new KubernetesApiEndpoin... |
@SuppressWarnings("unchecked")
@Override
protected List<OUT> executeOnCollections(
List<IN1> inputData1,
List<IN2> inputData2,
RuntimeContext runtimeContext,
ExecutionConfig executionConfig)
throws Exception {
FlatJoinFunction<IN1, IN2, OUT> fu... | @Test
void testJoinRich() throws Exception {
final AtomicBoolean opened = new AtomicBoolean(false);
final AtomicBoolean closed = new AtomicBoolean(false);
final String taskName = "Test rich join function";
final RichFlatJoinFunction<String, String, Integer> joiner =
... |
public static boolean validatePlugin(PluginLookup.PluginType type, Class<?> pluginClass) {
switch (type) {
case INPUT:
return containsAllMethods(inputMethods, pluginClass.getMethods());
case FILTER:
return containsAllMethods(filterMethods, pluginClass.getM... | @Test
public void testValidOutputPlugin() {
Assert.assertTrue(PluginValidator.validatePlugin(PluginLookup.PluginType.OUTPUT, Stdout.class));
} |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldHandleValueAvroSchemaNameForStream() {
// Given:
givenCommandFactoriesWithMocks();
givenProperty("VALUE_FORMAT", new StringLiteral("Avro"));
givenProperty("value_avro_schema_full_name", new StringLiteral("full.schema.name"));
final CreateStream statement = new CreateStream(... |
static MethodWrapper none() {
return new MethodWrapper(null, false);
} | @Test
public void testNone() {
MethodWrapper none = MethodWrapper.none();
assertThat(none.isPresent()).isFalse();
assertThat(none.getMethod()).isNull();
} |
public static <T extends TypedSPI> Optional<T> findService(final Class<T> serviceInterface, final Object type) {
return findService(serviceInterface, type, new Properties());
} | @Test
void assertFindServiceWithProperties() {
assertTrue(TypedSPILoader.findService(TypedSPIFixture.class, "TYPED.FIXTURE", new Properties()).isPresent());
} |
@SuppressWarnings("unchecked")
@Override
public void configure(Map<String, ?> configs) throws KafkaException {
if (sslEngineFactory != null) {
throw new IllegalStateException("SslFactory was already configured.");
}
this.endpointIdentification = (String) configs.get(SslConfig... | @Test
public void testSslFactoryWithoutPasswordConfiguration() throws Exception {
File trustStoreFile = TestUtils.tempFile("truststore", ".jks");
Map<String, Object> serverSslConfig = sslConfigsBuilder(ConnectionMode.SERVER)
.createNewTrustStore(trustStoreFile)
.build... |
@Override
public ValidationFailure addFailure(String message, @Nullable String correctiveAction) {
ValidationFailure validationFailure = new ValidationFailure(message, correctiveAction);
failuresCollection.add(validationFailure);
return validationFailure;
} | @Test
public void addFailure() {
/** arrange */
FailureCollectorWrapper failureCollectorWrapper = new FailureCollectorWrapper();
/** act */
RuntimeException error = new RuntimeException("An error has occurred");
failureCollectorWrapper.addFailure(error.getMessage(), null);
/** assert */
... |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final WindowRangeQuery<GenericKey, GenericRow> query = WindowR... | @Test
public void shouldReturnMultipleSessions() {
// Given:
givenSingleSession(LOWER_INSTANT.minusMillis(1), LOWER_INSTANT.plusSeconds(1));
final Instant wend0 = LOWER_INSTANT;
givenSingleSession(LOWER_INSTANT, wend0);
final Instant wend1 = UPPER_INSTANT;
givenSingleSession(UPPER_INSTANT, wen... |
@Override
public int run(String launcherVersion, String launcherMd5, ServerUrlGenerator urlGenerator, Map<String, String> env, Map<String, String> context) {
int exitValue = 0;
LOG.info("Agent launcher is version: {}", CurrentGoCDVersion.getInstance().fullVersion());
String[] command = new S... | @Test
public void shouldAddSSLConfigurationIfProvided() throws InterruptedException {
final List<String> cmd = new ArrayList<>();
String expectedAgentMd5 = TEST_AGENT.getMd5();
String expectedAgentPluginsMd5 = TEST_AGENT_PLUGINS.getMd5();
String expectedTfsMd5 = TEST_TFS_IMPL.getMd5(... |
@Override
public Network network(String netId) {
checkArgument(!Strings.isNullOrEmpty(netId), ERR_NULL_NETWORK_ID);
return osNetworkStore.network(netId);
} | @Test
public void testGetNetworkById() {
createBasicNetworks();
assertTrue("Network did not match", target.network(NETWORK_ID) != null);
assertTrue("Network did not match", target.network(UNKNOWN_ID) == null);
} |
@Override
public ByteBuf readBytes(int length) {
checkReadableBytes(length);
if (length == 0) {
return Unpooled.EMPTY_BUFFER;
}
ByteBuf buf = alloc().buffer(length, maxCapacity);
buf.writeBytes(this, readerIndex, length);
readerIndex += length;
re... | @Test
public void testReadBytesAfterRelease6() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().readBytes(new byte[8], 0, 1);
}
});
} |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void kGroupedStreamAnonymousMaterializedCountShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic")
.groupByKey()
.count(Materialized.<Object, Long, KeyValueStore<Bytes, byte[]>>with(null, Serdes.Lon... |
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir)))
.map(GitScmProvider::extractAbsoluteFilePaths)
.orElse(null);
} | @Test
public void branchChangedFiles_should_return_null_on_errors() throws GitAPIException {
DiffCommand diffCommand = mock(DiffCommand.class);
when(diffCommand.setShowNameAndStatusOnly(anyBoolean())).thenReturn(diffCommand);
when(diffCommand.setOldTree(any())).thenReturn(diffCommand);
when(diffComman... |
public static ShenyuAdminResult timeout(final String msg) {
return error(HttpStatus.REQUEST_TIMEOUT.value(), msg);
} | @Test
public void testTimeout() {
final ShenyuAdminResult result = ShenyuAdminResult.timeout("msg");
assertEquals(HttpStatus.REQUEST_TIMEOUT.value(), result.getCode().intValue());
assertEquals("msg", result.getMessage());
assertNull(result.getData());
assertEquals(3782806, re... |
@GetMapping("/hystrix")
public Object hystrixPluginFallback() {
return ShenyuResultWrap.error(ShenyuResultEnum.HYSTRIX_PLUGIN_FALLBACK, null);
} | @Test
public void hystrixPluginFallback() throws Exception {
final MockHttpServletResponse response = this.mockMvc.perform(MockMvcRequestBuilders.get("/fallback/hystrix"))
.andReturn().getResponse();
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
} |
@Override
public void removeEndpoints(String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_ENDPOINTS_UID);
synchronized (this) {
if (isEndpointsInUse(uid)) {
final String error = String.format(MSG_ENDPOINTS, uid, ERR_IN_USE);
throw new Illega... | @Test(expected = IllegalArgumentException.class)
public void testRemoveEndpointsWithNull() {
target.removeEndpoints(null);
} |
@Override
public Response setHeader(String name, String value) {
stream.response().setHeader(name, value);
return this;
} | @Test
public void set_header() {
underTest.setHeader("header", "value");
verify(response).setHeader("header", "value");
} |
@VisibleForTesting
protected ObjectMapper getMapper() {
return this.mapper;
} | @Test
public void testJacksonFeatureByConfigKey() {
// origin, should be FAIL_ON_UNKNOWN_PROPERTIES ture and FAIL_ON_EMPTY_BEANS true
JacksonSerializer origin = new JacksonSerializer();
ObjectMapper originMapper = origin.getMapper();
// originally false
Assert.assertFalse(ori... |
@Override
public boolean isEmpty() {
return size <= 0;
} | @Test
public void testIsEmpty() {
RangeSet rs = new RangeSet(0);
assertTrue(rs.isEmpty());
rs = new RangeSet(3);
assertFalse(rs.isEmpty());
} |
@Override
public void computeScanRangeAssignment() throws UserException {
if (locations.size() == 0) {
return;
}
long totalSize = computeTotalSize();
long avgNodeScanRangeBytes = totalSize / Math.max(workerProvider.getAllWorkers().size(), 1) + 1;
for (ComputeNod... | @Test
public void testHdfsScanNodeForceScheduleLocal() throws Exception {
new Expectations() {
{
hdfsScanNode.getId();
result = scanNodeId;
hiveTable.getTableLocation();
result = "hdfs://dfs00/dataset/";
}
};
... |
@Override
public void queuePermissionSyncTask(String submitterUuid, String componentUuid, String projectUuid) {
findManagedProjectService()
.ifPresent(managedProjectService -> managedProjectService.queuePermissionSyncTask(submitterUuid, componentUuid, projectUuid));
} | @Test
public void queuePermissionSyncTask_whenManagedInstanceServices_shouldDelegatesToRightService() {
NeverManagedInstanceService neverManagedInstanceService = spy(new NeverManagedInstanceService());
AlwaysManagedInstanceService alwaysManagedInstanceService = spy(new AlwaysManagedInstanceService());
Set... |
public static List<Chunk> split(String s) {
int pos = s.indexOf(SLASH);
if (pos == -1) {
throw new RuntimeException("path did not start with or contain '/'");
}
List<Chunk> list = new ArrayList();
int startPos = 0;
int searchPos = 0;
boolean anyDepth =... | @Test
void testIndex() {
List<PathSearch.Chunk> list = PathSearch.split("/hello[3]//world");
logger.debug("list: {}", list);
PathSearch.Chunk first = list.get(0);
assertFalse(first.anyDepth);
assertEquals("hello", first.controlType);
assertEquals(2, first.index);
... |
@Override
public String pwd() {
try {
return client.printWorkingDirectory();
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | @Test
@Disabled
public void isDirTest() throws Exception {
try (final Ftp ftp = new Ftp("127.0.0.1", 21)) {
Console.log(ftp.pwd());
ftp.isDir("/test");
Console.log(ftp.pwd());
}
} |
public List<QueryMetadata> sql(final String sql) {
return sql(sql, Collections.emptyMap());
} | @Test
public void shouldThrowIfFailedToInferSchema() {
// Given:
when(schemaInjector.inject(any()))
.thenThrow(new RuntimeException("Boom"));
// When:
final Exception e = assertThrows(
RuntimeException.class,
() -> ksqlContext.sql("Some SQL", SOME_PROPERTIES)
);
// Th... |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void signedRightShift() {
assertUnifiesAndInlines(
"4 >> 17", UBinary.create(Kind.RIGHT_SHIFT, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
@Override
public int getOrder() {
return PluginEnum.JWT.getCode();
} | @Test
public void testGetOrder() {
final int result = jwtPluginUnderTest.getOrder();
Assertions.assertEquals(PluginEnum.JWT.getCode(), result);
} |
@Override
public synchronized boolean isTerminated() {
if (!shutdownStarted) {
return false;
}
for (ManagedChannel channel : usedChannels) {
if (!channel.isTerminated()) return false;
}
for (ManagedChannel channel : channelCache) {
if (!channel.isTerminated()) return false;
}... | @Test
public void testIsTerminated() throws Exception {
ManagedChannel mockChannel = mock(ManagedChannel.class);
when(channelSupplier.get()).thenReturn(mockChannel);
IsolationChannel isolationChannel = IsolationChannel.create(channelSupplier);
when(mockChannel.shutdown()).thenReturn(mockChannel);
... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeJoinWithBeforeAndAfterAndGraceStatementsCorrectly() {
final String output = anon.anonymize("INSERT INTO OUTPUT SELECT col1, col2, col3"
+ " FROM SOURCE1 S1 JOIN SOURCE2 S2 "
+ "WITHIN (1 SECOND, 3 SECONDS) GRACE PERIOD 2 SECONDS ON col1.k=col2.k;");
Approvals.... |
@Override
public ResultSet executeQuery(String sql)
throws SQLException {
validateState();
try {
if (!DriverUtils.queryContainsLimitStatement(sql)) {
sql += " " + LIMIT_STATEMENT + " " + _maxRows;
}
String enabledSql = DriverUtils.enableQueryOptions(sql, _connection.getQueryOpt... | @Test
public void testPresetEnableNullHandling()
throws Exception {
Properties props = new Properties();
props.put(QueryOptionKey.ENABLE_NULL_HANDLING, "true");
PinotConnection pinotConnection =
new PinotConnection(props, "dummy", _dummyPinotClientTransport, "dummy", _dummyPinotControllerTra... |
public static String getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
FileChecksums fileChecksums = CHECKSUM_CACHE.get(file);
if (fileChecksums == null) {
try (InputStream stream = Files.newInputStream(file.toPath())) {
final MessageDige... | @Test
public void testGetChecksum_NoSuchAlgorithm() throws Exception {
String algorithm = "some unknown algorithm";
File file = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").getPath());
Exception exception = Assert.assertThrows(NoSuchAlgorithmException.class, () ... |
public Node deserializeObject(JsonReader reader) {
Log.info("Deserializing JSON to Node.");
JsonObject jsonObject = reader.readObject();
return deserializeObject(jsonObject);
} | @Test
void testOperator() {
Expression expr = parseExpression("1+1");
String serialized = serialize(expr, false);
Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized)));
assertEqualsStringIgnoringEol("1 + 1", deserialized.toString());
... |
public void start() {
if (!enabled) {
logger.info(format("Diagnostics disabled. To enable add -D%s=true to the JVM arguments.", ENABLED.getName()));
return;
}
this.diagnosticsLog = outputType.newLog(this);
this.scheduler = new ScheduledThreadPoolExecutor(1, new D... | @Test
public void start_whenEnabled() throws Exception {
Diagnostics diagnostics = newDiagnostics(new Config().setProperty(Diagnostics.ENABLED.getName(), "true"));
diagnostics.start();
assertNotNull("DiagnosticsLogFile should not be null", diagnostics.diagnosticsLog);
} |
@Override
protected String buildApiPath(final Method method,
final String superPath,
@NonNull final ShenyuSofaClient shenyuSofaClient) {
final String contextPath = this.getContextPath();
return superPath.contains("*") ? pathJoin(con... | @Test
public void testBuildApiPathSuperPathContainsStar() {
given(method.getName()).willReturn(METHOD_NAME);
String realApiPath = sofaServiceEventListener.buildApiPath(method, SUPER_PATH_CONTAINS_STAR, shenyuSofaClient);
String expectedApiPath = "/sofa/demo/buildURIRegisterDTO";
ass... |
@Override
public SchemaTransform from(PubsubReadSchemaTransformConfiguration configuration) {
if (configuration.getSubscription() == null && configuration.getTopic() == null) {
throw new IllegalArgumentException(
"To read from Pubsub, a subscription name or a topic name must be provided");
}
... | @Test
public void testInvalidConfigBothTopicAndSubscription() {
PCollectionRowTuple begin = PCollectionRowTuple.empty(p);
assertThrows(
IllegalArgumentException.class,
() ->
begin.apply(
new PubsubReadSchemaTransformProvider()
.from(
... |
public static GlobalMemoryAccessor getDefaultGlobalMemoryAccessor() {
return STORAGE.get(PLATFORM_AWARE);
} | @Test
public void test_getMemoryAccessor_default() {
assertNotNull(GlobalMemoryAccessorRegistry.getDefaultGlobalMemoryAccessor());
} |
public static String defaultEmptyIfBlank(String str) {
return defaultIfBlank(str, EMPTY);
} | @Test
void testDefaultEmptyIfBlank() {
assertEquals("", StringUtils.defaultEmptyIfBlank(null));
assertEquals("", StringUtils.defaultEmptyIfBlank(""));
assertEquals("", StringUtils.defaultEmptyIfBlank(" "));
assertEquals("bat", StringUtils.defaultEmptyIfBlank("bat"));
} |
public boolean fileExists(String path) throws IOException, InvalidTokenException {
String url;
try {
url =
getUriBuilder()
.setPath(API_PATH_PREFIX + "/mounts/primary/files/info")
.setParameter("path", path)
.build()
.toString();
} catc... | @Test
public void testFileExists() throws Exception {
server.enqueue(new MockResponse().setResponseCode(200));
boolean exists = client.fileExists("/path/to/file");
assertTrue(exists);
assertEquals(1, server.getRequestCount());
final RecordedRequest recordedRequest = server.takeRequest();
as... |
public static String prettyJson(ObjectMapper mapper, String jsonString) {
try {
Object jsonObject = mapper.readValue(jsonString, Object.class);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
} catch (JsonParseException e) {
log.debug("J... | @Test
public void testPrettyJson() {
String string = prettyJson(new ObjectMapper(), "{\"json\":\"json\"}");
String prettyJsonString = "{\n \"json\" : \"json\"\n}";
assertEquals(string, prettyJsonString);
assertNull(prettyJson(new ObjectMapper(), "{\"json\":\"json\""));
asse... |
@VisibleForTesting
@NonNull <T extends VFSConnectionDetails> FileName getConnectionRootProviderFileName(
@NonNull VFSConnectionFileNameTransformer<T> fileNameTransformer,
@NonNull T details )
throws KettleException {
// Example: "pvfs://my-connection"
ConnectionFileName rootPvfsFileName = getConn... | @Test( expected = IllegalArgumentException.class )
public void testGetConnectionRootProviderFileNameThrowsWhenConnectionNameIsEmpty() throws KettleException {
when( vfsConnectionDetails.getName() ).thenReturn( "" );
when( vfsConnectionDetails.getRootPath() ).thenReturn( "root/path" );
vfsConnectionManag... |
@Nullable
public byte[] getValue() {
return mValue;
} | @Test
public void setValue_UINT32_big() {
final MutableData data = new MutableData(new byte[4]);
data.setValue(0xF0000001L, Data.FORMAT_UINT32_LE, 0);
assertArrayEquals(new byte[] { 0x01, 0x00, 0x00, (byte) 0xF0 } , data.getValue());
} |
public static void ensureAllReadsConsumed(Pipeline pipeline) {
final Set<PCollection<?>> unconsumed = new HashSet<>();
pipeline.traverseTopologically(
new PipelineVisitor.Defaults() {
@Override
public void visitPrimitiveTransform(Node node) {
unconsumed.removeAll(node.get... | @Test
public void matcherProducesUnconsumedValueUnboundedRead() {
Unbounded<Long> transform = Read.from(CountingSource.unbounded());
pipeline.apply(transform);
UnconsumedReads.ensureAllReadsConsumed(pipeline);
validateConsumed();
} |
public LRUCacheEntry delete(final String namespace, final Bytes key) {
final NamedCache cache = getCache(namespace);
if (cache == null) {
return null;
}
final LRUCacheEntry entry;
synchronized (cache) {
final long oldSize = cache.sizeInBytes();
... | @Test
public void shouldNotBlowUpOnNonExistentNamespaceWhenDeleting() {
final ThreadCache cache = new ThreadCache(logContext, 10000L, new MockStreamsMetrics(new Metrics()));
assertNull(cache.delete(namespace, Bytes.wrap(new byte[]{1})));
} |
@Override
public long nextDelayDuration(int renewTimes) {
if (renewTimes < 0) {
renewTimes = 0;
}
int index = renewTimes;
if (index >= next.length) {
index = next.length - 1;
}
return next[index];
} | @Test
public void testNextDelayDuration() {
long value = this.retryPolicy.nextDelayDuration(times.getAndIncrement());
assertEquals(value, TimeUnit.MINUTES.toMillis(1));
value = this.retryPolicy.nextDelayDuration(times.getAndIncrement());
assertEquals(value, TimeUnit.MINUTES.toMillis... |
@Override
public MapperResult getCapacityList4CorrectUsage(MapperContext context) {
String sql = "SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?";
return new MapperResult(sql, CollectionUtils.list(context.getWhereParameter(FieldConstant.ID),
context.getWhereParameter(Fi... | @Test
void testGetCapacityList4CorrectUsage() {
Object id = 1;
Object limit = 10;
context.putWhereParameter(FieldConstant.ID, id);
context.putWhereParameter(FieldConstant.LIMIT_SIZE, limit);
MapperResult mapperResult = tenantCapacityMapperByMySql.getCapacityList4CorrectUsage(... |
@Override
public boolean updatesAreDetected(final int type) {
return false;
} | @Test
void assertUpdatesAreDetected() {
assertFalse(metaData.updatesAreDetected(0));
} |
public boolean isShardingTable(final String logicTableName) {
return shardingTables.containsKey(logicTableName);
} | @Test
void assertIsNotShardingTable() {
assertFalse(createMaximumShardingRule().isShardingTable("other_table"));
} |
@Override
public Object parse(final String property, final Object value) {
if (property.equalsIgnoreCase(KsqlConstants.LEGACY_RUN_SCRIPT_STATEMENTS_CONTENT)) {
validator.validate(property, value);
return value;
}
final ConfigItem configItem = resolver.resolve(property, true)
.orElseTh... | @Test
public void shouldCallValidatorForRunScriptConstant() {
// When:
parser.parse(KsqlConstants.LEGACY_RUN_SCRIPT_STATEMENTS_CONTENT, "something2");
// Then:
verify(validator).validate(KsqlConstants.LEGACY_RUN_SCRIPT_STATEMENTS_CONTENT, "something2");
} |
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new NewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_fails_with_NPE_if_ruleKey_is_null() {
NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap());
DetailsSupplier detailsSupplier = readDetailsSupplier(underTest);
assertThatThrownBy(() -> de... |
@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 shouldThrowOnEmptyString() {
// When:
final KsqlFunctionException e = assertThrows(
KsqlFunctionException.class,
() -> udf.stringToTimestamp("", "yyyy-MM-dd'T'HH:mm:ss.SSS")
);
// Then:
assertThat(e.getMessage(), containsString("Text '' could not be parsed at ind... |
public void updateNextVisibleTime(String topic, String group, int queueId, long queueOffset, long popTime, long nextVisibleTime) {
String key = buildKey(topic, group);
ConcurrentHashMap<Integer/*queueId*/, OrderInfo> qs = table.get(key);
if (qs == null) {
log.warn("orderInfo of queu... | @Test
public void testUpdateNextVisibleTime() {
long invisibleTime = 3000;
StringBuilder orderInfoBuilder = new StringBuilder();
consumerOrderInfoManager.update(
null,
false,
TOPIC,
GROUP,
QUEUE_ID_0,
popTime,
... |
@Override
public ObjectNode encode(MappingEntry mappingEntry, CodecContext context) {
checkNotNull(mappingEntry, "Mapping entry cannot be null");
final ObjectNode result = context.mapper().createObjectNode()
.put(ID, Long.toString(mappingEntry.id().value()))
.put(DE... | @Test
public void testMappingEntryEncode() {
MappingAddress address = MappingAddresses.ipv4MappingAddress(IPV4_PREFIX);
MappingInstruction unicastWeight = MappingInstructions.unicastWeight(UNICAST_WEIGHT);
MappingInstruction unicastPriority = MappingInstructions.unicastPriority(UNICAST_PRIO... |
public byte[] createFor(Account account, Device device, boolean includeE164) throws InvalidKeyException {
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
.setSenderDevice(Math.toIntExact(device.getId()))
.setExpires(System.currentTimeMillis() + TimeUnit.DAY... | @Test
void testCreateFor() throws IOException, InvalidKeyException, org.signal.libsignal.protocol.InvalidKeyException {
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final CertificateGenerator certificateGenerator = new CertificateGenerator(
Base64.getDecod... |
public E pop() {
if (mSize == 0) {
throw new EmptyStackException();
}
return mElements.set(--mSize, null);
} | @Test
void testIllegalPop() throws Exception {
Assertions.assertThrows(EmptyStackException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.pop();
});
} |
@SuppressWarnings("argument")
@VisibleForTesting
ProducerRecord<byte[], byte[]> transformOutput(Row row) {
row = castRow(row, row.getSchema(), schema);
String topic = Iterables.getOnlyElement(getTopics());
byte[] key = null;
byte[] payload;
List<Header> headers = ImmutableList.of();
Long tim... | @Test
public void reorderRowToRecord() {
Schema schema =
Schema.builder()
.addField(Schemas.HEADERS_FIELD, Schemas.HEADERS_FIELD_TYPE)
.addByteArrayField(Schemas.PAYLOAD_FIELD)
.build();
Schema rowSchema =
Schema.builder()
.addByteArrayField(Sche... |
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
if (targetClass != null && targetClass != method.getDeclaringClass() && isOverridable(method, targetClass)) {
try {
if (Modifier.isPublic(method.getModifiers())) {
try {
... | @Test
public void testGetMostSpecificNotPublicMethod() throws NoSuchMethodException {
Method method = AbstractMap.class.getDeclaredMethod("clone");
Method specificMethod = ClassUtils.getMostSpecificMethod(method, HashMap.class);
assertNotEquals(HashMap.class.getDeclaredMethod("clone"), speci... |
private String toStringDate() {
String retval;
if ( value == null ) {
return null;
}
SimpleDateFormat df = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss.SSS", Locale.US );
if ( isNull() || value.getDate() == null ) {
retval = Const.NULL_DATE;
} else {
retval = df.format( value.g... | @Test
public void testToStringDate() {
String result = null;
Value vs1 = new Value( "Name", Value.VALUE_TYPE_DATE );
result = vs1.toString( true );
assertEquals( "", result );
Value vs2 = new Value( "Name", Value.VALUE_TYPE_DATE );
vs2.setNull( true );
result = vs2.toString( true );
... |
@Override
public void doPut(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Put " + msgPartTwo);
} catch (Exception e) {
LOGGER.error("Exception occurred PUT request processing ", e);
... | @Test
void testDoPut() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mockR... |
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case MsSql.ID -> "VARBINARY(MAX)";
case Oracle.ID, H2.ID -> "BLOB";
case PostgreSql.ID -> "BYTEA";
default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
};... | @Test
public void generateSqlType_thows_IAE_for_unknown_dialect() {
Dialect dialect = mock(Dialect.class);
when(dialect.getId()).thenReturn("AAA");
assertThatThrownBy(() -> underTest.generateSqlType(dialect))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unsupported dialect id AA... |
@Override
public boolean removeIf(IntPredicate filter) {
throw new UnsupportedOperationException("RangeSet is immutable");
} | @Test(expected = UnsupportedOperationException.class)
public void removeIfPrimitive() {
RangeSet rs = new RangeSet(4);
rs.removeIf((int i) -> i == 3);
} |
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | @Test
public void testNonExistentProfileLocation() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setSaveProfilesToGcs(NON_EXISTENT_BUCKET);
thrown.expect(RuntimeException.class);
thrown.expectCause(instanceOf(FileNotFoundException.class));
thrown.expectMes... |
@ScalarOperator(SUBTRACT)
@SqlType(StandardTypes.INTEGER)
public static long subtract(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right)
{
try {
return Math.subtractExact((int) left, (int) right);
}
catch (ArithmeticException e) {
... | @Test
public void testSubtract()
{
assertFunction("INTEGER'37' - INTEGER'37'", INTEGER, 0);
assertFunction("INTEGER'37' - INTEGER'17'", INTEGER, 37 - 17);
assertFunction("INTEGER'17' - INTEGER'37'", INTEGER, 17 - 37);
assertFunction("INTEGER'17' - INTEGER'17'", INTEGER, 0);
... |
@Override
protected ActivityState<TransportProtos.SessionInfoProto> updateState(UUID sessionId, ActivityState<TransportProtos.SessionInfoProto> state) {
SessionMetaData session = sessions.get(sessionId);
if (session == null) {
return null;
}
state.setMetadata(session.get... | @Test
void givenNoGwSessionId_whenUpdatingActivityState_thenShouldReturnSameInstanceWithUpdatedSessionInfo() {
// GIVEN
TransportProtos.SessionInfoProto sessionInfo = TransportProtos.SessionInfoProto.newBuilder()
.setSessionIdMSB(SESSION_ID.getMostSignificantBits())
.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.