focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Optional<ServiceInstance> select(String serviceName, PolicyContext policyContext) {
final ServiceInstance lastInstance = policyContext.getServiceInstance();
return DiscoveryManager.INSTANCE.choose(serviceName, lbCache.computeIfAbsent(serviceName,
name -> new RoundRobinLo... | @Test
public void select() {
String serviceName = "test";
final ServiceInstance selectedInstance = CommonUtils.buildInstance(serviceName, 8989);
final ServiceInstance nextInstance = CommonUtils.buildInstance(serviceName, 8888);
final List<ServiceInstance> serviceInstances = Arrays.as... |
@Override
public List<ServiceDTO> getServiceInstances(String serviceId) {
Application application = eurekaClient.getApplication(serviceId);
if (application == null || CollectionUtils.isEmpty(application.getInstances())) {
Tracer.logEvent("Apollo.Discovery.NotFound", serviceId);
return Collections.... | @Test
public void testGetServiceInstancesWithNullInstances() {
when(eurekaClient.getApplication(someServiceId)).thenReturn(null);
assertTrue(defaultDiscoveryService.getServiceInstances(someServiceId).isEmpty());
} |
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset(
RequestContext context,
OffsetCommitRequestData request
) throws ApiException {
Group group = validateOffsetCommit(context, request);
// In the old consumer group protocol, the offset commits maintai... | @Test
public void testGenericGroupOffsetCommitWithoutMemberIdAndGeneration() {
OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build();
// Create an empty group.
ClassicGroup group = context.groupMetadataManager.getOrMaybeCreateClassicGroup(
... |
public static AvroGenericCoder of(Schema schema) {
return AvroGenericCoder.of(schema);
} | @Test
public void testDeterministicNonDeterministicArray() {
assertNonDeterministic(
AvroCoder.of(NonDeterministicArray.class),
reasonField(
UnorderedMapClass.class,
"mapField",
"java.util.Map<java.lang.String, java.lang.String>"
+ " may not be d... |
public CruiseConfig deserializeConfig(String content) throws Exception {
String md5 = md5Hex(content);
Element element = parseInputStream(new ByteArrayInputStream(content.getBytes()));
LOGGER.debug("[Config Save] Updating config cache with new XML");
CruiseConfig configForEdit = classPa... | @Test
void shouldAllowBothCounterAndTruncatedGitMaterialInLabelTemplate() throws Exception {
CruiseConfig cruiseConfig = xmlLoader.deserializeConfig(LABEL_TEMPLATE_WITH_LABEL_TEMPLATE("1.3.0-${COUNT}-${git[:7]}"));
assertThat(cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("cruise")).get... |
public static Builder builder() {
return new Builder();
} | @TestTemplate
public void replacePartitionsWithDuplicates() {
assertThat(listManifestFiles()).isEmpty();
table
.newReplacePartitions()
.addFile(FILE_A)
.addFile(DataFiles.builder(SPEC).copy(FILE_A).build())
.addFile(FILE_A)
.commit();
assertThat(table.currentSnaps... |
public Response logPage(String fileName, Integer start, Integer length, String grep, String user)
throws IOException, InvalidRequestException {
Path rawFile = logRoot.resolve(fileName);
Path absFile = rawFile.toAbsolutePath().normalize();
if (!absFile.startsWith(logRoot) || !rawFile.... | @Test
public void testLogPageOutsideLogRoot() throws Exception {
try (TmpPath rootPath = new TmpPath()) {
LogviewerLogPageHandler handler = createHandlerForTraversalTests(rootPath.getFile().toPath());
final Response returned = handler.logPage("../nimbus.log", 0, 100, null, "user");
... |
@Override
public Optional<Rule> findByKey(RuleKey key) {
verifyKeyArgument(key);
ensureInitialized();
return Optional.ofNullable(rulesByKey.get(key));
} | @Test
public void findByKey_returns_absent_if_rule_does_not_exist_in_DB() {
Optional<Rule> rule = underTest.findByKey(AC_RULE_KEY);
assertThat(rule).isEmpty();
} |
@Override
public void unsubscribe(String serviceName, String groupName, String clusters) throws NacosException {
} | @Test
void testUnsubscribe() throws Exception {
String groupName = "group1";
String serviceName = "serviceName";
String clusters = "clusters";
//when
clientProxy.unsubscribe(serviceName, groupName, clusters);
// do nothing
} |
public List<String> generate(String tableName, String columnName, boolean isAutoGenerated) throws SQLException {
return generate(tableName, singleton(columnName), isAutoGenerated);
} | @Test
public void generate_for_h2() throws SQLException {
when(dbConstraintFinder.findConstraintName(TABLE_NAME)).thenReturn(Optional.of(CONSTRAINT));
when(db.getDialect()).thenReturn(H2);
List<String> sqls = underTest.generate(TABLE_NAME, PK_COLUMN, true);
assertThat(sqls).containsExactly("ALTER TA... |
public static String buildRuleParentPath(final String pluginName) {
return String.join(PATH_SEPARATOR, RULE_PARENT, pluginName);
} | @Test
public void testBuildRuleParentPath() {
String pluginName = RandomStringUtils.randomAlphanumeric(10);
String ruleParentPath = DefaultPathConstants.buildRuleParentPath(pluginName);
assertThat(ruleParentPath, notNullValue());
assertThat(String.join(SEPARATOR, RULE_PARENT, pluginN... |
@Override
public void lockInode(Inode inode, LockMode mode) {
mode = nextLockMode(mode);
if (!mLocks.isEmpty()) {
Preconditions.checkState(!endsInInode(),
"Cannot lock inode %s for lock list %s because the lock list already ends in an inode",
inode.getId(), this);
checkInodeNam... | @Test
public void lockInodeAfterInode() {
mLockList.lockInode(mDirA, LockMode.READ);
mThrown.expect(IllegalStateException.class);
mLockList.lockInode(mDirB, LockMode.READ);
} |
protected short sampleStoreTopicReplicationFactor(Map<String, ?> config, AdminClient adminClient) {
if (_sampleStoreTopicReplicationFactor != null) {
return _sampleStoreTopicReplicationFactor;
}
int maxRetryCount = Integer.parseInt(config.get(MonitorConfig.FETCH_METRIC_SAMPLES_MAX_RETRY_COUNT_CONFIG)... | @Test
public void testSampleStoreTopicReplicationFactorWhenValueAlreadyExists() {
short expected = 1;
Map<String, ?> config = Collections.emptyMap();
AdminClient adminClient = EasyMock.mock(AdminClient.class);
AbstractKafkaSampleStore kafkaSampleStore = EasyMock.partialMockBuilder(Ab... |
public static final void saveAttributesMap( DataNode dataNode, AttributesInterface attributesInterface )
throws KettleException {
saveAttributesMap( dataNode, attributesInterface, NODE_ATTRIBUTE_GROUPS );
} | @Test
public void testSaveAttributesMap_DefaultTag_NullParameter() throws Exception {
try ( MockedStatic<AttributesMapUtil> mockedAttributesMapUtil = mockStatic( AttributesMapUtil.class ) ) {
mockedAttributesMapUtil.when( () -> AttributesMapUtil.saveAttributesMap( any( DataNode.class ),
any( Attribu... |
@Override
public double readDouble(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return 0d;
}
switch (fd.getType()) {
case DOUBLE:
return super.readDouble(fieldName);
... | @Test
public void testReadDouble() throws Exception {
double aByte = reader.readDouble("byte");
double aShort = reader.readDouble("short");
double aChar = reader.readDouble("char");
double aInt = reader.readDouble("int");
double aFloat = reader.readDouble("float");
do... |
private RemotingCommand notifyMinBrokerIdChange(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
NotifyMinBrokerIdChangeRequestHeader requestHeader = (NotifyMinBrokerIdChangeRequestHeader) request.decodeCommandCustomHeader(NotifyMinBrokerIdChangeRequestHeader.class);... | @Test
public void testNotifyMinBrokerIdChange() throws RemotingCommandException {
NotifyMinBrokerIdChangeRequestHeader requestHeader = new NotifyMinBrokerIdChangeRequestHeader();
requestHeader.setMinBrokerId(1L);
requestHeader.setMinBrokerAddr("127.0.0.1:10912");
requestHeader.setOff... |
public Set<LongPair> items() {
Set<LongPair> items = new HashSet<>();
forEach((item1, item2) -> items.add(new LongPair(item1, item2)));
return items;
} | @Test
public void testItems() {
ConcurrentLongPairSet set = ConcurrentLongPairSet.newBuilder().build();
int n = 100;
int limit = 10;
for (int i = 0; i < n; i++) {
set.add(i, i);
}
Set<LongPair> items = set.items();
Set<LongPair> limitItems = set.... |
public boolean match(String pattern, String path) {
return doMatch(pattern, path, true, null);
} | @Test
public void matchesTest() {
AntPathMatcher antPathMatcher = new AntPathMatcher();
boolean matched = antPathMatcher.match("/api/org/organization/{orgId}", "/api/org/organization/999");
assertTrue(matched);
} |
@Override
public ContainerItem getContainer(final Path file) {
Deque<Path> pathDeque = decompose(file);
Path lastContainer = null;
Path lastCollection = null;
boolean exit = false, nextExit = false, exitEarly = false;
while(!exit && pathDeque.size() > 0) {
final... | @Test
public void testContainerEquality() {
final Path source = new Path("/Default/Drives/Docs", EnumSet.of(Path.Type.directory))
.withAttributes(new PathAttributes()
.withFileId("File Id"));
final Path target = new Path("/Default/Drives/Docs", EnumSet.of(Path... |
@Override
public InputFile newInputFile(String location) {
Preconditions.checkState(!closed, "Cannot call newInputFile after calling close()");
byte[] contents = IN_MEMORY_FILES.get(location);
if (null == contents) {
throw new NotFoundException("No in-memory file found for location: %s", location);
... | @Test
public void testNewInputFileNotFound() {
InMemoryFileIO fileIO = new InMemoryFileIO();
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> fileIO.newInputFile("s3://nonexistent/file"));
} |
@Override
public void revert(final Path file) throws BackgroundException {
try {
session.getClient().copy(URIEncoder.encode(file.getAbsolute()),
new DAVPathEncoder().encode(file));
}
catch(SardineException e) {
throw new DAVExceptionMappingService(... | @Test
public void testRevert() throws Exception {
final Path directory = new DAVDirectoryFeature(session).mkdir(new Path(
new OwncloudHomeFeature(session.getHost()).find(),
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new... |
@Nonnull
@Override
public Collection<DataConnectionResource> listResources() {
HazelcastInstance instance = getClient();
try {
return instance.getDistributedObjects()
.stream()
.filter(IMap.class::isInstance)
.map(o -> new D... | @Test
public void list_resources_should_not_return_system_maps() {
DataConnectionConfig dataConnectionConfig = sharedDataConnectionConfig(clusterName);
hazelcastDataConnection = new HazelcastDataConnection(dataConnectionConfig);
Collection<DataConnectionResource> resources = hazelcastDataCo... |
public static short translateBucketAcl(GSAccessControlList acl, String userId) {
short mode = (short) 0;
for (GrantAndPermission gp : acl.getGrantAndPermissions()) {
Permission perm = gp.getPermission();
GranteeInterface grantee = gp.getGrantee();
if (perm.equals(Permission.PERMISSION_READ)) {... | @Test
public void translateUserFullPermission() {
mAcl.grantPermission(mUserGrantee, Permission.PERMISSION_FULL_CONTROL);
assertEquals((short) 0700, GCSUtils.translateBucketAcl(mAcl, ID));
assertEquals((short) 0000, GCSUtils.translateBucketAcl(mAcl, OTHER_ID));
} |
public Tenant getTenant(TenantName tenantName) {
return tenants.get(tenantName);
} | @Test
public void testListenersAdded() throws IOException, SAXException {
TenantApplications applicationRepo = tenantRepository.getTenant(tenant1).getApplicationRepo();
ApplicationId id = ApplicationId.from(tenant1, ApplicationName.defaultName(), InstanceName.defaultName());
applicationRepo.... |
public void generateTypeStubs() throws IOException
{
generateMetaAttributeEnum();
for (final List<Token> tokens : ir.types())
{
switch (tokens.get(0).signal())
{
case BEGIN_ENUM:
generateEnum(tokens);
break;
... | @Test
void shouldGenerateChoiceSetStub() throws Exception
{
final int bufferOffset = 8;
final byte bitset = (byte)0b0000_0100;
final String className = "OptionalExtrasDecoder";
final String fqClassName = ir.applicableNamespace() + "." + className;
when(mockBuffer.getByte... |
@Override
public boolean accept(final Path file) {
if(list.find(new SimplePathPredicate(file)) != null) {
return true;
}
for(Path f : list) {
if(f.isChild(file)) {
return true;
}
}
if(log.isDebugEnabled()) {
log.... | @Test
public void testAcceptFile() {
final RecursiveSearchFilter f = new RecursiveSearchFilter(new AttributedList<>(Arrays.asList(new Path("/f", EnumSet.of(Path.Type.file)))));
assertTrue(f.accept(new Path("/f", EnumSet.of(Path.Type.file))));
assertFalse(f.accept(new Path("/a", EnumSet.of(Pa... |
@Override
public boolean matches(Job localJob, Job storageProviderJob) {
if (storageProviderJob.getVersion() > localJob.getVersion() + 1) {
Optional<ProcessingState> localProcessingState = localJob.getLastJobStateOfType(ProcessingState.class);
Optional<ProcessingState> storageProvide... | @Test
void ifJobIsHavingConcurrentStateChangeOnSameServerItWillNotMatch() {
final Job jobInProgress = aJobInProgress().build();
final Job succeededJob = aCopyOf(jobInProgress).withState(new SucceededState(ofMillis(10), ofMillis(6))).build();
boolean matchesAllowedStateChange = allowedStateC... |
@Override
public void define(IndexDefinitionContext context) {
NewRegularIndex index = context.create(
DESCRIPTOR,
newBuilder(config)
.setDefaultNbOfShards(5)
.build())
// storing source is required because some search queries on issue index use terms lookup query onto the view i... | @Test
public void define() {
ViewIndexDefinition def = new ViewIndexDefinition(new MapSettings().asConfig());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
NewIndex index = underTest.getIndices().get("views");
assertThat(index.getMainType())
.isEqualTo(IndexType.main... |
public void encryptColumns(
String inputFile, String outputFile, List<String> paths, FileEncryptionProperties fileEncryptionProperties)
throws IOException {
Path inPath = new Path(inputFile);
Path outPath = new Path(outputFile);
RewriteOptions options = new RewriteOptions.Builder(conf, inPath, o... | @Test
public void testNestedColumn() throws IOException {
String[] encryptColumns = {"Links.Forward"};
testSetup("GZIP");
columnEncryptor.encryptColumns(
inputFile.getFileName(),
outputFile,
Arrays.asList(encryptColumns),
EncDecProperties.getFileEncryptionProperties(encrypt... |
public final void isNotNaN() {
if (actual == null) {
failWithActual(simpleFact("expected a double other than NaN"));
} else {
isNotEqualTo(NaN);
}
} | @Test
public void isNotNaNIsNull() {
expectFailureWhenTestingThat(null).isNotNaN();
assertFailureKeys("expected a double other than NaN", "but was");
} |
public static Object getValueFromFieldOrProperty(Object object, String paramName) {
Class<?> aClass = object.getClass();
final Optional<Field> optionalField = findField(aClass, paramName);
if (optionalField.isPresent()) {
return getValueFromField(optionalField.get(), object);
... | @Test
void testGetValueFromFieldOrProperty() {
final TestObject test = new TestObject("test");
assertThat(getValueFromFieldOrProperty(test, "field")).isEqualTo("test");
assertThat(getValueFromFieldOrProperty(test, "anotherField")).isEqualTo("test");
assertThatThrownBy(() -> getValue... |
public static String removeDigits( String input ) {
if ( Utils.isEmpty( input ) ) {
return null;
}
StringBuilder digitsOnly = new StringBuilder();
char c;
for ( int i = 0; i < input.length(); i++ ) {
c = input.charAt( i );
if ( !Character.isDigit( c ) ) {
digitsOnly.append(... | @Test
public void testRemoveDigits() {
assertNull( Const.removeDigits( null ) );
assertEquals( "foobar", Const.removeDigits( "123foo456bar789" ) );
} |
public static DistCpOptions parse(String[] args)
throws IllegalArgumentException {
CommandLineParser parser = new CustomParser();
CommandLine command;
try {
command = parser.parse(cliOptions, args, true);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to pars... | @Test
public void testOptionsAppendToConfDoesntOverwriteBandwidth() {
Configuration conf = new Configuration();
Assert.assertEquals(
conf.getRaw(DistCpOptionSwitch.BANDWIDTH.getConfigLabel()), null);
DistCpOptions options = OptionsParser.parse(new String[] {
"hdfs://localhost:8020/source/f... |
public static <T> IntermediateCompatibilityResult<T> constructIntermediateCompatibilityResult(
TypeSerializerSnapshot<?>[] newNestedSerializerSnapshots,
TypeSerializerSnapshot<?>[] oldNestedSerializerSnapshots) {
Preconditions.checkArgument(
newNestedSerializerSnapshots.... | @Test
void testCompatibleAfterMigrationIntermediateCompatibilityResult() {
final TypeSerializerSnapshot<?>[] previousSerializerSnapshots =
new TypeSerializerSnapshot<?>[] {
new SchemaCompatibilityTestingSerializer("a").snapshotConfiguration(),
new Sche... |
@Override
public boolean isLeader() {
return isLeader;
} | @Test
void pausesPollingAfterDowngradeFromLeader() {
final AtomicInteger lockInvocations = new AtomicInteger();
final AtomicReference<Lock> lock = new AtomicReference<>();
when(lockService.lock(any(), isNull())).then(i -> {
lockInvocations.incrementAndGet();
return O... |
@Override
public Long time(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG);
return syncFuture(f);
} | @Test
public void testTime() {
testInCluster(connection -> {
RedisClusterNode master = getFirstMaster(connection);
Long time = connection.time(master);
assertThat(time).isGreaterThan(1000);
});
} |
public ParsedQuery parse(final String query) throws ParseException {
final TokenCollectingQueryParser parser = new TokenCollectingQueryParser(ParsedTerm.DEFAULT_FIELD, ANALYZER);
parser.setSplitOnWhitespace(true);
parser.setAllowLeadingWildcard(allowLeadingWildcard);
final Query parsed ... | @Test
void testValueTokenSimple() throws ParseException {
final ParsedQuery query = parser.parse("foo:bar AND lorem:ipsum");
assertThat(query.terms().size()).isEqualTo(2);
assertThat(query.terms())
.hasSize(2)
.anySatisfy(term -> {
assertT... |
@NonNull
FrameHeader readFrameHeader() throws IOException {
String id = readPlainBytesToString(FRAME_ID_LENGTH);
int size = readInt();
if (tagHeader != null && tagHeader.getVersion() >= 0x0400) {
size = unsynchsafe(size);
}
short flags = readShort();
retur... | @Test
public void testReadFrameHeader() throws IOException {
byte[] data = generateFrameHeader("CHAP", 42);
CountingInputStream inputStream = new CountingInputStream(new ByteArrayInputStream(data));
FrameHeader header = new ID3Reader(inputStream).readFrameHeader();
assertEquals("CHAP... |
public boolean isHidden(final String topicName) {
return hiddenTopicsPattern.matcher(topicName).matches();
} | @Test
public void shouldReturnFalseOnNonHiddenTopics() {
// Given
final List<String> topicNames = ImmutableList.of(
KSQL_PROCESSING_LOG_TOPIC,
"topic_prefix_", "_suffix_topic"
);
// Given
topicNames.forEach(topic -> {
// When
final boolean isHidden = internalTopics.isH... |
@Override
public Metrics toHour() {
MaxLabeledFunction metrics = (MaxLabeledFunction) createNew();
metrics.setEntityId(getEntityId());
metrics.setTimeBucket(toTimeBucketInHour());
metrics.setServiceId(getServiceId());
metrics.getValue().copyFrom(getValue());
return me... | @Test
public void testToHour() {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1);
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_2);
function.calculate();
final MaxLabeledFunction hourFunction = (MaxLa... |
public static MacAddress valueOf(final String address) {
if (!isValid(address)) {
throw new IllegalArgumentException(
"Specified MAC Address must contain 12 hex digits"
+ " separated pairwise by :'s.");
}
final String[] elements = addre... | @Test(expected = IllegalArgumentException.class)
public void testValueOfInvalidStringWithTooLongOctet() throws Exception {
MacAddress.valueOf(INVALID_MAC_OCTET_TOO_LONG);
} |
@Override
public boolean isNodeVersionCompatibleWith(Version clusterVersion) {
Preconditions.checkNotNull(clusterVersion);
return node.getVersion().asVersion().equals(clusterVersion);
} | @Test
public void test_nodeVersionNotCompatibleWith_otherMinorVersion() {
MemberVersion currentVersion = getNode(hazelcastInstance).getVersion();
Version minorPlusOne = Version.of(currentVersion.getMajor(), currentVersion.getMinor() + 1);
assertFalse(nodeExtension.isNodeVersionCompatibleWith... |
@Override
public long timestamp() {
if (recordContext == null) {
// This is only exposed via the deprecated ProcessorContext,
// in which case, we're preserving the pre-existing behavior
// of returning dummy values when the record context is undefined.
// For... | @Test
public void shouldReturnTimestampFromRecordContext() {
assertThat(context.timestamp(), equalTo(recordContext.timestamp()));
} |
@Override
public E peek() {
E e = null;
for (int i=0; e == null && i < queues.size(); i++) {
e = queues.get(i).peek();
}
return e;
} | @Test
public void testPeekNullWhenEmpty() {
assertNull(fcq.peek());
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void chatJoinRequest() {
BaseResponse response = bot.execute(new ApproveChatJoinRequest(groupId, memberBot));
assertFalse(response.isOk());
assertEquals("Bad Request: USER_ALREADY_PARTICIPANT", response.description());
response = bot.execute(new DeclineChatJoinRequest(g... |
protected CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageFromRemoteAsync(String topic, long offset, int queueId, String brokerName) {
try {
String brokerAddr = this.brokerController.getTopicRouteInfoManager().findBrokerAddressInSubscribe(brokerName, MixAll.MASTER_ID, false);
... | @Test
public void getMessageFromRemoteAsyncTest() {
Assertions.assertThatCode(() -> escapeBridge.getMessageFromRemoteAsync(TEST_TOPIC, 1, DEFAULT_QUEUE_ID, BROKER_NAME)).doesNotThrowAnyException();
} |
protected static DataSource getDataSourceFromJndi( String dsName, Context ctx ) throws NamingException {
if ( Utils.isEmpty( dsName ) ) {
throw new NamingException( BaseMessages.getString( PKG, "DatabaseUtil.DSNotFound", String.valueOf( dsName ) ) );
}
Object foundDs = FoundDS.get( dsName );
if ( ... | @Test( expected = NamingException.class )
public void testEmptyName() throws NamingException {
DatabaseUtil.getDataSourceFromJndi( "", context );
} |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testRecordWithPastTimestampIsRejected() {
long timestampBeforeMaxConfig = Duration.ofHours(24).toMillis(); // 24 hrs
long timestampAfterMaxConfig = Duration.ofHours(1).toMillis(); // 1 hr
long now = System.currentTimeMillis();
long fiveMinutesBeforeThreshold = now -... |
public void remove(String name) {
metadata.remove(name);
} | @Test
public void testRemove() {
Metadata meta = new Metadata();
meta.remove("name-one");
assertEquals(0, meta.size());
meta.add("name-one", "value-1.1");
meta.add("name-one", "value-1.2");
meta.add("name-two", "value-2.2");
assertEquals(2, meta.size());
... |
@Override
public ExecuteContext before(ExecuteContext context) {
init();
Object[] arguments = context.getArguments();
URI uri = (URI) context.getArguments()[1];
if (!PlugEffectWhiteBlackUtils.isHostEqualRealmName(uri.getHost())) {
return context;
}
Map<Str... | @Test
public void test() {
// The domain name does not match
arguments[1] = URI.create("http://www.domain1.com/foo/hello");
interceptor.before(context);
Assert.assertFalse(context.isSkip());
// The name of the service does not match
arguments[1] = URI.create("http://... |
public void setExpression(String expression) {
this.expression = expression;
} | @Test
void testSetExpression() {
MockCmdbSelector cmdbSelector = new MockCmdbSelector();
assertNull(cmdbSelector.getExpression());
cmdbSelector.setExpression("test");
assertEquals("test", cmdbSelector.getExpression());
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldCreateSourceTable() {
// Given:
final SingleStatementContext stmt =
givenQuery("CREATE SOURCE TABLE X WITH (kafka_topic='X');");
// When:
final CreateTable result = (CreateTable) builder.buildStatement(stmt);
// Then:
assertThat(result.isSource(), is(true));
... |
@Override
public byte[] decompress(byte[] src) throws IOException {
byte[] result = src;
byte[] uncompressData = new byte[src.length];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArra... | @Test(expected = IOException.class)
public void testDecompressionFailureWithInvalidData() throws Exception {
byte[] compressedData = new byte[] {0, 1, 2, 3, 4};
ZlibCompressor compressor = new ZlibCompressor();
compressor.decompress(compressedData); // Invalid compressed data
} |
@Override
public void deletePermission(String role, String resource, String action) {
String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?";
try {
jt.update(sql, role, resource, action);
} catch (CannotGetJdbcConnectionException e) {
... | @Test
void testDeletePermission() {
String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?";
externalPermissionPersistService.deletePermission("role", "resource", "action");
Mockito.verify(jdbcTemplate).update(sql, "role", "resource", "action");
} |
@Override
public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext,
final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException {
if (1 == queryResults.size() && !isNeedAggregateRewri... | @Test
void assertBuildGroupByStreamMergedResultWithOracleLimit() throws SQLException {
final ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "Oracle"));
final ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS... |
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException {
final List<MavenArtifact> result = new ArrayList<>();
try (InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
JsonParser ... | @Test
public void shouldProcessCorrectlyArtifactoryAnswerWithoutSha256() throws IOException {
// Given
Dependency dependency = new Dependency();
dependency.setSha1sum("2e66da15851f9f5b5079228f856c2f090ba98c38");
dependency.setMd5sum("3dbee72667f107b4f76f2d5aa33c5687");
final ... |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
// 0. 只有【普通】订单,才计算该优惠
if (ObjectUtil.notEqual(result.getType(), TradeOrderTypeEnum.NORMAL.getType())) {
return;
}
// 1. 获得用户的会员等级
MemberUserRespDTO user = memberUse... | @Test
public void testCalculate() {
// 准备参数
TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
.setUserId(1024L)
.setItems(asList(
new TradePriceCalculateReqBO.Item().setSkuId(10L).setCount(2).setSelected(true), // 匹配活动,且已选中
... |
public WatsonxAiRequest request(Prompt prompt) {
WatsonxAiChatOptions options = WatsonxAiChatOptions.builder().build();
if (this.defaultOptions != null) {
options = ModelOptionsUtils.merge(options, this.defaultOptions, WatsonxAiChatOptions.class);
}
if (prompt.getOptions() != null) {
if (prompt.getOpti... | @Test
public void testCreateRequestWithNoModelId() {
var options = ChatOptionsBuilder.builder().withTemperature(0.9f).withTopK(100).withTopP(0.6f).build();
Prompt prompt = new Prompt("Test message", options);
Exception exception = Assert.assertThrows(IllegalArgumentException.class, () -> {
WatsonxAiRequest ... |
@Override
protected void write(final PostgreSQLPacketPayload payload) {
payload.getByteBuf().writeBytes(PREFIX);
payload.getByteBuf().writeByte(status);
} | @Test
void assertReadWriteWithNotInTransaction() {
ByteBuf byteBuf = ByteBufTestUtils.createByteBuf(6);
PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8);
PostgreSQLReadyForQueryPacket packet = PostgreSQLReadyForQueryPacket.NOT_IN_TRANSACTION;
... |
public Set<String> getReferencedSearchFiltersIds(final Collection<UsesSearchFilters> searchFiltersOwners) {
return searchFiltersOwners
.stream()
.map(UsesSearchFilters::filters)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
... | @Test
void testGetReferencedSearchFiltersIdsReturnsProperIds() {
final ReferencedSearchFilter filter1 = ReferencedQueryStringSearchFilter.builder().id("r_id_1").build();
final ReferencedSearchFilter filter2 = ReferencedQueryStringSearchFilter.builder().id("r_id_2").build();
final Query query... |
@Transactional
public ReviewGroupCreationResponse createReviewGroup(ReviewGroupCreationRequest request) {
String reviewRequestCode;
do {
reviewRequestCode = randomCodeGenerator.generate(REVIEW_REQUEST_CODE_LENGTH);
} while (reviewGroupRepository.existsByReviewRequestCode(reviewRe... | @Test
void 코드가_중복되는_경우_다시_생성한다() {
// given
reviewGroupRepository.save(new ReviewGroup("reviewee", "project", "0000", "1111"));
given(randomCodeGenerator.generate(anyInt()))
.willReturn("0000") // ReviewRequestCode
.willReturn("AAAA");
ReviewGroupCrea... |
public Analysis analyze(Statement statement)
{
return analyze(statement, false);
} | @Test
public void testOrderByExpressionOnOutputColumn2()
{
// TODO: validate output
analyze("SELECT a x FROM t1 ORDER BY a + 1");
assertFails(TYPE_MISMATCH, 3, 10,
"SELECT x.c as x\n" +
"FROM (VALUES 1) x(c)\n" +
"ORDER BY ... |
public int getWriteDelaySeconds() {
return writeDelaySeconds;
} | @Test
public void getWriteDelaySeconds() {
assertEquals(DEFAULT_WRITE_DELAY_SECONDS, new MapStoreConfig().getWriteDelaySeconds());
} |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseNullAsNullIfSurroundedByWhitespace() {
SchemaAndValue schemaAndValue = Values.parseString(WHITESPACE + "null" + WHITESPACE);
assertNull(schemaAndValue);
} |
@Override
public int[] toIntArray() {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = i;
}
return array;
} | @Test
public void toIntArray() throws Exception {
RangeSet rs = new RangeSet(4);
int[] array = rs.toIntArray();
assertArrayEquals(new int[]{0, 1, 2, 3}, array);
} |
public static boolean isContains(String values, String value) {
return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value);
} | @Test
void testIsContains() throws Exception {
assertThat(StringUtils.isContains("a,b, c", "b"), is(true));
assertThat(StringUtils.isContains("", "b"), is(false));
assertThat(StringUtils.isContains(new String[] {"a", "b", "c"}, "b"), is(true));
assertThat(StringUtils.isContains((Stri... |
@Override
public void consume(Update update) {
super.consume(update);
} | @Test
void canReportUpdatedStatistics() {
Update upd1 = mockFullUpdate(bot, CREATOR, "/count 1 2 3 4");
bot.consume(upd1);
Update upd2 = mockFullUpdate(bot, CREATOR, "must reply");
bot.consume(upd2);
Mockito.reset(silent);
Update statUpd = mockFullUpdate(bot, CREATOR, "/stats");
bot.cons... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
@Category(ValidatesRunner.class)
public void testReshuffleAfterSessionsAndGroupByKey() {
PCollection<KV<String, Iterable<Integer>>> input =
pipeline
.apply(
Create.of(GBK_TESTABLE_KVS)
.withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of())))
... |
@Subscribe
public void onScriptCallbackEvent(ScriptCallbackEvent event)
{
String eventName = event.getEventName();
int[] intStack = client.getIntStack();
String[] stringStack = client.getStringStack();
int intStackSize = client.getIntStackSize();
int stringStackSize = client.getStringStackSize();
switch... | @Test
public void testExplicitSearch()
{
when(client.getIntStack()).thenReturn(new int[]{0, ABYSSAL_WHIP});
when(client.getStringStack()).thenReturn(new String[]{"tag:whip"});
when(configManager.getConfiguration(BankTagsPlugin.CONFIG_GROUP,
TagManager.ITEM_KEY_PREFIX + ABYSSAL_WHIP)).thenReturn("herb,bossin... |
public URL getInterNodeListener(
final Function<URL, Integer> portResolver
) {
return getInterNodeListener(portResolver, LOGGER);
} | @Test
public void shouldThrowIfOnGetInterNodeListenerIfInternalListenerSetToUnresolvableHost() {
// Given:
final URL expected = url("https://unresolvable_host:12345");
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(StreamsConfig.BOOTSTRAP_SERVERS_CONF... |
static String replaceInvalidChars(String str) {
char[] chars = null;
final int strLen = str.length();
int pos = 0;
for (int i = 0; i < strLen; i++) {
final char c = str.charAt(i);
switch (c) {
case '>':
case '<':
ca... | @Test
void testReplaceInvalidChars() {
assertThat(JMXReporter.replaceInvalidChars("")).isEqualTo("");
assertThat(JMXReporter.replaceInvalidChars("abc")).isEqualTo("abc");
assertThat(JMXReporter.replaceInvalidChars("abc\"")).isEqualTo("abc");
assertThat(JMXReporter.replaceInvalidChars... |
public Future<Void> reconcile(boolean isOpenShift, ImagePullPolicy imagePullPolicy, List<LocalObjectReference> imagePullSecrets, Clock clock) {
return serviceAccount()
.compose(i -> entityOperatorRole())
.compose(i -> topicOperatorRole())
.compose(i -> userOper... | @Test
public void reconcileWithToAndUoAndWatchNamespaces(VertxTestContext context) {
String toWatchNamespace = "to-watch-namespace";
String uoWatchNamespace = "uo-watch-namespace";
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
DeploymentOperator mockDep... |
@Override
public boolean unloadPlugin(String pluginId) {
if (currentPluginId.equals(pluginId)) {
return original.unloadPlugin(pluginId);
} else {
throw new IllegalAccessError(PLUGIN_PREFIX + currentPluginId + " tried to execute unloadPlugin for foreign pluginId!");
}
... | @Test
public void unloadPlugin() {
pluginManager.loadPlugins();
assertThrows(IllegalAccessError.class, () -> wrappedPluginManager.unloadPlugin(OTHER_PLUGIN_ID));
assertTrue(wrappedPluginManager.unloadPlugin(THIS_PLUGIN_ID));
} |
public void startAsync() {
try {
udfLoader.load();
ProcessingLogServerUtils.maybeCreateProcessingLogTopic(
serviceContext.getTopicClient(),
processingLogConfig,
ksqlConfig);
if (processingLogConfig.getBoolean(ProcessingLogConfig.STREAM_AUTO_CREATE)) {
log.warn... | @Test
public void shouldCreateProcessingLogTopic() {
// When:
standaloneExecutor.startAsync();
// Then
verify(kafkaTopicClient).createTopic(eq(PROCESSING_LOG_TOPIC_NAME), anyInt(), anyShort());
} |
@Override
public List<Change> computeDiff(final List<T> source, final List<T> target, DiffAlgorithmListener progress) {
Objects.requireNonNull(source, "source list must not be null");
Objects.requireNonNull(target, "target list must not be null");
if (progress != null) {
progres... | @Test
public void testDiffMyersExample1Forward() {
List<String> original = Arrays.asList("A", "B", "C", "A", "B", "B", "A");
List<String> revised = Arrays.asList("C", "B", "A", "B", "A", "C");
final Patch<String> patch = Patch.generate(original, revised, new MyersDiff<String>().computeDiff(o... |
public void set(int index, E value) {
assert value != null;
Storage32 newStorage = storage.set(index, value);
if (newStorage != storage) {
storage = newStorage;
}
} | @Test
public void testSetDenseToSparse32WithMaxExceeded() {
// add some dense entries
for (int i = 0; i < ARRAY_STORAGE_32_MAX_SPARSE_SIZE; ++i) {
set(i);
verify();
}
// go far beyond the last index to trigger dense to sparse conversion
set(ARRAY_STOR... |
@Override
public void checkBeforeUpdate(final CreateReadwriteSplittingRuleStatement sqlStatement) {
ReadwriteSplittingRuleStatementChecker.checkCreation(database, sqlStatement.getRules(), null == rule ? null : rule.getConfiguration(), sqlStatement.isIfNotExists());
} | @Test
void assertCheckSQLStatementWithoutExistedResources() {
when(resourceMetaData.getNotExistedDataSources(any())).thenReturn(Arrays.asList("read_ds_0", "read_ds_1"));
assertThrows(MissingRequiredStorageUnitsException.class, () -> executor.checkBeforeUpdate(createSQLStatement("TEST")));
} |
@VisibleForTesting
static List<TopicPartition> getAllTopicPartitions(
SerializableFunction<Map<String, Object>, Consumer<byte[], byte[]>> kafkaConsumerFactoryFn,
Map<String, Object> kafkaConsumerConfig,
Set<String> topics,
@Nullable Pattern topicPattern) {
List<TopicPartition> current = ne... | @Test
public void testGetAllTopicPartitions() throws Exception {
Consumer<byte[], byte[]> mockConsumer = Mockito.mock(Consumer.class);
when(mockConsumer.listTopics())
.thenReturn(
ImmutableMap.of(
"topic1",
ImmutableList.of(
new Partition... |
public Map<String, FieldMapping> fieldTypes(final String index) {
final JsonNode result = client.executeRequest(request(index), "Unable to retrieve field types of index " + index);
final JsonNode fields = result.path(index).path("mappings").path("properties");
//noinspection UnstableApiUsage
... | @Test
void testReturnsEmptyMapOnNoMappings() throws Exception {
String mappingResponse = """
{
"graylog_13": {
"mappings": {
"properties": {
}
}
}
}
... |
public static <T> int indexOfSub(T[] array, T[] subArray) {
return indexOfSub(array, 0, subArray);
} | @Test
public void lastIndexOfSubTest2() {
Integer[] a = {0x12, 0x56, 0x78, 0x56, 0x21, 0x9A};
Integer[] b = {0x56, 0x78};
int i = ArrayUtil.indexOfSub(a, b);
assertEquals(1, i);
} |
@Override
public synchronized void blameResult(InputFile file, List<BlameLine> lines) {
checkNotNull(file);
checkNotNull(lines);
checkArgument(allFilesToBlame.contains(file), "It was not expected to blame file %s", file);
if (lines.size() != file.lines()) {
LOG.debug("Ignoring blame result sinc... | @Test
public void shouldFailIfNullDate() {
InputFile file = new TestInputFileBuilder("foo", "src/main/java/Foo.java").setLines(1).build();
var blameOutput = new DefaultBlameOutput(null, analysisWarnings, singletonList(file), mock(DocumentationLinkGenerator.class));
var lines = singletonList(new BlameLine(... |
public static void extract(Path source, Path destination) throws IOException {
extract(source, destination, false);
} | @Test
public void testExtract_reproducibleTimestampsEnabled() throws URISyntaxException, IOException {
// The tarfile has only level1/level2/level3/file.txt packaged
Path source = Paths.get(Resources.getResource("core/tarfile-only-file-packaged.tar").toURI());
Path destination = temporaryFolder.getRoot()... |
@Override
public boolean betterThan(Num criterionValue1, Num criterionValue2) {
return criterionValue1.isGreaterThan(criterionValue2);
} | @Test
public void betterThan() {
AnalysisCriterion criterion = getCriterion();
assertTrue(criterion.betterThan(numOf(50), numOf(45)));
assertFalse(criterion.betterThan(numOf(45), numOf(50)));
} |
public void loadServiceMetadataSnapshot(ConcurrentMap<Service, ServiceMetadata> snapshot) {
for (Service each : snapshot.keySet()) {
Service service = Service.newService(each.getNamespace(), each.getGroup(), each.getName(), each.isEphemeral());
ServiceManager.getInstance().getSingleton(... | @Test
void testLoadServiceMetadataSnapshot() {
namingMetadataManager.loadServiceMetadataSnapshot(new ConcurrentHashMap<>());
Map<Service, ServiceMetadata> serviceMetadataSnapshot = namingMetadataManager.getServiceMetadataSnapshot();
assertEquals(0, serviceMetadataSnapshot.size());
... |
@Override
public JCExpression inline(Inliner inliner) {
return inliner.getBinding(key()).inline(inliner);
} | @Test
public void inline() {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
Symtab symtab = Symtab.instance(context);
Type listType = symtab.listType;
bind(
new UTypeVar.Key("E"),
TypeWithExpression.create(
new ClassType(listType, List.<Type>of(symtab.stringType... |
public E peek() {
if (mSize == 0) {
throw new EmptyStackException();
}
return mElements.get(mSize - 1);
} | @Test
void testIllegalPeek() throws Exception {
Assertions.assertThrows(EmptyStackException.class, () -> {
Stack<String> stack = new Stack<String>();
stack.peek();
});
} |
public static PodTemplateSpec createPodTemplateSpec(
String workloadName,
Labels labels,
PodTemplate template,
Map<String, String> defaultPodLabels,
Map<String, String> podAnnotations,
Affinity affinity,
List<Container> initContainers,
... | @Test
public void testCreatePodTemplateSpecWithNullValues() {
PodTemplateSpec pod = WorkloadUtils.createPodTemplateSpec(
NAME,
LABELS,
null,
null,
null,
null,
null,
List.of(new Co... |
@Udf(description = "Returns a masked version of the input string. All characters except for the"
+ " last n will be replaced according to the default masking rules.")
@SuppressWarnings("MethodMayBeStatic") // Invoked via reflection
public String mask(
@UdfParameter("input STRING to be masked") final Str... | @Test
public void shouldThrowIfLengthIsNegative() {
// When:
final KsqlException e = assertThrows(
KsqlFunctionException.class,
() -> udf.mask("AbCd#$123xy Z", -1)
);
// Then:
assertThat(e.getMessage(), containsString("function mask_keep_right requires a non-negative number"));
} |
@VisibleForTesting
static String fromSecondLevel(String qualifiedTemplateClass) {
List<String> path = Splitter.on('.').splitToList(qualifiedTemplateClass);
for (int topLevel = 0; topLevel < path.size() - 1; topLevel++) {
if (Ascii.isUpperCase(path.get(topLevel).charAt(0))) {
return Joiner.on('_'... | @Test
public void fromSecondLevel() {
assertThat(
RefasterRule.fromSecondLevel(
"com.google.devtools.javatools.refactory.refaster.cleanups.MergeNestedIf"))
.isEqualTo("MergeNestedIf");
assertThat(
RefasterRule.fromSecondLevel(
"com.google.devtool... |
@Operation(summary = "秒杀场景二(redis分布式锁实现)", description = "秒杀场景二(redis分布式锁实现)", method = "POST")
@PostMapping("/redisson")
public Result doWithRedissionLock(@RequestBody @Valid SeckillWebMockRequestDTO dto) {
processSeckill(dto, REDISSION_LOCK);
return Result.ok();
} | @Test
void testDoWithRedissionLock() {
SeckillWebMockRequestDTO requestDTO = new SeckillWebMockRequestDTO();
requestDTO.setSeckillId(1L);
requestDTO.setRequestCount(1);
SeckillMockRequestDTO any = new SeckillMockRequestDTO();
any.setSeckillId(1L);
Result response = se... |
@Override
public boolean tryLock() {
return get(tryLockAsync());
} | @Test
public void testReentrancy() throws InterruptedException {
Lock lock = redisson.getSpinLock("lock1");
Assertions.assertTrue(lock.tryLock());
Assertions.assertTrue(lock.tryLock());
lock.unlock();
// next row for test renew expiration tisk.
//Thread.currentThread... |
static boolean isAllowedMultiplicationBasedOnSpec(final Object left, final Object right, final EvaluationContext ctx) {
if (left instanceof TemporalAmount && right instanceof TemporalAmount) {
ctx.notifyEvt(() -> new InvalidParametersEvent(FEELEvent.Severity.ERROR, Msg.createMessage(Msg.INVALID_PARA... | @Test
void isAllowedMultiplicationBasedOnSpecTest() {
EvaluationContext evaluationContext = mock(EvaluationContext.class);
Object left = 23;
Object right = 354.5;
assertThat(isAllowedMultiplicationBasedOnSpec(left, right, evaluationContext)).isTrue();
verify(evaluationContext... |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldAllowNestedLambdaFunctionsWithoutDuplicate() {
// Given:
final Statement stmt = givenQuery(
"SELECT TRANSFORM_ARRAY(Col4, (X,Y,Z) => TRANSFORM_MAP(Col4, Q => 4, H => 5), (X,Y,Z) => 0) FROM TEST1;");
// When:
final Query result = (Query) AstSanitizer.sanitize(stmt, META... |
public void evaluate(List<AuthorizationContext> contexts) {
if (CollectionUtils.isEmpty(contexts)) {
return;
}
contexts.forEach(this.authorizationStrategy::evaluate);
} | @Test
public void evaluate1() {
if (MixAll.isMac()) {
return;
}
User user = User.of("test", "test");
this.authenticationMetadataManager.createUser(user).join();
Acl acl = AuthTestHelper.buildAcl("User:test", "Topic:test*", "Pub", "192.168.0.0/24", Decision.ALLOW)... |
@Override
public void waitFor(
final KsqlEntityList previousCommands,
final Class<? extends Statement> statementClass) {
if (mustSync.test(statementClass)) {
final ArrayList<KsqlEntity> reversed = new ArrayList<>(previousCommands);
Collections.reverse(reversed);
reversed.stream()
... | @Test
public void shouldNotWaitForNonCommandStatusEntity() throws Exception {
// Given:
givenSyncWithPredicate(clazz -> true);
givenEntities(entity1);
// When:
commandQueueSync.waitFor(entities, CreateStreamAsSelect.class);
// Then:
verify(commandQueue, never()).ensureConsumedPast(anyLon... |
protected Timestamp convertBigNumberToTimestamp( BigDecimal bd ) {
if ( bd == null ) {
return null;
}
return convertIntegerToTimestamp( bd.longValue() );
} | @Test
public void testConvertBigNumberToTimestamp_Milliseconds() throws KettleValueException {
System.setProperty( Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE,
Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE_MILLISECONDS );
ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp();
Timestamp ... |
public Map<String, Object> populateAnomalyDetails() {
// Goal violation has one more field than other anomaly types.
Map<String, Object> anomalyDetails = new HashMap<>();
anomalyDetails.put(_isJson ? DETECTION_MS : DETECTION_DATE,
_isJson ? _anomalyState.detectionMs() : utcDateFor(_an... | @Test
public void testPopulateAnomalyDetails() {
AnomalyState mockAnomalyState = EasyMock.mock(AnomalyState.class);
for (KafkaAnomalyType anomalyType : KafkaAnomalyType.cachedValues()) {
AnomalyDetails details = new AnomalyDetails(mockAnomalyState, anomalyType, false, false);
EasyMock.expect(mock... |
@Override
public Optional<IndexSet> get(final String indexSetId) {
return this.indexSetsCache.get()
.stream()
.filter(indexSet -> Objects.equals(indexSet.id(), indexSetId))
.map(indexSetConfig -> (IndexSet) mongoIndexSetFactory.create(indexSetConfig))
... | @Test
public void indexSetsCacheShouldReturnNewListAfterInvalidate() {
final IndexSetConfig indexSetConfig = mock(IndexSetConfig.class);
final List<IndexSetConfig> indexSetConfigs = Collections.singletonList(indexSetConfig);
when(indexSetService.findAll()).thenReturn(indexSetConfigs);
... |
public void go(PrintStream out) {
KieServices ks = KieServices.Factory.get();
KieRepository kr = ks.getRepository();
Resource ex1Res = ks.getResources().newFileSystemResource(getFile("kiebase-inclusion"));
Resource ex2Res = ks.getResources().newFileSystemResource(getFile("named-kiesessi... | @Test
public void testGo() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
new KieModuleFromMultipleFilesExample().go(ps);
ps.close();
String actual = baos.toString();
String expected = "" +
... |
public static ConfigDefinition createConfigDefinition(CNode root) {
ConfigDefinition def = new ConfigDefinition(root.getName(), root.getNamespace());
for (CNode node : root.getChildren()) {
addNode(def, node);
}
return def;
} | @Test
// TODO Test ranges
public void testCreateConfigDefinition() throws IOException {
File defFile = new File(DEF_NAME);
DefParser defParser = new DefParser(defFile.getName(), new FileReader(defFile));
CNode root = defParser.getTree();
ConfigDefinition def = ConfigDefinitionBu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.