focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void onPartitionsAssigned(final Collection<TopicPartition> partitions) {
// NB: all task management is already handled by:
// org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.onAssignment
if (assignmentErrorCode.get() == AssignorError.INCOMPLETE_SOURCE_T... | @Test
public void shouldThrowTaskAssignmentExceptionOnUnrecognizedErrorCode() {
assignmentErrorCode.set(Integer.MAX_VALUE);
final TaskAssignmentException exception = assertThrows(
TaskAssignmentException.class,
() -> streamsRebalanceListener.onPartitionsAssigned(Collections.... |
static SerializableFunction<LinkedHashMap<String, Double>,
LinkedHashMap<String, Double>> getProbabilityMapFunction(final RegressionModel.NormalizationMethod normalizationMethod,
final boolean isBinary) {
if (UNSUPPORTED_NORMALIZAT... | @Test
void getProbabilityMapUnsupportedFunction() {
KiePMMLClassificationTableFactory.UNSUPPORTED_NORMALIZATION_METHODS.forEach(normalizationMethod -> {
try {
KiePMMLClassificationTableFactory.getProbabilityMapFunction(normalizationMethod, false);
} catch (Throwable t... |
@Override
public boolean isNetworkRequestEnable() {
return false;
} | @Test
public void isNetworkRequestEnable() {
Assert.assertFalse(mSensorsAPI.isNetworkRequestEnable());
} |
public void cancel() {
if (isOpen()) {
LOG.debug("Cancelling stream ({})", mDescription);
mCanceled = true;
mRequestObserver.cancel("Request is cancelled by user.", null);
}
} | @Test
public void cancel() throws Exception {
mStream.cancel();
assertTrue(mStream.isCanceled());
assertFalse(mStream.isOpen());
verify(mRequestObserver).cancel(any(String.class), eq(null));
} |
public TolerantDoubleComparison isNotWithin(double tolerance) {
return new TolerantDoubleComparison() {
@Override
public void of(double expected) {
Double actual = DoubleSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolera... | @Test
public void isNotWithinZeroTolerance() {
double max = Double.MAX_VALUE;
assertThatIsNotWithinFails(max, 0.0, max);
assertThatIsNotWithinFails(NEARLY_MAX, 0.0, NEARLY_MAX);
assertThat(max).isNotWithin(0.0).of(NEARLY_MAX);
assertThat(NEARLY_MAX).isNotWithin(0.0).of(max);
double min = Doub... |
@Override
public <T> T detach(T attachedObject) {
addExpireListener(commandExecutor);
Map<String, Object> alreadyDetached = new HashMap<String, Object>();
return detach(attachedObject, alreadyDetached);
} | @Test
public void testDetach() {
RLiveObjectService service = redisson.getLiveObjectService();
TestClass ts = new TestClass(new ObjectId(100));
ts.setValue("VALUE");
ts.setCode("CODE");
TestClass merged = service.merge(ts);
assertEquals("VALUE", merged.getValue());
... |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
String method = request.getMethod();
URI uri = request.getUri();
for (Rule rule : rules) {
if (rule.matches(method, uri)) {
log.log(Level.FINE, () ->
String.for... | @Test
void performs_action_on_first_matching_rule() throws IOException {
RuleBasedFilterConfig config = new RuleBasedFilterConfig.Builder()
.dryrun(false)
.defaultRule(new DefaultRule.Builder()
.action(DefaultRule.Action.Enum.ALLOW))
.r... |
public abstract void calculateIV(byte[] initIV, long counter, byte[] IV); | @Test(timeout=120000)
public void testCalculateIV() throws Exception {
JceAesCtrCryptoCodec codec = new JceAesCtrCryptoCodec();
codec.setConf(conf);
SecureRandom sr = new SecureRandom();
byte[] initIV = new byte[16];
byte[] IV = new byte[16];
long iterations = 1000;
long counter = 10000;... |
@Override
public void disableCaching() {
close(regularDbSession, "regular");
close(batchDbSession, "batch");
regularDbSession.remove();
batchDbSession.remove();
CACHING_ENABLED.remove();
} | @Test
void disableCaching_has_no_effect_if_enabledCaching_has_not_been_called() {
underTest.disableCaching();
verifyNoMoreInteractions(myBatis);
} |
@Override
public void endInput() throws Exception {
endCompaction(Long.MAX_VALUE);
snapshotState(Long.MAX_VALUE);
clearExpiredFiles(Long.MAX_VALUE);
} | @Test
void testEndInput() throws Exception {
Path f0 = newFile(".uncompacted-f0", 3);
Path f1 = newFile(".uncompacted-f1", 4);
Path f2 = newFile(".uncompacted-f2", 2);
FileSystem fs = f0.getFileSystem();
runCompact(
harness -> {
harness.s... |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetMonitoringInterceptorConfigProperties() {
final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap(
"confluent.monitoring.interceptor.topic", "foo"));
final Object result
= ksqlConfig.getKsqlStreamConfigProps().get("confluent.monitoring.interceptor.topic... |
public static List<URL> parseURLs(String address, Map<String, String> defaults) {
if (StringUtils.isEmpty(address)) {
throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter.");
}
String[] addresses = REGISTRY_SPLIT_PATTERN.split(address);
if (... | @Test
void testParseUrlsAddressNull() {
String exceptionMessage = "Address is not allowed to be empty, please re-enter.";
try {
UrlUtils.parseURLs(null, null);
} catch (IllegalArgumentException illegalArgumentException) {
assertEquals(exceptionMessage, illegalArgument... |
@ApiOperation(value = "获取接口资源分页列表")
@GetMapping("/page")
public ApiPageResult<IPage<BaseAction>> page(PageForm pageForm){
return ApiPageResult.success(baseActionService.page(new Page(pageForm.getPageNum(), pageForm.getPageSize())));
} | @Test
void page() {
} |
@Override
public boolean shouldFire(TriggerStateMachine.TriggerContext context) {
return false;
} | @Test
public void falseAfterEndOfWindow() throws Exception {
triggerTester.injectElements(TimestampedValue.of(1, new Instant(1)));
IntervalWindow window =
new IntervalWindow(new Instant(0), new Instant(0).plus(Duration.standardMinutes(5)));
assertThat(triggerTester.shouldFire(window), is(false));
... |
public void setSQLServerInstance( String instanceName ) {
// This is also covered/persisted by JDBC option MS SQL Server / instancename / <somevalue>
// We want to return set <somevalue>
// --> MSSQL.instancename
if ( ( instanceName != null ) && ( instanceName.length() > 0 ) ) {
addExtraOption( ge... | @Test
public void setSQLServerInstanceTest() {
DatabaseMeta dbmeta = new DatabaseMeta();
DatabaseInterface mssqlServerDatabaseMeta = new MSSQLServerDatabaseMeta();
mssqlServerDatabaseMeta.setPluginId( "MSSQL" );
DatabaseInterface mssqlServerNativeDatabaseMeta = new MSSQLServerNativeDatabaseMeta();
... |
GooglePubsubLiteConsumer(GooglePubsubLiteEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
this.processor = processor;
this.subscribers = Collections.synchronizedList(new LinkedList<>());
String loggerId = endpoint.getLoggerId();
... | @Test
public void testGooglePubsubLiteConsumer() {
when(endpoint.getCamelContext()).thenReturn(context);
GooglePubsubLiteConsumer consumer = new GooglePubsubLiteConsumer(endpoint, processor);
assertNotNull(consumer);
} |
public Frequency multiply(long value) {
return new Frequency(this.frequency * value);
} | @Test
public void testMultiply() {
Frequency frequency = Frequency.ofMHz(1000);
long factor = 5;
Frequency expected = Frequency.ofGHz(5);
assertThat(frequency.multiply(5), is(expected));
} |
@Nullable
public PasswordAlgorithm forPassword(String hashedPassword) {
for (PasswordAlgorithm passwordAlgorithm : passwordAlgorithms.values()) {
if (passwordAlgorithm.supports(hashedPassword))
return passwordAlgorithm;
}
return null;
} | @Test
public void testForPasswordShouldReturnSecondAlgorithm() throws Exception {
when(passwordAlgorithm1.supports(anyString())).thenReturn(false);
when(passwordAlgorithm2.supports(anyString())).thenReturn(true);
final PasswordAlgorithmFactory passwordAlgorithmFactory = new PasswordAlgorith... |
public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" ) );
}
... | @Test
public void testGetLegacyColumnNameDriverLessOrEqualToThreeFieldNoAliasText() throws Exception {
DatabaseMetaData databaseMetaData = mock( DatabaseMetaData.class );
doReturn( 3 ).when( databaseMetaData ).getDriverMajorVersion();
assertEquals( "NoAliasText", new MySQLDatabaseMeta().getLegacyColumnNa... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testCpuLS() {
test(Loss.ls(), "CPU", CPU.formula, CPU.data, 60.5335);
} |
public boolean hasRequiredResourceManagers()
{
return currentResourceManagerCount >= resourceManagerMinCountActive;
} | @Test
public void testHasRequiredResourceManagers()
throws InterruptedException
{
assertFalse(monitor.hasRequiredResourceManagers());
for (int i = numResourceManagers.get(); i < DESIRED_RESOURCE_MANAGER_COUNT_ACTIVE; i++) {
addResourceManager(nodeManager);
}
... |
public static ArrayByteIterable comparableSetToEntry(@NotNull final ComparableSet object) {
return BINDING.objectToEntry(object);
} | @Test(expected = ExodusException.class)
public void empty() {
ComparableSetBinding.comparableSetToEntry(new ComparableSet());
} |
String offsetSyncsTopic() {
String otherClusterAlias = SOURCE_CLUSTER_ALIAS_DEFAULT.equals(offsetSyncsTopicLocation())
? targetClusterAlias()
: sourceClusterAlias();
return replicationPolicy().offsetSyncsTopic(otherClusterAlias);
} | @Test
public void testOffsetSyncsTopic() {
// Invalid location
Map<String, String> connectorProps = makeProps("offset-syncs.topic.location", "something");
assertThrows(ConfigException.class, () -> new MirrorSourceConfig(connectorProps));
connectorProps.put("offset-syncs.topic.locati... |
@Override
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
} | @Test
public void testHashCode() {
PathSpecSet pss1 = PathSpecSet.of(THREE_FIELD_MODEL_FIELD1, THREE_FIELD_MODEL_FIELD2);
PathSpecSet pss2 = PathSpecSet.of(THREE_FIELD_MODEL_FIELD1, THREE_FIELD_MODEL_FIELD2);
Assert.assertEquals(pss1.hashCode(), pss2.hashCode());
} |
public void process() {
LOGGER.debug("Beginning Composer lock processing");
try {
final JsonObject composer = jsonReader.readObject();
if (composer.containsKey("packages")) {
LOGGER.debug("Found packages");
final JsonArray packages = composer.getJs... | @Test(expected = ComposerException.class)
public void testNotPackagesArray() throws Exception {
String input = "{\"packages\":\"eleventy\"}";
ComposerLockParser clp = new ComposerLockParser(new ByteArrayInputStream(input.getBytes(Charset.defaultCharset())));
clp.process();
} |
public synchronized void addAll(T... nodes) {
for (T node : nodes) {
addInternal(node, defaultReplication);
}
refreshTable();
} | @Test
@Ignore("Helper test for performance, no assertion")
public void speed() {
Map<String, Integer> data = new CopyOnWriteMap.Hash<>();
for (int i = 0; i < 1000; i++) {
data.put("node" + i, 100);
}
data.put("tail", 100);
long start = System.currentTimeMilli... |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
boolean useJavaCC = "--useJavaCC".equals(getArg(args, 0, null));
if (args.size() > (useJavaCC ? 3 : 2)
|| (args.size() == 1 && (args.get(0).equals("--help") || args.get(0).equals("-help"))... | @Test
public void testWriteIdlAsSchema() throws Exception {
String idl = "src/test/idl/schema.avdl";
String protocol = "src/test/idl/schema.avsc";
String outfile = "target/test-schema.avsc";
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
List<String> arglist = Arrays.asList(idl, outf... |
public static String kbToHumanReadable(long kb) {
int unit = 1;
while (kb >= KB && unit < UNITS.length() - 1) {
kb /= KB;
unit++;
}
String kbString = String.valueOf(kb);
return kbString + UNITS.charAt(unit);
} | @Test
void kbToHumanReadable() {
Assertions.assertEquals("0k", OsUtils.kbToHumanReadable(0L));
Assertions.assertEquals("1001k", OsUtils.kbToHumanReadable(1001L));
Assertions.assertEquals("1m", OsUtils.kbToHumanReadable(1024L));
Assertions.assertEquals("1023m", OsUtils.kbToHumanReadab... |
@Override
public void onHeartbeatSuccess(ShareGroupHeartbeatResponseData response) {
if (response.errorCode() != Errors.NONE.code()) {
String errorMessage = String.format(
"Unexpected error in Heartbeat response. Expected no error, but received: %s",
Error... | @Test
public void testTransitionToReconcilingIfEmptyAssignmentReceived() {
ShareMembershipManager membershipManager = createMembershipManagerJoiningGroup();
assertEquals(MemberState.JOINING, membershipManager.state());
ShareGroupHeartbeatResponse responseWithoutAssignment = createShareGroup... |
@Override
public void configure(String encodedAuthParamString) {
checkArgument(isNotBlank(encodedAuthParamString), "authParams must not be empty");
try {
setAuthParams(AuthenticationUtil.configureFromJsonString(encodedAuthParamString));
} catch (IOException e) {
thro... | @Test
public void testCopperArgos() throws Exception {
@Cleanup
AuthenticationAthenz caAuth = new AuthenticationAthenz();
Field ztsClientField = caAuth.getClass().getDeclaredField("ztsClient");
ztsClientField.setAccessible(true);
ztsClientField.set(caAuth, new MockZTSClient("... |
public void collect(K key, V value, int partition) throws IOException {
kvPusher.collect(key, value, partition);
} | @Test
public void testCollect() throws IOException {
this.handler = new NativeCollectorOnlyHandler(taskContext, nativeHandler, pusher, combiner);
handler.collect(new BytesWritable(), new BytesWritable(), 100);
handler.close();
handler.close();
Mockito.verify(pusher, Mockito.times(1)).collect(any(... |
File putIfAbsent(String userId, boolean saveToDisk) throws IOException {
String idKey = getIdStrategy().keyFor(userId);
String directoryName = idToDirectoryNameMap.get(idKey);
File directory = null;
if (directoryName == null) {
synchronized (this) {
directoryN... | @Test
public void testDirectoryFormatSingleCharacter() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = ".";
File directory1 = mapper.putIfAbsent(user1, true);
assertThat(directory1.getName(), startsWith("_"));
} |
void forwardToStateService(DeviceStateServiceMsgProto deviceStateServiceMsg, TbCallback callback) {
if (statsEnabled) {
stats.log(deviceStateServiceMsg);
}
stateService.onQueueMsg(deviceStateServiceMsg, callback);
} | @Test
public void givenProcessingSuccess_whenForwardingActivityMsgToStateService_thenOnSuccessCallbackIsCalled() {
// GIVEN
var activityMsg = TransportProtos.DeviceActivityProto.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(te... |
@Override
public void updateLoadBalancer(KubevirtLoadBalancer lb) {
checkNotNull(lb, ERR_NULL_LOAD_BALANCER);
checkArgument(!Strings.isNullOrEmpty(lb.name()), ERR_NULL_LOAD_BALANCER_NAME);
kubevirtLoadBalancerStore.updateLoadBalancer(lb);
log.info(String.format(MSG_LOAD_BALANCER, lb... | @Test(expected = IllegalArgumentException.class)
public void testUpdateUnregisteredLoadBalancer() {
target.updateLoadBalancer(LB);
} |
public Map<String, String> getExtendData() {
return extendData;
} | @Test
void testGetExtendData() {
Map<String, String> extendData = serviceMetadata.getExtendData();
assertNotNull(extendData);
assertEquals(0, extendData.size());
} |
@Override
public void getPipeline(
GetJobPipelineRequest request, StreamObserver<GetJobPipelineResponse> responseObserver) {
LOG.trace("{} {}", GetJobPipelineRequest.class.getSimpleName(), request);
String invocationId = request.getJobId();
try {
JobInvocation invocation = getInvocation(invoca... | @Test
public void testGetPipelineIsSuccessful() throws Exception {
prepareAndRunJob();
JobApi.GetJobPipelineRequest request =
JobApi.GetJobPipelineRequest.newBuilder().setJobId(TEST_JOB_ID).build();
RecordingObserver<JobApi.GetJobPipelineResponse> recorder = new RecordingObserver<>();
service... |
@Override
public Http2Headers decodeHeaders(int streamId, ByteBuf headerBlock) throws Http2Exception {
try {
final Http2Headers headers = newHeaders();
hpackDecoder.decode(streamId, headerBlock, headers, validateHeaders);
headerArraySizeAccumulator = HEADERS_COUNT_WEIGHT_... | @Test
public void decodingTrailersTeHeaderMustNotFailValidation() throws Exception {
// The TE header is expressly allowed to have the value "trailers".
ByteBuf buf = null;
try {
buf = encode(b(":method"), b("GET"), b("te"), b("trailers"));
Http2Headers headers = deco... |
public SimpleMain(CamelContext camelContext) {
super(camelContext);
} | @Test
public void testSimpleMain() throws Exception {
List<String> events = new ArrayList<>();
CamelContext context = new DefaultCamelContext();
SimpleMain main = new SimpleMain(context);
main.configure().addRoutesBuilder(new MyRouteBuilder());
main.addMainListener(new MainL... |
public static <T, V> Collection<V> flatCollect(
Iterable<T> iterable,
Function<? super T, ? extends Iterable<V>> function)
{
return FJIterate.flatCollect(iterable, function, false);
} | @Test
public void flatCollect()
{
this.iterables.each(this::basicFlatCollect);
} |
public boolean contains(int value) {
return contains(Util.toUnsignedLong(value));
} | @Test
public void testContains() {
// empty
Assert.assertFalse(emptyBitmap.contains(1));
// single value
Assert.assertTrue(singleBitmap.contains(1));
Assert.assertFalse(singleBitmap.contains(2));
// bitmap
Assert.assertTrue(largeBitmap.contains(1));
... |
public final boolean checkIfExecuted(String input) {
return this.validator.isExecuted(Optional.of(ByteString.copyFromUtf8(input)));
} | @Test
public void checkIfExecuted_withOptional_executesValidator() {
TestValidatorIsCalledValidator testValidator = new TestValidatorIsCalledValidator();
Payload payload = new Payload("my-payload", testValidator, PAYLOAD_ATTRIBUTES, CONFIG);
payload.checkIfExecuted(Optional.empty());
assertTrue(testV... |
@Override
public Integer doCall() throws Exception {
CommandLineHelper.createPropertyFile();
if (configuration.split("=").length == 1) {
printer().println("Configuration parameter not in key=value format");
return 1;
}
CommandLineHelper.loadProperties(proper... | @Test
public void shouldOverwriteConfig() throws Exception {
UserConfigHelper.createUserConfig("foo=bar");
ConfigSet command = new ConfigSet(new CamelJBangMain().withPrinter(printer));
command.configuration = "foo=baz";
command.doCall();
Assertions.assertEquals("", printer.... |
public synchronized Counter findCounter(String group, String name) {
if (name.equals("MAP_INPUT_BYTES")) {
LOG.warn("Counter name MAP_INPUT_BYTES is deprecated. " +
"Use FileInputFormatCounters as group name and " +
" BYTES_READ as counter name instead");
return findCounter... | @SuppressWarnings("rawtypes")
@Test
public void testFrameworkCounter() {
GroupFactory groupFactory = new GroupFactoryForTest();
FrameworkGroupFactory frameworkGroupFactory =
groupFactory.newFrameworkGroupFactory(JobCounter.class);
Group group = (Group) frameworkGroupFactory.newGroup("JobCounter... |
@Override
public void deleteProject(Long id) {
// 校验存在
validateProjectExists(id);
// 删除
goViewProjectMapper.deleteById(id);
} | @Test
public void testDeleteProject_success() {
// mock 数据
GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class);
goViewProjectMapper.insert(dbGoViewProject);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbGoViewProject.getId();
// 调用
goViewProjectServ... |
private RemotingCommand getProducerConnectionList(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetProducerConnectionListRequestHeader requestHeader =
(GetProdu... | @Test
public void testGetProducerConnectionList() throws RemotingCommandException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_PRODUCER_CONNECTION_LIST, null);
request.addExtField("producerGroup", "ProducerGroupId");
RemotingCommand response = adminBrokerP... |
public static <T> T uncheckIOExceptions(CallableRaisingIOE<T> call) {
return call.unchecked();
} | @Test
public void testUncheckIOExceptionsUnchecked() throws Throwable {
final UncheckedIOException raised = new UncheckedIOException(
new IOException("text"));
final UncheckedIOException ex = intercept(UncheckedIOException.class, "text", () ->
uncheckIOExceptions(() -> {
throw raised... |
protected void updateCurrentDir() {
String prevCurrentDir = variables.getVariable( Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY );
String currentDir = variables.getVariable(
repository != null
? Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY
: filename != null
? Const.... | @Test
public void testUpdateCurrentDirWithFilename( ) {
JobMeta jobMetaTest = new JobMeta( );
jobMetaTest.setFilename( "hasFilename" );
jobMetaTest.setVariable( Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY, "Original value defined at run execution" );
jobMetaTest.setVariable( Const.INTERNAL_VARIAB... |
public int format(String... args) throws UsageException {
CommandLineOptions parameters = processArgs(args);
if (parameters.version()) {
errWriter.println(versionString());
return 0;
}
if (parameters.help()) {
throw new UsageException();
}
JavaFormatterOptions options =
... | @Test
public void importRemoveErrorParseError() throws Exception {
Locale backupLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.ROOT);
String[] input = {
"import java.util.ArrayList;", //
"import java.util.List;",
"class Test {",
"}}",
};
S... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void returnOnCompleteUsingSingle() throws InterruptedException {
RetryConfig config = retryConfig();
Retry retry = Retry.of("testName", config);
given(helloWorldService.returnHelloWorld())
.willReturn("Hello world")
.willThrow(new HelloWorldException())
... |
public void reloadTpsControlRule(String pointName, boolean external) {
NotifyCenter.publishEvent(new TpsControlRuleChangeEvent(pointName, external));
} | @Test
void testReloadTpsControlRule() throws Exception {
String localRuleStorageBaseDir = EnvUtils.getNacosHome() + File.separator + "tmpTps" + File.separator + "tps" + File.separator;
ControlConfigs.getInstance().setLocalRuleStorageBaseDir(localRuleStorageBaseDir);
resetRuleStorageProxy();
... |
@Bean(PRODUCER_BEAN_NAME)
@ConditionalOnMissingBean(DefaultMQProducer.class)
@ConditionalOnProperty(prefix = "rocketmq", value = {"name-server", "producer.group"})
public DefaultMQProducer defaultMQProducer(RocketMQProperties rocketMQProperties) {
RocketMQProperties.Producer producerConfig = rocketM... | @Test
public void testDefaultMQProducer() {
runner.withPropertyValues("rocketmq.name-server=127.0.0.1:9876",
"rocketmq.producer.group=spring_rocketmq").
run((context) -> {
assertThat(context).hasSingleBean(DefaultMQProducer.class);
});
} |
@VisibleForTesting
static void validateDefaultTopicFormats(final KsqlConfig config) {
validateTopicFormat(config, KsqlConfig.KSQL_DEFAULT_KEY_FORMAT_CONFIG, "key");
validateTopicFormat(config, KsqlConfig.KSQL_DEFAULT_VALUE_FORMAT_CONFIG, "value");
} | @Test
public void shouldFailOnInvalidDefaultValueFormat() {
// Given:
final KsqlConfig config = configWith(ImmutableMap.of(
KsqlConfig.KSQL_DEFAULT_VALUE_FORMAT_CONFIG, "bad"
));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> KsqlServerMain.validateD... |
static boolean toBoolean(final JsonNode object) {
if (object instanceof BooleanNode) {
return object.booleanValue();
}
throw invalidConversionException(object, SqlBaseType.BOOLEAN);
} | @Test
public void shouldNotIncludeValueInExceptionWhenFailingToBoolean() {
try {
// When:
JsonSerdeUtils.toBoolean(JsonNodeFactory.instance.textNode("personal info: do not log me"));
fail("Invalid test: should throw");
} catch (final Exception e) {
assertThat(ExceptionUtils.getStackT... |
void consumeAll(Consumer<T> consumer) throws InterruptedException {
waitForData();
try {
for (int i = size(); i-- > 0; ) {
consumer.consume(front()); // can take forever
_dequeue();
}
}
finally {
clearConsumerLock();
}
} | @Test public void testConsumeAll() throws Exception {
final int capacity = 64; // arbitrary
final SinkQueue<Integer> q = new SinkQueue<Integer>(capacity);
for (int i = 0; i < capacity; ++i) {
assertTrue("should enqueue", q.enqueue(i));
}
assertTrue("should not enqueue", !q.enqueue(capacity))... |
public static KafkaPool fromCrd(
Reconciliation reconciliation,
Kafka kafka,
KafkaNodePool pool,
NodeIdAssignment idAssignment,
Storage oldStorage,
OwnerReference ownerReference,
SharedEnvironmentProvider sharedEnvironmentProvider
)... | @Test
public void testResourceValidation() {
KafkaNodePool pool = new KafkaNodePoolBuilder(POOL)
.editSpec()
.withResources(new ResourceRequirementsBuilder()
.withRequests(Map.of("cpu", new Quantity("4"), "memory", new Quantity("-16Gi")))
... |
@Override
public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) {
final ModelId modelId = entityDescriptor.id();
try {
final Output output = outputService.load(modelId.id());
return Optional.of(exportNativeEntity(outp... | @Test
public void exportEntity() {
final ImmutableMap<String, Object> configuration = ImmutableMap.of(
"some-setting", "foobar"
);
final OutputImpl output = OutputImpl.create(
"01234567890",
"Output Title",
"org.graylog2.outputs... |
@VisibleForTesting
static CompostState determineCompostUsed(String chatMessage)
{
if (!chatMessage.contains("compost"))
{
return null;
}
Matcher matcher;
if ((matcher = COMPOST_USED_ON_PATCH.matcher(chatMessage)).matches() ||
(matcher = FERTILE_SOIL_CAST.matcher(chatMessage)).find() ||
(matcher = ... | @Test
public void determineCompostUsed_returnsAppropriateCompostValues()
{
// invalid
collector.checkThat(
CompostTracker.determineCompostUsed("This is not a farming chat message."),
is((CompostState) null)
);
collector.checkThat(
CompostTracker.determineCompostUsed("Contains word compost but is not ... |
public static JavaVersion parse(String version)
{
Matcher matcher = LEGACY_PATTERN.matcher(version);
if (matcher.matches()) {
int major = Integer.parseInt(matcher.group("MAJOR"));
int minor = Optional.ofNullable(matcher.group("MINOR"))
.map(Integer::parseI... | @Test
public void testParseLegacy()
{
assertEquals(JavaVersion.parse("1.8"), new JavaVersion(8, 0));
assertEquals(JavaVersion.parse("1.8.0"), new JavaVersion(8, 0));
assertEquals(JavaVersion.parse("1.8.0_5"), new JavaVersion(8, 0, OptionalInt.of(5)));
assertEquals(JavaVersion.par... |
@Override
public long estimate() {
final double raw = (1 / computeE()) * alpha() * m * m;
return applyRangeCorrection(raw);
} | @Test
public void testAlpha_withMemoryFootprintOf32() {
DenseHyperLogLogEncoder encoder = new DenseHyperLogLogEncoder(5);
encoder.estimate();
} |
protected SaveFederationQueuePolicyRequest parsePolicy(String policy) throws YarnException {
String[] policyItems = policy.split(SEMICOLON);
if (policyItems == null || policyItems.length != 4) {
throw new YarnException("The policy cannot be empty or the policy is incorrect. \n" +
" Required inf... | @Test
public void testParsePolicy() throws Exception {
// Case1, If policy is empty.
String errMsg1 = "The policy cannot be empty or the policy is incorrect. \n" +
" Required information to provide: queue,router weight,amrm weight,headroomalpha \n" +
" eg. root.a;SC-1:0.7,SC-2:0.3;SC-1:0.7,SC-... |
@Override
public ValidationTaskResult validateImpl(Map<String, String> optionMap)
throws InterruptedException {
String hadoopVersion;
try {
hadoopVersion = getHadoopVersion();
} catch (IOException e) {
return new ValidationTaskResult(ValidationUtils.State.FAILED, getName(),
... | @Test
public void versionMatched() throws Exception {
PowerMockito.mockStatic(ShellUtils.class);
String[] cmd = new String[]{"hadoop", "version"};
BDDMockito.given(ShellUtils.execCommand(cmd)).willReturn("Hadoop 2.6");
CONF.set(PropertyKey.UNDERFS_VERSION, "2.6");
HdfsVersionValidationTask task =... |
public static boolean isBlank(String str) {
return StringUtils.isBlank(str);
} | @Test
public void testIsBlank() {
assertThat(UtilAll.isBlank("Hello ")).isFalse();
assertThat(UtilAll.isBlank(" Hello")).isFalse();
assertThat(UtilAll.isBlank("He llo")).isFalse();
assertThat(UtilAll.isBlank(" ")).isTrue();
assertThat(UtilAll.isBlank("Hello")).isFalse();
... |
public boolean same(final KsqlVersion version) {
return isAtLeast(version) && version.isAtLeast(this);
} | @Test
public void shouldCompareCpVersionToStandaloneVersionInSame() {
// known mappings
assertThat(new KsqlVersion("6.0.").same(new KsqlVersion("0.10.")), is(true));
assertThat(new KsqlVersion("0.10.").same(new KsqlVersion("6.0.")), is(true));
assertThat(new KsqlVersion("6.1.").same(new KsqlVersion("... |
@Override
public CompletableFuture<PopResult> popMessage(ProxyContext ctx, AddressableMessageQueue messageQueue,
PopMessageRequestHeader requestHeader, long timeoutMillis) {
requestHeader.setBornTime(System.currentTimeMillis());
RemotingCommand request = LocalRemotingCommand.createRequestCom... | @Test
public void testPopMessageWriteAndFlush() throws Exception {
int reviveQueueId = 1;
long popTime = System.currentTimeMillis();
long invisibleTime = 3000L;
long startOffset = 100L;
long restNum = 0L;
StringBuilder startOffsetStringBuilder = new StringBuilder();
... |
@NotNull
public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) {
// 优先从 DB 中获取,因为 code 有且可以使用一次。
// 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次
SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state);
i... | @Test
public void testAuthSocialUser_notNull() {
// mock 数据
SocialUserDO socialUser = randomPojo(SocialUserDO.class,
o -> o.setType(SocialTypeEnum.GITEE.getType()).setCode("tudou").setState("yuanma"));
socialUserMapper.insert(socialUser);
// 准备参数
Integer socia... |
public boolean isEmpty() {
return results.isEmpty();
} | @Test
public void empty() {
assertTrue(result.isEmpty());
} |
@VisibleForTesting
static String extractUrn(MonitoringInfoSpecs.Enum value) {
return value.getValueDescriptor().getOptions().getExtension(monitoringInfoSpec).getUrn();
} | @Test
public void testUniqueUrnsDefinedForAllSpecs() {
Multimap<String, MonitoringInfoSpecs.Enum> urnToEnum = ArrayListMultimap.create();
for (MonitoringInfoSpecs.Enum value : MonitoringInfoSpecs.Enum.values()) {
if (value != MonitoringInfoSpecs.Enum.UNRECOGNIZED) {
urnToEnum.put(extractUrn(valu... |
@Override
protected Map<String, RowMetaInterface> getInputRowMetaInterfaces( GetXMLDataMeta meta ) {
Map<String, RowMetaInterface> inputRows = getInputFields( meta );
if ( inputRows == null ) {
inputRows = new HashMap<>();
}
// Get some boolean flags from the meta for easier access
boolean i... | @Test
public void testGetInputRowMetaInterfaces_isInFields() throws Exception {
when( parentTransMeta.getPrevStepNames( Mockito.<StepMeta>any() ) ).thenReturn( null );
RowMetaInterface rowMetaInterface = mock( RowMetaInterface.class );
lenient().doReturn( rowMetaInterface ).when( analyzer ).getOutputFiel... |
@Override
public void registerStore(final StateStore store,
final StateRestoreCallback stateRestoreCallback,
final CommitCallback commitCallback) {
final String storeName = store.name();
// TODO (KAFKA-12887): we should not trigger user's ... | @Test
public void shouldThrowProcessorStateExceptionOnFlushIfStoreThrowsAnException() {
final RuntimeException exception = new RuntimeException("KABOOM!");
final ProcessorStateManager stateManager = getStateManager(Task.TaskType.ACTIVE);
final MockKeyValueStore stateStore = new MockKeyValueS... |
@Override
public SarifSchema210 deserialize(Path reportPath) {
try {
return mapper
.enable(JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION)
.addHandler(new DeserializationProblemHandler() {
@Override
public Object handleInstantiationProblem(DeserializationContext ctxt, Clas... | @Test
public void deserialize() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("eslint-sarif210.json"));
Path sarif = Paths.get(sarifResource.toURI());
SarifSchema210 deserializationResult = serializer.deserialize(sarif);
verifySarif(deserializationResult);
} |
@Override
public void close() {
isRunning.set(false);
getListener().onClose(this);
} | @Test
public void shouldCallbackOnClose() {
// when:
sandboxed.close();
// then:
verify(listener).onClose(sandboxed);
} |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed!");
return;
}
final List<SearchPivotLimitMigration> pivotLimitMigrations = StreamSupport.stream(this.searches.find().spliterator... | @Test
@MongoDBFixtures("V20230113095301_MigrateGlobalPivotLimitsToGroupingsInSearchesTest_empty.json")
void notMigratingAnythingIfNoSearchesArePresent() {
this.migration.upgrade();
assertThat(migrationCompleted().migratedSearchTypes()).isZero();
} |
public IssuesChangesNotification newIssuesChangesNotification(Set<DefaultIssue> issues, Map<String, UserDto> assigneesByUuid) {
AnalysisChange change = new AnalysisChange(analysisMetadataHolder.getAnalysisDate());
Set<ChangedIssue> changedIssues = issues.stream()
.map(issue -> new ChangedIssue.Builder(iss... | @Test
public void newIssuesChangesNotification_fails_with_ISE_if_treeRootHolder_is_empty() {
RuleKey ruleKey = RuleKey.of("foo", "bar");
DefaultIssue issue = new DefaultIssue()
.setRuleKey(ruleKey);
Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid();
ruleRepository.add(ruleKey);
... |
@Override
public void updateSettings(Map<String, String> settings, AuthenticationInfo subject) {
if (settings == null || settings.isEmpty()) {
LOGGER.error("Cannot update {} with empty settings", this.getClass().getName());
return;
}
String newNotebookDirectotyPath = StringUtils.EMPTY;
if ... | @Test
void testUpdateSettings() throws IOException {
List<NotebookRepoSettingsInfo> repoSettings = notebookRepo.getSettings(AuthenticationInfo.ANONYMOUS);
assertEquals(1, repoSettings.size());
NotebookRepoSettingsInfo settingInfo = repoSettings.get(0);
assertEquals("Notebook Path", settingInfo.name);
... |
@Override
public Failure parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
Failure.CompressFailureError compressFailureError = null;
StanzaError stanzaError = null;
XmlEnvironment failureXmlEnviron... | @Test
public void withStanzaErrrorFailureTest() throws Exception {
final String xml = "<failure xmlns='http://jabber.org/protocol/compress'>"
+ "<setup-failed/>"
+ "<error xmlns='jabber:client' type='modify'>"
+ "<bad-request xmlns='u... |
public static void checkState(boolean isValid, String message) throws IllegalStateException {
if (!isValid) {
throw new IllegalStateException(message);
}
} | @Test
public void testCheckStateWithoutArguments() {
try {
Preconditions.checkState(true, "Test message");
} catch (IllegalStateException e) {
Assert.fail("Should not throw exception when isValid is true");
}
try {
Preconditions.checkState(false, "Test message");
Assert.fail("... |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) {
final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported schema type: " + schema.type()... | @Test
public void shouldVisitBytes() {
// Given:
final Schema schema = Schema.OPTIONAL_BYTES_SCHEMA;
when(visitor.visitBytes(any())).thenReturn("Expected");
// When:
final String result = SchemaWalker.visit(schema, visitor);
// Then:
verify(visitor).visitBytes(same(schema));
assertTh... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String tableNameSuffix = String.valueOf(doSharding(parseDa... | @Test
void assertRangeDoShardingWithAllRange() {
List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3", "t_order_4");
Collection<String> actual = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "cre... |
public PrivateKey convertPrivateKey(final String privatePemKey) {
StringReader keyReader = new StringReader(privatePemKey);
try {
PrivateKeyInfo privateKeyInfo = PrivateKeyInfo
.getInstance(new PEMParser(keyReader).readObject());
return new JcaPEMKeyConverter... | @Test
void givenEmptyPrivateKey_whenConvertPrivateKey_thenThrowRuntimeException() {
// Given
String emptyPrivatePemKey = "";
// When & Then
assertThatThrownBy(() -> KeyConverter.convertPrivateKey(emptyPrivatePemKey))
.isInstanceOf(RuntimeException.class)
... |
Path getImageDirectory(ImageReference imageReference) {
// Replace ':' and '@' with '!' to avoid directory-naming restrictions
String replacedReference =
imageReference.toStringWithQualifier().replace(':', '!').replace('@', '!');
// Split image reference on '/' to build directory structure
Iter... | @Test
public void testGetImageDirectory() throws InvalidImageReferenceException {
Path imagesDirectory = Paths.get("cache", "directory", "images");
Assert.assertEquals(imagesDirectory, TEST_CACHE_STORAGE_FILES.getImagesDirectory());
Assert.assertEquals(
imagesDirectory.resolve("reg.istry/repo/sit... |
public static Field p(String fieldName) {
return SELECT_ALL_FROM_SOURCES_ALL.where(fieldName);
} | @Test
void contains_near_onear_with_annotation() {
{
String q = Q.p("f1").containsNear(A.a("distance", 5), "p1", "p2", "p3")
.build();
assertEquals(q, "yql=select * from sources * where f1 contains ([{\"distance\":5}]near(\"p1\", \"p2\", \"p3\"))");
}
... |
@Override
public Optional<IdentityProvider> getIdentityProvider() {
return Optional.empty();
} | @Test
public void getIdentityProvider() {
assertThat(githubWebhookUserSession.getIdentityProvider()).isEmpty();
} |
@Override
public String getName() {
return "NPM CPE Analyzer";
} | @Test
public void testGetName() {
NpmCPEAnalyzer instance = new NpmCPEAnalyzer();
String expResult = "NPM CPE Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
} |
public int remap(int var, int size) {
if ((var & REMAP_FLAG) != 0) {
return unmask(var);
}
int offset = var - argsSize;
if (offset < 0) {
// self projection for method arguments
return var;
}
if (offset >= mapping.length) {
mapping = Arrays.copyOf(mapping, Math.max(mappi... | @Test
public void remapOutOfOrder() {
assertEquals(0, instance.remap(2, 1));
assertEquals(1, instance.remap(0, 2));
assertEquals(3, instance.remap(3, 1));
} |
public int add(Object o) {
HollowTypeMapper typeMapper = getTypeMapper(o.getClass(), null, null);
return typeMapper.write(o);
} | @Test
public void testBasic() throws IOException {
HollowObjectMapper mapper = new HollowObjectMapper(writeStateEngine);
mapper.add(new TypeA("two", 2, new TypeB((short) 20, 20000000L, 2.2f, "two".toCharArray(), new byte[]{2, 2, 2}),
Collections.<TypeC>emptySet()));
mapper.a... |
public List<RoleDO> getRoles() {
return ((Collection<?>) getSource())
.stream()
.map(RoleDO.class::cast)
.collect(Collectors.toList());
} | @Test
public void testGetRoles() {
List<RoleDO> roles = batchRoleDeletedEventTest.getRoles();
assertEquals(roles, roleDOList);
List<RoleDO> emptyRoles = batchRoleDeletedEventEmptySourceTest.getRoles();
assertEquals(emptyRoles, emptyRoleDOList);
} |
@Override
public Predicate visit(OrPredicate orPredicate, IndexRegistry indexes) {
Predicate[] originalInnerPredicates = orPredicate.predicates;
if (originalInnerPredicates == null || originalInnerPredicates.length < MINIMUM_NUMBER_OF_OR_TO_REPLACE) {
return orPredicate;
}
... | @Test
public void whenEmptyPredicate_thenReturnItself() {
OrPredicate or = new OrPredicate((Predicate[]) null);
OrPredicate result = (OrPredicate) visitor.visit(or, indexes);
assertThat(or).isEqualTo(result);
} |
@Override
public boolean filter(Message msg) {
if (msg.getSourceInputId() == null) {
return false;
}
for (final Map.Entry<String, String> field : staticFields.getOrDefault(msg.getSourceInputId(), Collections.emptyList())) {
if (!msg.hasField(field.getKey())) {
... | @Test
@SuppressForbidden("Executors#newSingleThreadExecutor() is okay for tests")
public void testFilter() throws Exception {
Message msg = messageFactory.createMessage("hello", "junit", Tools.nowUTC());
msg.setSourceInputId("someid");
when(input.getId()).thenReturn("someid");
w... |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testNotNaN() {
Evaluator evaluator = new Evaluator(STRUCT, notNaN("y"));
assertThat(evaluator.eval(TestHelpers.Row.of(1, Double.NaN, 3))).as("NaN is NaN").isFalse();
assertThat(evaluator.eval(TestHelpers.Row.of(1, 2.0, 3))).as("2 is not NaN").isTrue();
Evaluator structEvaluator = ne... |
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SAExposureData that = (SAExposureData) o;
return exposureConfig.equals(that.exposureConfig) && properties.toString().equals(that.... | @Test
public void testEquals() {
} |
@Override
public long findRegion(int subpartition, int bufferIndex, boolean loadToCache) {
// first of all, find the region from current writing region group.
RegionGroup regionGroup = currentRegionGroup[subpartition];
if (regionGroup != null) {
long regionOffset =
... | @Test
void testFindNonExistentRegion() throws Exception {
CompletableFuture<Void> cachedRegionFuture = new CompletableFuture<>();
try (FileDataIndexSpilledRegionManager<TestingFileDataIndexRegion> spilledRegionManager =
createSpilledRegionManager(
(ignore1, ig... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testRelativeOffsetAssignmentCompressedV1() {
long now = System.currentTimeMillis();
Compression compression = Compression.gzip().build();
MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V1, now, compression);
long offset = 1234567;
checkOffset... |
public int compare(Object o1, Object o2, Schema s) {
return compare(o1, o2, s, false);
} | @Test
void compare() {
// Prepare a schema for testing.
Field integerField = new Field("test", Schema.create(Type.INT), null, null);
List<Field> fields = new ArrayList<>();
fields.add(integerField);
Schema record = Schema.createRecord("test", null, null, false);
record.setFields(fields);
... |
@Override
public List<RedisClientInfo> getClientList(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
List<String> list = syncFuture(f);
return CONVERTER.convert(l... | @Test
public void testGetClientList() {
RedisClusterNode master = getFirstMaster();
List<RedisClientInfo> list = connection.getClientList(master);
assertThat(list.size()).isGreaterThan(10);
} |
public NonClosedTracking<RAW, BASE> trackNonClosed(Input<RAW> rawInput, Input<BASE> baseInput) {
NonClosedTracking<RAW, BASE> tracking = NonClosedTracking.of(rawInput, baseInput);
// 1. match by rule, line, line hash and message
match(tracking, LineAndLineHashAndMessage::new);
// 2. match issues with ... | @Test
public void similar_issues_except_rule_do_not_match() {
FakeInput baseInput = new FakeInput("H1");
baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("H1");
Issue raw = rawInput.createIssueOnLine(1, RULE_UNUSED_LOCAL_VARIABLE, "msg");
Tracking<Issu... |
@Override
public Serde<List<?>> getSerde(
final PersistenceSchema schema,
final Map<String, String> formatProperties,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final boolean isKey) {
FormatProperties.validateProperties(name(), formatProperties... | @Test
public void shouldReturnVoidSerde() {
// When:
final Serde<List<?>> serde = format.getSerde(schema, formatProps, ksqlConfig, srClientFactory, false);
// Then:
assertThat(serde, instanceOf(KsqlVoidSerde.class));
} |
@Override
public KvMetadata resolveMetadata(
boolean isKey,
List<MappingField> resolvedFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void test_resolveMetadata(boolean key, String prefix) {
KvMetadata metadata = INSTANCE.resolveMetadata(
key,
asList(
field("boolean", QueryDataType.BOOLEAN, pref... |
public MyNewIssuesNotification newMyNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new MyNewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid));
} | @Test
public void newMyNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_returns_name_and_language_from_RuleRepository() {
RuleKey rulekey1 = RuleKey.of("foo", "bar");
RuleKey rulekey2 = RuleKey.of("foo", "donut");
RuleKey rulekey3 = RuleKey.of("no", "language");
DumbRule rule1 = ruleRe... |
public AStarBidirection setApproximation(WeightApproximator approx) {
weightApprox = new BalancedWeightApproximator(approx);
return this;
} | @Test
void infeasibleApproximator_noException() {
// An infeasible approximator means that the weight of the entries polled from the priority queue does not
// increase monotonically. Here we deliberately choose the approximations and edge distances such that the fwd
// search first explores... |
@Override
public ExecutionResult toExecutionResult(String responseBody) {
ExecutionResult executionResult = new ExecutionResult();
ArrayList<String> exceptions = new ArrayList<>();
try {
Map result = (Map) GSON.fromJson(responseBody, Object.class);
if (!(result.contai... | @Test
public void shouldConstructExecutionResultFromSuccessfulExecutionResponse() {
GoPluginApiResponse response = mock(GoPluginApiResponse.class);
when(response.responseBody()).thenReturn("{\"success\":true,\"message\":\"message1\"}");
ExecutionResult result = new JsonBasedTaskExtensionHan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.