focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void getMyDefaultAdministratorRights() {
bot.execute(new SetMyDefaultAdministratorRights()
.forChannels(false)
.rights(new ChatAdministratorRights()
.canManageChat(false)
.canDeleteMessages(false)
... |
public static Collection<MdbValidityStatus> assertEjbClassValidity(final ClassInfo mdbClass) {
Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length);
final String className = mdbClass.name().toString();
verifyModifiers(className, mdbClass.flags... | @Test
public void mdbWithPrivateOnMessageMethod() {
assertTrue(assertEjbClassValidity(buildClassInfoForClass(InvalidMdbOnMessageCantBePrivate.class.getName())).contains(
MdbValidityStatus.MDB_ON_MESSAGE_METHOD_CANT_BE_PRIVATE));
} |
public void validate(List<String> values, String type, List<String> options) {
TypeValidation typeValidation = findByKey(type);
for (String value : values) {
typeValidation.validate(value, options);
}
} | @Test
public void validate() {
TypeValidation fakeTypeValidation = mock(TypeValidation.class);
when(fakeTypeValidation.key()).thenReturn("Fake");
TypeValidations typeValidations = new TypeValidations(newArrayList(fakeTypeValidation));
typeValidations.validate("10", "Fake", newArrayList("a"));
ve... |
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{networkId}/devices")
public Response getVirtualDevices(@PathParam("networkId") long networkId) {
NetworkId nid = NetworkId.networkId(networkId);
Set<VirtualDevice> vdevs = vnetService.getVirtualDevices(nid);
return ok(encodeArray(Vir... | @Test
public void testGetVirtualDevicesEmptyArray() {
NetworkId networkId = networkId4;
expect(mockVnetService.getVirtualDevices(networkId)).andReturn(ImmutableSet.of()).anyTimes();
replay(mockVnetService);
WebTarget wt = target();
String location = "vnets/" + networkId.toSt... |
@Override
public BeamSqlTable buildBeamSqlTable(Table table) {
Schema schema = table.getSchema();
ObjectNode properties = table.getProperties();
Optional<ParsedLocation> parsedLocation = Optional.empty();
if (!Strings.isNullOrEmpty(table.getLocation())) {
parsedLocation = Optional.of(parseLocat... | @Test
public void testBuildWithExtraServers() {
Table table =
mockTableWithExtraServers("hello", ImmutableList.of("localhost:1111", "localhost:2222"));
BeamSqlTable sqlTable = provider.buildBeamSqlTable(table);
assertNotNull(sqlTable);
assertTrue(sqlTable instanceof BeamKafkaCSVTable);
B... |
public static Optional<Object> invokeMethod(Object target, String methodName, Class<?>[] paramsType,
Object[] params) {
if (methodName == null || target == null) {
return Optional.empty();
}
final Optional<Method> method = findMethod(target.getClass(), methodName, paramsT... | @Test
public void invokeMethod() {
final TestReflect testReflect = new TestReflect();
String name = "Mike";
final Optional<Object> hasParams = ReflectUtils
.invokeMethod(testReflect, "hasParams", new Class[]{String.class}, new Object[]{name});
Assert.assertTrue(hasPar... |
static <T extends CompoundPredicate> T flattenCompound(Predicate predicateLeft, Predicate predicateRight, Class<T> klass) {
// The following could have been achieved with {@link com.hazelcast.query.impl.predicates.FlatteningVisitor},
// however since we only care for 2-argument flattening, we can avoid ... | @Test
public void testOr_whenNoPredicateOr() {
Predicate<Object, Object> predicate1 = Predicates.alwaysTrue();
Predicate<Object, Object> predicate2 = Predicates.alwaysTrue();
OrPredicate concatenatedOr = SqlPredicate.flattenCompound(predicate1, predicate2, OrPredicate.class);
assertE... |
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
} | @Test
void isInfoEnabled() {
jobRunrDashboardLogger.isInfoEnabled();
verify(slfLogger).isInfoEnabled();
} |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final EnumSet<OpenMode> flags;
if(status.isAppend()) {
if(status.isExists()) {
// No... | @Test(expected = NotfoundException.class)
public void testWriteNotFound() throws Exception {
final Path test = new Path(new SFTPHomeDirectoryService(session).find().getAbsolute() + "/nosuchdirectory/" + UUID.randomUUID(), EnumSet.of(Path.Type.file));
new SFTPWriteFeature(session).write(test, new Tra... |
public ResT receive(long timeoutMs) throws IOException {
if (mCompleted) {
return null;
}
if (mCanceled) {
throw new CancelledException(formatErrorMessage("Stream is already canceled."));
}
long startMs = System.currentTimeMillis();
while (true) {
long waitedForMs = System.cur... | @Test
public void receiveMoreThanBufferSize() throws Exception {
WriteResponse[] responses = Stream.generate(() -> WriteResponse.newBuilder().build())
.limit(BUFFER_SIZE * 2).toArray(WriteResponse[]::new);
EXECUTOR.submit(() -> {
for (WriteResponse response : responses) {
mResponseObser... |
@Override
public <T extends Response> CompletableFuture<T> sendAsync(
Request request, Class<T> responseType) {
CompletableFuture<T> result = new CompletableFuture<>();
long requestId = request.getId();
requestForId.put(requestId, new WebSocketRequest<>(result, responseType));
... | @Test
public void testReceiveError() throws Exception {
CompletableFuture<Web3ClientVersion> reply =
service.sendAsync(request, Web3ClientVersion.class);
sendErrorReply();
assertTrue(reply.isDone());
Web3ClientVersion version = reply.get();
assertTrue(version... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean paramCheckEnabled = ServerParamCheckConfig.getInstance().isParamCheckEnabled();
if (!paramCheckEnabled) {
chain.doFilter(request,... | @Test
void testDoFilterMethodNotFound() throws IOException, ServletException {
when(methodsCache.getMethod(request)).thenReturn(null);
filter.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
} |
@Override
public long size() {
return mSize.longValue();
} | @Test
public void longRunningIterAndRestore() throws Exception {
// Manually set this flag, otherwise an exception will be thrown when the exclusive lock
// is forced.
Configuration.set(PropertyKey.TEST_MODE, false);
prepareBlocks(FILE_NUMBER);
// Prepare a checkpoint file
File checkpointFile... |
public static FilterPredicate rewrite(FilterPredicate pred) {
Objects.requireNonNull(pred, "pred cannot be null");
return pred.accept(INSTANCE);
} | @Test
public void testBaseCases() {
UserDefined<Integer, DummyUdp> ud = userDefined(intColumn, DummyUdp.class);
assertNoOp(eq(intColumn, 17));
assertNoOp(notEq(intColumn, 17));
assertNoOp(lt(intColumn, 17));
assertNoOp(ltEq(intColumn, 17));
assertNoOp(gt(intColumn, 17));
assertNoOp(gtEq(i... |
@VisibleForTesting
public static void validateIngestionConfig(TableConfig tableConfig, @Nullable Schema schema) {
IngestionConfig ingestionConfig = tableConfig.getIngestionConfig();
if (ingestionConfig != null) {
String tableNameWithType = tableConfig.getTableName();
// Batch
if (ingestion... | @Test
public void ingestionConfigForDimensionTableTest() {
Map<String, String> batchConfigMap = new HashMap<>();
batchConfigMap.put(BatchConfigProperties.INPUT_DIR_URI, "s3://foo");
batchConfigMap.put(BatchConfigProperties.OUTPUT_DIR_URI, "gs://bar");
batchConfigMap.put(BatchConfigProperties.INPUT_FS_... |
@Override
public void onBlocked(BlockException ex, Context context, ResourceWrapper resourceWrapper, DefaultNode param,
int count, Object... args) {
for (MetricExtension m : MetricExtensionProvider.getMetricExtensions()) {
if (m instanceof AdvancedMetricExtension) {
... | @Test
public void onBlocked() throws Exception {
FakeMetricExtension extension = new FakeMetricExtension();
FakeAdvancedMetricExtension advancedExtension = new FakeAdvancedMetricExtension();
MetricExtensionProvider.addMetricExtension(extension);
MetricExtensionProvider.addMetricExten... |
@Override
public void handle(final RoutingContext routingContext) {
if (routingContext.request().isSSL()) {
final String indicatedServerName = routingContext.request().connection()
.indicatedServerName();
final String requestHost = routingContext.request().host();
if (indicatedServerNa... | @Test
public void shouldNotReturnMisdirectedResponseIfMatchHostPort() {
// Given:
when(serverRequest.host()).thenReturn("localhost:80");
when(httpConnection.indicatedServerName()).thenReturn("localhost");
// When:
sniHandler.handle(routingContext);
// Then:
verify(routingContext, never()... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
try {
final IRODSFileSystemAO fs = session.getClient();
final IRODSFile s = fs.getIRO... | @Test
public void testMoveDirectory() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
this.getClass().getResourceAsStream("/iRODS (iPlant C... |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(ap... | @Test
public void status_YELLOW_when_two_GREEN_application_node_and_any_number_of_other_is_RED_or_GREEN() {
Set<NodeHealth> nodeHealths = of(
// at least 1 RED
of(appNodeHealth(RED)),
// 0 to 10 RED/GREEN
randomNumberOfAppNodeHealthOfAnyStatus(GREEN, RED),
// 2 GREEN
nodeHealth... |
static String getModel(String fileName) {
return FileNameUtils.getSuffix(fileName).replace(FINAL_SUFFIX, "");
} | @Test
void getModel() {
String fileName = "file_name.model_json";
String expected = "model";
String source = fileName;
assertThat(IndexFile.getModel(source)).isEqualTo(expected);
source = File.separator + "dir" + File.separator + fileName;
assertThat(IndexFile.getMode... |
@Override
@Nonnull
public List<Sdk> selectSdks(Configuration configuration, UsesSdk usesSdk) {
Config config = configuration.get(Config.class);
Set<Sdk> sdks = new TreeSet<>(configuredSdks(config, usesSdk));
if (enabledSdks != null) {
sdks = Sets.intersection(sdks, enabledSdks);
}
return L... | @Test
public void withAllSdksConfigAndNoMinSdkVersion_shouldUseFullSdkRangeFromAndroidManifest()
throws Exception {
when(usesSdk.getTargetSdkVersion()).thenReturn(22);
when(usesSdk.getMinSdkVersion()).thenReturn(1);
when(usesSdk.getMaxSdkVersion()).thenReturn(22);
assertThat(
sdkPick... |
public RegisterTypeCommand create(final RegisterType statement) {
final String name = statement.getName();
final boolean ifNotExists = statement.getIfNotExists();
final SqlType type = statement.getType().getSqlType();
if (!ifNotExists && metaStore.resolveType(name).isPresent()) {
throw new KsqlEx... | @Test
public void shouldCreateCommandForRegisterTypeWhenIfNotExitsSet() {
// Given:
final RegisterType ddlStatement = new RegisterType(
Optional.empty(),
NOT_EXISTING_TYPE,
new Type(SqlStruct.builder().field("foo", SqlPrimitiveType.of(SqlBaseType.STRING)).build()),
true
);
... |
@Override
public void upgrade() {
MongoCollection<Document> roles = mongoDatabase.getCollection("roles");
Document viewsUserRole = roles.findOneAndDelete(eq("name", "Views User"));
if (viewsUserRole != null) {
removeRoleFromUsers(viewsUserRole);
}
} | @Test
public void doesntFailIfOldPermissionsNotPresent() {
Document role = insertRole("Dancing Monkey");
Document user = insertUserWithRoles(role);
migration.upgrade();
assertThat(rolesCollection.find()).containsOnly(role);
assertThat(usersCollection.find()).containsOnly(us... |
@Override
public void clear(long fromIndex, long toIndex) {
get(clearAsync(fromIndex, toIndex));
} | @Test
public void testClear() {
RBitSet bs = redisson.getBitSet("testbitset");
bs.set(0, 8);
bs.clear(0, 3);
assertThat(bs.toString()).isEqualTo("{3, 4, 5, 6, 7}");
} |
public void resetOffsetsFromResetPlan(final Consumer<byte[], byte[]> client,
final Set<TopicPartition> inputTopicPartitions,
final Map<TopicPartition, Long> topicPartitionsAndOffset) {
final Map<TopicPartition, Long> endOffsets ... | @Test
public void testResetUsingPlanWhenBeforeBeginningOffset() {
final Map<TopicPartition, Long> endOffsets = new HashMap<>();
endOffsets.put(topicPartition, 4L);
consumer.updateEndOffsets(endOffsets);
final Map<TopicPartition, Long> beginningOffsets = new HashMap<>();
begi... |
public WriteLock writeLock() {
return writeMutex;
} | @Test
public void testSetNodeData() throws Exception {
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
try {
client.start();
final byte[] nodeData = new byte[] {1, 2, 3, 4};
InterProcessReadWriteLock ... |
@Override
public PayloadSerializer getSerializer(Schema schema, Map<String, Object> tableParams) {
Class<? extends Message> protoClass = getClass(tableParams);
inferAndVerifySchema(protoClass, schema);
SimpleFunction<byte[], Row> toRowFn = ProtoMessageSchema.getProtoBytesToRowFn(protoClass);
return Pa... | @Test
public void invalidArgs() {
assertThrows(
IllegalArgumentException.class,
() -> provider.getSerializer(SHUFFLED_SCHEMA, ImmutableMap.of()));
assertThrows(
IllegalArgumentException.class,
() -> provider.getSerializer(SHUFFLED_SCHEMA, ImmutableMap.of("protoClass", "")));
... |
@VisibleForTesting
GenericData getDataModel() {
return dataModelSupplier.get();
} | @Test
void getDataModel() {
assertThat(
((AvroParquetRecordFormat) AvroParquetReaders.forGenericRecord(schema))
.getDataModel()
.getClass())
.isEqualTo(GenericData.class);
assertThat(
... |
public static void saveContractInfo(Contract contract) {
if (!CONTRACT_MAP.containsKey(contract.getServiceKey())) {
CONTRACT_MAP.putIfAbsent(contract.getServiceKey(), contract);
} else if (Objects.equals(contract.getServiceType(), ServiceType.DUBBO.getType())) {
Contract oldContr... | @Test
public void saveContractInfo() {
Contract contract = new Contract();
contract.setServiceKey(CollectorCacheTest.class.getName());
contract.setServiceType(ServiceType.DUBBO.getType());
contract.setInterfaceName(CollectorCacheTest.class.getName());
List<MethodInfo> methodI... |
public <T> List<T> apply(T[] a) {
return apply(Arrays.asList(a));
} | @Test
public void normalRange() {
Range r = new Range(2,4);
assertEquals("[c, d]", toS(r.apply(array)));
assertEquals("[c, d]", toS(r.apply(list)));
assertEquals("[c, d]", toS(r.apply(set)));
} |
private static void nativeMemory(XmlGenerator gen, NativeMemoryConfig nativeMemory) {
gen.open("native-memory", "enabled", nativeMemory.isEnabled(),
"allocator-type", nativeMemory.getAllocatorType())
.node("capacity", null, "value", nativeMemory.getCapacity().getValue(),
... | @Test
public void nativeMemory() {
NativeMemoryConfig expected = new NativeMemoryConfig();
expected.setEnabled(true)
.setAllocatorType(MemoryAllocatorType.STANDARD)
.setMetadataSpacePercentage(70)
.setMinBlockSize(randomInt())
.setPageS... |
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception {
return newGetter(object, parent, modifier, field.getType(), field::get,
(t, et) -> new FieldGetter(parent, field, modifier, t, et));
} | @Test
public void newFieldGetter_whenExtractingFromNull_Array_AndReducerSuffixInNotEmpty_thenReturnNullGetter()
throws Exception {
OuterObject object = OuterObject.nullInner("name");
Getter getter = GetterFactory.newFieldGetter(object, null, innersArrayField, "[any]");
Class<?> ... |
protected static SimpleDateFormat getLog4j2Appender() {
Optional<Appender> log4j2xmlAppender =
configuration.getAppenders().values().stream()
.filter( a -> a.getName().equalsIgnoreCase( log4J2Appender ) ).findFirst();
if ( log4j2xmlAppender.isPresent() ) {
ArrayList<String> matchesArray = ne... | @Test
public void testGetLog4j2UsingAppender12() {
// Test with no matching appender name and set Default Pattern value "yyyy/MM/dd HH:mm:ss"
KettleLogLayout.log4J2Appender = "pdi-execution-appender-test-twelve";
Assert.assertEquals( "yyyy/MM/dd HH:mm:ss",
KettleLogLayout.getLog4j2Appender().toPatte... |
@Override
public Optional<ScmInfo> getScmInfo(Component component) {
requireNonNull(component, "Component cannot be null");
if (component.getType() != Component.Type.FILE) {
return Optional.empty();
}
return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent);
} | @Test
public void read_from_DB_if_no_report_and_file_unchanged_and_copyFromPrevious_is_true() {
createDbScmInfoWithOneLine();
when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true);
addFileSourceInReport(1);
addCopyFromPrevious();
ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get();
a... |
@Override
public ConsumerBuilder<T> topic(String... topicNames) {
checkArgument(topicNames != null && topicNames.length > 0,
"Passed in topicNames should not be null or empty.");
return topics(Arrays.stream(topicNames).collect(Collectors.toList()));
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testConsumerBuilderImplWhenTopicNamesVarargsIsNull() {
consumerBuilderImpl.topic(null);
} |
public Map<String, ServiceInfo> getServiceInfoMap() {
return serviceInfoMap;
} | @Test
void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException {
assertEquals(0, holder.getServiceInfoMap().size());
Field fieldNotifierEventScope = ServiceInfoHolder.class.getDeclaredField("notifierEventScope");
fieldNotifierEventScope.setAccessible(true);
as... |
@Operation(summary = "Read the answers of the 3 apdus and read the pip/pp to send to digid x")
@PostMapping(value = { Constants.URL_OLD_RDW_POLYMORPHICDATA,
Constants.URL_RDW_POLYMORPHICDATA }, consumes = "application/json", produces = "application/json")
public PolyDataResponse getPolymorphicDataRe... | @Test
public void getPolymorphicDataRestServiceTest() {
PolyDataResponse expectedResponse = new PolyDataResponse();
when(rdwServiceMock.getPolymorphicDataRestService(any(PolyDataRequest.class), anyString())).thenReturn(expectedResponse);
PolyDataResponse actualResponse = rdwController.getPo... |
String upload(File report) {
LOG.debug("Upload report");
long startTime = System.currentTimeMillis();
Part filePart = new Part(MediaTypes.ZIP, report);
PostRequest post = new PostRequest("api/ce/submit")
.setMediaType(MediaTypes.PROTOBUF)
.setParam("projectKey", moduleHierarchy.root().key())... | @Test
public void test_send_branches_characteristics() throws Exception {
String branchName = "feature";
when(branchConfiguration.branchName()).thenReturn(branchName);
when(branchConfiguration.branchType()).thenReturn(BRANCH);
WsResponse response = mock(WsResponse.class);
PipedOutputStream out =... |
public void lockClusterState(ClusterStateChange stateChange, Address initiator, UUID txnId, long leaseTime,
int memberListVersion, long partitionStateStamp) {
Preconditions.checkNotNull(stateChange);
clusterServiceLock.lock();
try {
if (!node.getNodeE... | @Test(expected = IllegalArgumentException.class)
public void test_lockClusterState_nonPositiveLeaseTime() throws Exception {
Address initiator = newAddress();
clusterStateManager.lockClusterState(ClusterStateChange.from(FROZEN), initiator, TXN, -1000, MEMBERLIST_VERSION,
PARTITION_ST... |
@Override
public BackgroundException map(final ApiException failure) {
final StringBuilder buffer = new StringBuilder();
if(StringUtils.isNotBlank(failure.getMessage())) {
for(String s : StringUtils.split(failure.getMessage(), ",")) {
this.append(buffer, LocaleFactory.loc... | @Test
public void testParseError() {
assertEquals("LIMIT_MAX_FOLDER_COUNT. LIMIT_MAX_RESOURCE_COUNT. Please contact your web hosting service provider for assistance.",
new EueExceptionMappingService().map(new ApiException("LIMIT_MAX_FOLDER_COUNT,LIMIT_MAX_RESOURCE_COUNT", null, 500, null)).g... |
@Override
public void execute(final ConnectionSession connectionSession) {
String name = showStatement.getName().orElse("").toLowerCase(Locale.ROOT);
if ("ALL".equalsIgnoreCase(name)) {
executeShowAll(connectionSession);
return;
}
queryResultMetaData = new Raw... | @Test
void assertExecuteShowAll() throws SQLException {
ConnectionSession connectionSession = mock(ConnectionSession.class);
PostgreSQLShowVariableExecutor executor = new PostgreSQLShowVariableExecutor(new PostgreSQLShowStatement("ALL"));
executor.execute(connectionSession);
QueryRes... |
public TimelineWriteResponse putEntities(TimelineEntities entities,
UserGroupInformation callerUgi) throws IOException {
LOG.debug("putEntities(entities={}, callerUgi={})", entities, callerUgi);
TimelineWriteResponse response = null;
try {
boolean isStorageUp = checkRetryWithSleep();
if (... | @Test
void testPutEntity() throws IOException {
TimelineWriter writer = mock(TimelineWriter.class);
TimelineHealth timelineHealth = new TimelineHealth(TimelineHealth.
TimelineHealthStatus.RUNNING, "");
when(writer.getHealthStatus()).thenReturn(timelineHealth);
Configuration conf = new Configu... |
@Override
@Deprecated
public void process(final org.apache.kafka.streams.processor.ProcessorSupplier<? super K, ? super V> processorSupplier,
final String... stateStoreNames) {
process(processorSupplier, Named.as(builder.newProcessorName(PROCESSOR_NAME)), stateStoreNames);
} | @Test
public void shouldNotAllowNullStoreNamesOnProcessWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.process(processorSupplier, Named.as("processor"), (String[]) null));
assertThat(exception.getMessage(), equal... |
public static void verifyPrecondition(boolean assertionResult, String errorMessage) {
if (!assertionResult) {
throw new RuntimeException(errorMessage);
}
} | @Test
public void testVerifyPreconditionFailure() {
assertThrows(RuntimeException.class, () -> verifyPrecondition(false, ""));
} |
public static DynamicMessage messageFromTableRow(
SchemaInformation schemaInformation,
Descriptor descriptor,
TableRow tableRow,
boolean ignoreUnknownValues,
boolean allowMissingRequiredFields,
final @Nullable TableRow unknownFields,
@Nullable String changeType,
long chan... | @Test
public void testMessageFromTableRow() throws Exception {
TableRow tableRow =
new TableRow()
.set("nestedValue1", BASE_TABLE_ROW)
.set("nestedValue2", BASE_TABLE_ROW)
.set("nestedValueNoF1", BASE_TABLE_ROW_NO_F)
.set("nestedValueNoF2", BASE_TABLE_ROW_NO... |
public void replayAddKey(EncryptionKeyPB keyPB) {
EncryptionKey key = create(keyPB);
keysLock.writeLock().lock();
try {
idToKey.put(key.id, key);
} finally {
keysLock.writeLock().unlock();
}
} | @Test
public void testReplayAddKey() {
KeyMgr keyMgr = new KeyMgr();
EncryptionKeyPB pb = new EncryptionKeyPB();
pb.id = 1L;
pb.algorithm = EncryptionAlgorithmPB.AES_128;
pb.encryptedKey = new byte[16];
pb.type = EncryptionKeyTypePB.NORMAL_KEY;
pb.createTime =... |
@Override
public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException {
final SMBSession.DiskShareWrapper share = session.openShare(folder);
try {
share.get().mkdir(new SMBPathContainerService(session).getKey(folder));
}
catch(SMBRuntimeEx... | @Test
public void testMakeDirectory() throws Exception {
final Path test = new SMBDirectoryFeature(session).mkdir(
new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus());
assertTru... |
public static Result find(List<Path> files, Consumer<LogEvent> logger) {
List<String> mainClasses = new ArrayList<>();
for (Path file : files) {
// Makes sure classFile is valid.
if (!Files.exists(file)) {
logger.accept(LogEvent.debug("MainClassFinder: " + file + " does not exist; ignoring")... | @Test
public void testFindMainClass_innerClasses() throws URISyntaxException, IOException {
Path rootDirectory =
Paths.get(Resources.getResource("core/class-finder-tests/inner-classes").toURI());
MainClassFinder.Result mainClassFinderResult =
MainClassFinder.find(new DirectoryWalker(rootDirect... |
public static SonarRuntime forSonarQube(Version apiVersion, SonarQubeSide side, SonarEdition edition) {
return new SonarRuntimeImpl(apiVersion, SonarProduct.SONARQUBE, side, edition);
} | @Test(expected = IllegalArgumentException.class)
public void sonarqube_requires_side() {
SonarRuntimeImpl.forSonarQube(A_VERSION, null, null);
} |
public static TimeLimiterMetrics ofTimeLimiter(TimeLimiter timeLimiter) {
return new TimeLimiterMetrics(List.of(timeLimiter));
} | @Test
public void shouldRecordErrors() {
TimeLimiter timeLimiter = TimeLimiter.of(TimeLimiterConfig.ofDefaults());
metricRegistry.registerAll(TimeLimiterMetrics.ofTimeLimiter(timeLimiter));
timeLimiter.onError(new RuntimeException());
timeLimiter.onError(new RuntimeException());
... |
@Override
public ThreadPoolBulkheadConfig getBulkheadConfig() {
return config;
} | @Test
public void testCustomSettings() {
assertThat(bulkhead.getBulkheadConfig().getMaxThreadPoolSize()).isEqualTo(2);
assertThat(bulkhead.getBulkheadConfig().getQueueCapacity()).isEqualTo(10);
assertThat(bulkhead.getBulkheadConfig().getCoreThreadPoolSize()).isEqualTo(1);
assertThat(... |
public int numBufferedStreams() {
return pendingStreams.size();
} | @Test
public void receivingGoAwayFailsBufferedStreams() throws Http2Exception {
encoder.writeSettingsAck(ctx, newPromise());
setMaxConcurrentStreams(5);
int streamId = 3;
List<ChannelFuture> futures = new ArrayList<ChannelFuture>();
for (int i = 0; i < 9; i++) {
... |
@VisibleForTesting
int log2Floor(long n) {
checkArgument(n >= 0);
return n == 0 ? -1 : LongMath.log2(n, RoundingMode.FLOOR);
} | @Test
public void testLog2Floor_zero() {
OrderedCode orderedCode = new OrderedCode();
assertEquals(-1, orderedCode.log2Floor(0));
} |
public void endTransactionOneway(
final String addr,
final EndTransactionRequestHeader requestHeader,
final String remark,
final long timeoutMillis
) throws RemotingException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.EN... | @Test
public void testEndTransactionOneway() throws RemotingException, InterruptedException {
mockInvokeSync();
EndTransactionRequestHeader requestHeader = mock(EndTransactionRequestHeader.class);
mqClientAPI.endTransactionOneway(defaultBrokerAddr, requestHeader, "", defaultTimeout);
} |
public Schema mergeTables(
Map<FeatureOption, MergingStrategy> mergingStrategies,
Schema sourceSchema,
List<SqlNode> derivedColumns,
List<SqlWatermark> derivedWatermarkSpecs,
SqlTableConstraint derivedPrimaryKey) {
SchemaBuilder schemaBuilder =
... | @Test
void mergeOverwritingComputedColumnWithMetadataColumn() {
Schema sourceSchema =
Schema.newBuilder()
.column("one", DataTypes.INT())
.columnByExpression("two", "one + 3")
.build();
List<SqlNode> derivedColu... |
public static List<ACL> parseACLs(String aclString) throws
BadAclFormatException {
List<ACL> acl = Lists.newArrayList();
if (aclString == null) {
return acl;
}
List<String> aclComps = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults()
.split(aclString)... | @Test
public void testEmptyACL() {
List<ACL> result = ZKUtil.parseACLs("");
assertTrue(result.isEmpty());
} |
@Override
public void debug(String msg) {
logger.debug(msg);
} | @Test
void testDebug() {
jobRunrDashboardLogger.debug("Debug");
verify(slfLogger).debug("Debug");
} |
public static JavaBeanDescriptor serialize(Object obj) {
return serialize(obj, JavaBeanAccessor.FIELD);
} | @Test
void testSerialize_Primitive_NUll() {
JavaBeanDescriptor descriptor;
descriptor = JavaBeanSerializeUtil.serialize(null);
Assertions.assertNull(descriptor);
} |
@Override
public void doHealthCheck() {
try {
initIfNecessary();
for (Service each : client.getAllPublishedService()) {
if (switchDomain.isHealthCheckEnabled(each.getGroupedServiceName())) {
InstancePublishInfo instancePublishInfo = client.getInsta... | @Test
void testDoHealthCheck() {
when(ipPortBasedClient.getAllPublishedService()).thenReturn(returnService());
healthCheckTaskV2.setCheckRtWorst(1);
healthCheckTaskV2.setCheckRtLastLast(1);
assertEquals(1, healthCheckTaskV2.getCheckRtWorst());
assertEquals(1, healthC... |
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
public static LocalCommands open(
final KsqlEngine ksqlEngine,
final File directory
) {
if (!directory.exists()) {
if (!directory.mkdirs()) {
throw new KsqlServerException("Couldn't create the local commands directory: "
... | @Test
public void shouldThrowWhenCommandLocationIsNotWritable() throws IOException {
// Given
final File file = commandsDir.newFolder();
Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("r-x------"));
// When
final Exception e = assertThrows(
KsqlServerExceptio... |
@Override
public List<String> splitAndEvaluate() {
return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : split(inlineExpression);
} | @Test
void assertEvaluateForLong() {
StringBuilder expression = new StringBuilder();
for (int i = 0; i < 1024; i++) {
expression.append("ds_");
expression.append(i / 64);
expression.append(".t_user_");
expression.append(i);
if (i != 1023) {... |
public static <P> String getMethodName(Func1<P, ?> func) {
return resolve(func).getImplMethodName();
} | @Test
public void getMethodNameTest() {
final String methodName = LambdaUtil.getMethodName(MyTeacher::getAge);
assertEquals("getAge", methodName);
} |
@HighFrequencyInvocation
public Optional<ShardingSphereUser> findUser(final Grantee grantee) {
return configuration.getUsers().stream().filter(each -> each.getGrantee().accept(grantee)).findFirst();
} | @Test
void assertFindUser() {
AuthorityRule rule = createAuthorityRule();
Optional<ShardingSphereUser> actual = rule.findUser(new Grantee("admin", "localhost"));
assertTrue(actual.isPresent());
assertThat(actual.get().getGrantee().getUsername(), is("admin"));
assertThat(actua... |
@Override
public URI getCallBackUri() {
return callBackUri;
} | @Test
public void testGetCallBackUri() {
assertEquals("callback", hystrixCommand.getCallBackUri().getHost());
} |
@Override
public int size() {
return count(members, selector);
} | @Test
public void testSizeWhenAllSelected() {
MemberSelectingCollection<MemberImpl> collection = new MemberSelectingCollection<>(members,
NO_OP_MEMBER_SELECTOR);
assertEquals(3, collection.size());
} |
public DataSource createDataSourceProxy(DataSource dataSource) {
return createDataSourceProxy(null, dataSource);
} | @Test
public void testCreateDataSourceProxy() throws Exception {
// on fait le ménage au cas où TestMonitoringSpringInterceptor ait été exécuté juste avant
cleanUp();
assertTrue("getBasicDataSourceProperties0",
JdbcWrapper.getBasicDataSourceProperties().isEmpty());
assertEquals("getMaxConnectionCount0", -... |
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) {
SourceConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!ex... | @Test
public void testMergeDifferentResources() {
SourceConfig sourceConfig = createSourceConfig();
Resources resources = new Resources();
resources.setCpu(0.3);
resources.setRam(1232L);
resources.setDisk(123456L);
SourceConfig newSourceConfig = createUpdatedSourceCon... |
@Override
public LogicalSchema getSchema() {
return schema;
} | @Test
public void shouldHaveFullyQualifiedJoinSchemaWithSyntheticKey() {
// Given:
when(joinKey.resolveKeyName(any(), any())).thenReturn(SYNTH_KEY);
// When:
final JoinNode joinNode = new JoinNode(nodeId, OUTER, joinKey, true, left,
right, empty(),"KAFKA");
// When:
assertThat(... |
@Override
public String convert(final ReadwriteSplittingRuleConfiguration ruleConfig) {
if (ruleConfig.getDataSourceGroups().isEmpty()) {
return "";
}
StringBuilder result = new StringBuilder(ReadwriteSplittingDistSQLConstants.CREATE_READWRITE_SPLITTING_RULE);
Iterator<Re... | @Test
void assertConvert() {
ReadwriteSplittingDataSourceGroupRuleConfiguration dataSourceGroupConfig =
new ReadwriteSplittingDataSourceGroupRuleConfiguration("readwrite_ds", "ds_primary", Arrays.asList("ds_slave_0", "ds_slave_1"), "test");
ReadwriteSplittingRuleConfiguration readwri... |
public static AbstractPredictor getZooPredictor(DJLEndpoint endpoint)
throws ModelNotFoundException, MalformedModelException, IOException {
String applicationPath = endpoint.getApplication();
// CV
if (IMAGE_CLASSIFICATION.getPath().equals(applicationPath)) {
return new ... | @Test
void testGetZooPredictor() throws ModelNotFoundException, MalformedModelException, IOException {
// CV
assertInstanceOf(ZooImageClassificationPredictor.class,
getZooPredictor(zooEndpoint("cv/image_classification", "ai.djl.zoo:mlp:0.0.3")));
assertInstanceOf(ZooObjectDet... |
public static <T extends DatabaseTypedSPI> T getService(final Class<T> spiClass, final DatabaseType databaseType) {
return findService(spiClass, databaseType).orElseGet(() -> TypedSPILoader.getService(spiClass, null));
} | @Test
void assertGetServiceWithRegisteredDatabaseType() {
assertDoesNotThrow(() -> DatabaseTypedSPILoader.getService(DatabaseTypedSPIFixture.class, TypedSPILoader.getService(DatabaseType.class, "TRUNK")));
} |
public static final File createLocalTempFile(final File basefile,
final String prefix,
final boolean isDeleteOnExit)
throws IOException {
File tmp = File.createTempFile(prefix + basefile.getName(),
... | @Test (timeout = 30000)
public void testCreateLocalTempFile() throws IOException {
final File baseFile = new File(tmp, "base");
File tmp1 = FileUtil.createLocalTempFile(baseFile, "foo", false);
File tmp2 = FileUtil.createLocalTempFile(baseFile, "foo", true);
assertFalse(tmp1.getAbsolutePath().equals(b... |
@Override
public YamlAuthorityRuleConfiguration swapToYamlConfiguration(final AuthorityRuleConfiguration data) {
YamlAuthorityRuleConfiguration result = new YamlAuthorityRuleConfiguration();
result.setPrivilege(algorithmSwapper.swapToYamlConfiguration(data.getPrivilegeProvider()));
result.se... | @Test
void assertSwapToYamlConfiguration() {
AuthorityRuleConfiguration authorityRuleConfig = new AuthorityRuleConfiguration(Collections.emptyList(), new AlgorithmConfiguration("ALL_PERMITTED", new Properties()),
Collections.singletonMap("md5", createAlgorithmConfiguration()), "scram_sha256"... |
@Override
public CompletableFuture<Void> deleteOffloaded(long ledgerId, UUID uid,
Map<String, String> offloadDriverMetadata) {
BlobStoreLocation bsKey = getBlobStoreLocation(offloadDriverMetadata);
String readBucket = bsKey.getBucket(offloadDriverMe... | @Test
public void testDeleteOffloaded() throws Exception {
ReadHandle readHandle = buildReadHandle(DEFAULT_BLOCK_SIZE, 1);
UUID uuid = UUID.randomUUID();
BlobStoreManagedLedgerOffloader offloader = getOffloader();
// verify object exist after offload
offloader.offload(readH... |
public List<ConnectionProvider<? extends ConnectionDetails>> getProviders() {
return Collections.list( this.connectionProviders.elements() );
} | @Test
public void testGetProviders() {
addProvider();
assertEquals( 1, connectionManager.getProviders().size() );
assertEquals( TestConnectionWithBucketsProvider.SCHEME, connectionManager.getProviders().get( 0 ).getKey() );
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final String msg = new String(rawMessage.getPayload(), charset);
try (Timer.Context ignored = this.decodeTime.time()) {
final ResolvableInetSocketAddress address = rawMessage.getRemoteAddress();
f... | @Test
public void testDecodeStructuredIssue549() throws Exception {
final Message message = codec.decode(buildRawMessage(STRUCTURED_ISSUE_549));
assertNotNull(message);
assertEquals("RT_FLOW_SESSION_DENY [junos@2636.1.1.1.2.39 source-address=\"1.2.3.4\" source-port=\"56639\" destination-add... |
@Deprecated
public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) {
return prune(segments, query, new SegmentPrunerStatistics());
} | @Test
public void notEmptyValidSegmentsAreNotPruned() {
SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
IndexSegment indexSegment = mockIndexSegment(10, "col1", "col2");
SegmentPrunerStatistics stats = new SegmentPrunerStatistics();
List<IndexSegment> indexes = new ArrayLi... |
public boolean authenticate(LDAPConnection connection, String bindDn, EncryptedValue password) throws LDAPException {
checkArgument(!isNullOrEmpty(bindDn), "Binding with empty principal is forbidden.");
checkArgument(password != null, "Binding with null credentials is forbidden.");
checkArgument... | @Test
public void testAuthenticateFail() throws LDAPException {
final boolean authenticated = connector.authenticate(connection, "cn=John Doe,ou=users,dc=example,dc=com", encryptedValueService.encrypt("wrongpass"));
assertThat(authenticated).isFalse();
} |
@Override
public String getPrefix() {
return String.format("%s.%s", IRODSProtocol.class.getPackage().getName(), StringUtils.upperCase(this.getType().name()));
} | @Test
public void testGetPrefix() {
assertEquals("ch.cyberduck.core.irods.IRODS", new IRODSProtocol().getPrefix());
} |
public static MDS of(double[][] proximity) {
return of(proximity, new Properties());
} | @Test
public void test() {
System.out.println("MDS");
double[] eig = {19538377.0895, 11856555.3340};
double[][] points = {
{ 2290.274680, 1798.80293},
{ -825.382790, 546.81148},
{ 59.183341, -367.08135},
{ -82.845973, -429.91466},
... |
public static void validate(final String table, final String column, final Comparable<?> shadowValue) {
for (Class<?> each : UNSUPPORTED_TYPES) {
ShardingSpherePreconditions.checkState(!each.isAssignableFrom(shadowValue.getClass()), () -> new UnsupportedShadowColumnTypeException(table, column, each)... | @Test
void assertValidateEnumType() {
assertThrows(UnsupportedShadowColumnTypeException.class, () -> ShadowValueValidator.validate("tbl", "col", mock(Enum.class)));
} |
@Override
public Set<Long> calculateUsers(DelegateExecution execution, String param) {
Object result = FlowableUtils.getExpressionValue(execution, param);
return Convert.toSet(Long.class, result);
} | @Test
public void testCalculateUsers() {
try (MockedStatic<FlowableUtils> flowableUtilMockedStatic = mockStatic(FlowableUtils.class)) {
// 准备参数
String param = "1,2";
DelegateExecution execution = mock(DelegateExecution.class);
// mock 方法
flowableUt... |
@Override
public void isNotEqualTo(@Nullable Object expected) {
super.isNotEqualTo(expected);
} | @Test
public void isNotEqualTo_WithoutToleranceParameter_FailEquals() {
expectFailureWhenTestingThat(array(2.2d, 5.4d, POSITIVE_INFINITY, NEGATIVE_INFINITY))
.isNotEqualTo(array(2.2d, 5.4d, POSITIVE_INFINITY, NEGATIVE_INFINITY));
} |
public JetSqlRow project(Object object) {
target.setTarget(object, null);
return ExpressionUtil.projection(predicate, projection, this, evalContext);
} | @Test
@SuppressWarnings("unchecked")
public void when_filteredByPredicate_then_returnsNull() {
RowProjector projector = new RowProjector(
new String[]{"target"},
new QueryDataType[]{INT},
new IdentityTarget(),
(Expression<Boolean>) Constant... |
@Override
public Object deserialize(Writable writable) {
return ((Container<?>) writable).get();
} | @Test
public void testDeserialize() {
HiveIcebergSerDe serDe = new HiveIcebergSerDe();
Record record = RandomGenericData.generate(SCHEMA, 1, 0).get(0);
Container<Record> container = new Container<>();
container.set(record);
assertThat(serDe.deserialize(container)).isEqualTo(record);
} |
public ShardingSphereDatabase getDatabase(final String name) {
ShardingSpherePreconditions.checkNotEmpty(name, NoDatabaseSelectedException::new);
ShardingSphereMetaData metaData = getMetaDataContexts().getMetaData();
ShardingSpherePreconditions.checkState(metaData.containsDatabase(name), () -> n... | @Test
void assertAddSchema() {
contextManager.getMetaDataContextManager().getSchemaMetaDataManager().addSchema("foo_db", "bar_schema");
verify(metaDataContexts.getMetaData().getDatabase("foo_db")).addSchema(anyString(), any(ShardingSphereSchema.class));
} |
public static PostgreSQLCommandPacket newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLPacketPayload payload) {
if (!PostgreSQLCommandPacketType.isExtendedProtocolPacketType(commandPacketType)) {
payload.getByteBuf().skipBytes(1);
return getPostgreSQLComma... | @Test
void assertNewInstanceWithFlushComPacket() {
assertThat(PostgreSQLCommandPacketFactory.newInstance(PostgreSQLCommandPacketType.FLUSH_COMMAND, payload), instanceOf(PostgreSQLAggregatedCommandPacket.class));
} |
public Plan validateReservationUpdateRequest(
ReservationSystem reservationSystem, ReservationUpdateRequest request)
throws YarnException {
ReservationId reservationId = request.getReservationId();
Plan plan = validateReservation(reservationSystem, reservationId,
AuditConstants.UPDATE_RESERV... | @Test
public void testUpdateReservationInvalidDeadline() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 0, 3);
Plan plan = null;
try {
plan = rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
} catch (YarnException e)... |
@Override
public CompletableFuture<KubernetesWatch> watchPodsAndDoCallback(
Map<String, String> labels, WatchCallbackHandler<KubernetesPod> podCallbackHandler) {
return FutureUtils.retryWithDelay(
() ->
CompletableFuture.supplyAsync(
... | @Test
void testWatchPodsAndDoCallback() throws Exception {
mockPodEventWithLabels(
NAMESPACE, TASKMANAGER_POD_NAME, KUBERNETES_ZERO_RESOURCE_VERSION, TESTING_LABELS);
// the count latch for events.
CompletableFuture<Action> podAddedAction = new CompletableFuture();
Co... |
@VisibleForTesting
static String parseBAHighGambleWidget(final String text)
{
final Matcher highGambleMatch = BA_HIGH_GAMBLE_REWARD_PATTERN.matcher(text);
if (highGambleMatch.find())
{
String gambleCount = highGambleMatch.group("gambleCount");
return String.format("High Gamble(%s)", gambleCount);
}
r... | @Test
public void testBAHighGambleRewardParsing()
{
assertEquals("High Gamble(100)", ScreenshotPlugin.parseBAHighGambleWidget(BA_HIGH_GAMBLE_REWARD));
} |
@Override
public CompletableFuture<KubernetesWorkerNode> requestResource(
TaskExecutorProcessSpec taskExecutorProcessSpec) {
final KubernetesTaskManagerParameters parameters =
createKubernetesTaskManagerParameters(
taskExecutorProcessSpec, getBlockedNodeRe... | @Test
void testKubernetesExceptionHandling() throws Exception {
new Context() {
{
runTest(
() ->
FlinkAssertions.assertThatFuture(
runInMainThread(
... |
@Override
public MailAccountDO getMailAccount(Long id) {
return mailAccountMapper.selectById(id);
} | @Test
public void testGetMailAccount() {
// mock 数据
MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class);
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbMailAccount.getId();
// 调用
MailAccountDO mailAccount = mailAcco... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testUpgradeWithIbpv(VertxTestContext context) {
String kafkaVersion = VERSIONS.defaultVersion().version();
String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.PREVIOUS_PROTOCOL_VERSION;
String oldLogMessageFormatVersion = KafkaVersionTestUtils.PREVIOUS_FORMAT_VERSI... |
@Override
public ListenableFuture<?> execute(Rollback statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
if (!session.getTransactionId().isPr... | @Test
public void testNoTransactionRollback()
{
TransactionManager transactionManager = createTestTransactionManager();
Session session = sessionBuilder()
.build();
QueryStateMachine stateMachine = createQueryStateMachine("ROLLBACK", session, true, transactionManager, ex... |
public WorkflowDefinition addWorkflowDefinition(
WorkflowDefinition workflowDef, Properties changes) {
LOG.info("Adding a new workflow definition with an id [{}]", workflowDef.getWorkflow().getId());
final Workflow workflow = workflowDef.getWorkflow();
final Metadata metadata = workflowDef.getMetadata... | @Test
public void testAddWorkflowDefinition() throws Exception {
WorkflowDefinition wfd = loadWorkflow(TEST_WORKFLOW_ID1);
WorkflowDefinition definition =
workflowDao.addWorkflowDefinition(wfd, wfd.getPropertiesSnapshot().extractProperties());
assertEquals(wfd, definition);
verify(publisher, t... |
private MqttMessage getMessage( Object[] row ) throws KettleStepException {
MqttMessage mqttMessage = new MqttMessage();
try {
mqttMessage.setQos( Integer.parseInt( meta.qos ) );
} catch ( NumberFormatException e ) {
throw new KettleStepException(
getString( PKG, "MQTTProducer.Error.QOS"... | @Test
public void testErrorOnPublishStopsAll() throws Exception {
handleAsSecondRow( trans );
MqttException mqttException = mock( MqttException.class );
when( mqttException.getMessage() ).thenReturn( "publish failed" );
when( mqttClient.isConnected() ).thenReturn( true, false );
doThrow( mqttExce... |
@EventListener(ApplicationEvent.class)
void onApplicationEvent(ApplicationEvent event) {
if (AnnotationUtils.findAnnotation(event.getClass(), SharedEvent.class) == null) {
return;
}
// we should copy the plugins list to avoid ConcurrentModificationException
var startedPlu... | @Test
void shouldNotDispatchEventToAllStartedPluginsWhilePluginContextIsNotLifecycle() {
var pw = mock(PluginWrapper.class);
var plugin = mock(SpringPlugin.class);
var context = mock(ApplicationContext.class);
when(plugin.getApplicationContext()).thenReturn(context);
when(pw.... |
public void copyToWithPermission(FilePath target) throws IOException, InterruptedException {
// Use NIO copy with StandardCopyOption.COPY_ATTRIBUTES when copying on the same machine.
if (this.channel == target.channel) {
act(new CopyToWithPermission(target));
return;
}
... | @Test public void copyToWithPermission() throws IOException, InterruptedException {
File tmp = temp.getRoot();
File child = new File(tmp, "child");
FilePath childP = new FilePath(child);
childP.touch(4711);
Chmod chmodTask = new Chmod();
chmodTask.set... |
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void when_userDeclaresObjectField_then_itsNameHasPrecedenceOverResolvedOne(boolean key, String prefix) {
Map<String, String> options = Map.of(
(key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORM... |
@Override
public void visit(Entry target) {
final FreeplaneMenuBar menuBar = userInputListenerFactory.getMenuBar();
addMnemonicsBeforeShowing(menuBar);
new EntryAccessor().setComponent(target, menuBar);
} | @Test
public void createsEmptyToolbarComponent() {
Entry toolbarEntry = new Entry();
final IUserInputListenerFactory userInputListenerFactory = mock(IUserInputListenerFactory.class);
final FreeplaneMenuBar menubar = TestMenuBarFactory.createFreeplaneMenuBar();
when(userInputListenerFactory.getMenuBar()).thenRe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.