focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public HttpAction restore(final CallContext ctx, final String defaultUrl) {
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val optRequestedUrl = sessionStore.get(webContext, Pac4jConstants.REQUESTED_URL);
HttpAction requestedAction = null;
... | @Test
public void testRestoreOkActionAfterPost() {
val context = MockWebContext.create().setFullRequestURL(PAC4J_URL).addRequestParameter(KEY, VALUE);
val formPost = HttpActionHelper.buildFormPostContent(context);
context.setRequestMethod("POST");
val sessionStore = new MockSessionSt... |
@Override
public PageResult<DiscountActivityDO> getDiscountActivityPage(DiscountActivityPageReqVO pageReqVO) {
return discountActivityMapper.selectPage(pageReqVO);
} | @Test
public void testGetDiscountActivityPage() {
// mock 数据
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class, o -> { // 等会查询到
o.setName("芋艿");
o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus());
o.setCreateTime(buildTime(2021, 1, 15))... |
@GET
@Path("{netId}")
@Produces(MediaType.APPLICATION_JSON)
public Response allocateIp(@PathParam("netId") String netId) {
log.trace("Received IP allocation request of network " + netId);
K8sNetwork network =
nullIsNotFound(networkService.network(netId), NETWORK_ID_NOT_FOUND... | @Test
public void testAllocateIpWithNullIp() {
expect(mockNetworkService.network(anyObject())).andReturn(k8sNetwork);
expect(mockIpamService.allocateIp(anyObject())).andReturn(null);
replay(mockNetworkService);
replay(mockIpamService);
final WebTarget wt = target();
... |
public synchronized QueryId createNextQueryId()
{
// only generate 100,000 ids per day
if (counter > 99_999) {
// wait for the second to rollover
while (MILLISECONDS.toSeconds(nowInMillis()) == lastTimeInSeconds) {
Uninterruptibles.sleepUninterruptibly(1, Time... | @Test
public void testCreateNextQueryId()
{
TestIdGenerator idGenerator = new TestIdGenerator();
long millis = new DateTime(2001, 7, 14, 1, 2, 3, 4, DateTimeZone.UTC).getMillis();
idGenerator.setNow(millis);
// generate ids to 99,999
for (int i = 0; i < 100_000; i++) {
... |
public PublicKey convertPublicKey(final String publicPemKey) {
final StringReader keyReader = new StringReader(publicPemKey);
try {
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
.getInstance(new PEMParser(keyReader).readObject());
return new JcaPE... | @Test
void givenEmptyPublicKey_whenConvertPublicKey_thenThrowRuntimeException() {
// Given
String emptyPublicPemKey = "";
// When & Then
assertThatThrownBy(() -> KeyConverter.convertPublicKey(emptyPublicPemKey))
.isInstanceOf(RuntimeException.class)
.... |
public static CompletableFuture<Channel> toCompletableFuture(ChannelFuture channelFuture) {
Objects.requireNonNull(channelFuture, "channelFuture cannot be null");
CompletableFuture<Channel> adapter = new CompletableFuture<>();
if (channelFuture.isDone()) {
if (channelFuture.isSucces... | @Test(expectedExceptions = NullPointerException.class)
public void toCompletableFuture_shouldRequireNonNullArgument() {
ChannelFutures.toCompletableFuture(null);
} |
public Properties getProperties()
{
return properties;
} | @Test
public void testEmptyPassword()
throws SQLException
{
PrestoDriverUri parameters = createDriverUri("presto://localhost:8080?password=");
assertEquals(parameters.getProperties().getProperty("password"), "");
} |
public static void analyze(CreateTableStmt statement, ConnectContext context) {
final TableName tableNameObject = statement.getDbTbl();
MetaUtils.normalizationTableName(context, tableNameObject);
final String catalogName = tableNameObject.getCatalog();
MetaUtils.checkCatalogExistAndRepo... | @Test
public void testAnalyzeMaxBucket() throws Exception {
Config.max_column_number_per_table = 10000;
String sql = "CREATE TABLE test_create_table_db.starrocks_test_table\n" +
"(\n" +
" `tag_id` bigint not null,\n" +
" `tag_name` string\n" +
... |
@Override
public List<RegisteredMigrationStep> readFrom(long migrationNumber) {
validate(migrationNumber);
int startingIndex = lookupIndexOfClosestTo(migrationNumber);
if (startingIndex < 0) {
return Collections.emptyList();
}
return steps.subList(startingIndex, steps.size());
} | @Test
public void readFrom_returns_an_empty_stream_if_argument_is_greater_than_biggest_migration_number() {
verifyContainsNumbers(underTest.readFrom(9));
verifyContainsNumbers(unorderedSteps.readFrom(9));
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testInFlightFetchOnPausedPartition() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
subscriptions.pause(tp0);
client.prepareResponse(fullFetchResponse(tidp0, records, Errors.NONE, 100L... |
@GET
@Path("/{entityType}/{entityId}")
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8
/* , MediaType.APPLICATION_XML */})
public TimelineEntity getEntity(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@PathParam("entityType") String entityType,
... | @Test
void testPostEntitiesWithPrimaryFilter() throws Exception {
TimelineEntities entities = new TimelineEntities();
TimelineEntity entity = new TimelineEntity();
Map<String, Set<Object>> filters = new HashMap<String, Set<Object>>();
filters.put(TimelineStore.SystemFilter.ENTITY_OWNER.toString(),
... |
public int remap(int var, int size) {
if ((var & REMAP_FLAG) != 0) {
return unmask(var);
}
int offset = var - argsSize;
if (offset < 0) {
// self projection for method arguments
return var;
}
if (offset >= mapping.length) {
mapping = Arrays.copyOf(mapping, Math.max(mappi... | @Test
public void remapSame() {
int var = instance.remap(2, 1);
assertEquals(var, instance.remap(2, 1));
} |
public ImmutableList<GlobalSetting> parse(final InputStream is) {
return Jsons.toObjects(is, GlobalSetting.class);
} | @Test
public void should_parse_settings_file_with_context() {
InputStream stream = getResourceAsStream("settings/context-settings.json");
ImmutableList<GlobalSetting> globalSettings = parser.parse(stream);
assertThat(globalSettings.get(0).includes().get(0), is(join("src", "test", "resources... |
protected int calculateDegree(Graph graph, Node n) {
return graph.getDegree(n);
} | @Test
public void testOneNodeDegree() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1);
Graph graph = graphModel.getGraph();
Node n = graph.getNode("0");
Degree d = new Degree();
int degree = d.calculateDegree(graph, n);
assertEquals(degree, 0)... |
public Optional<Violation> validate(IndexSetConfig newConfig) {
// Don't validate prefix conflicts in case of an update
if (Strings.isNullOrEmpty(newConfig.id())) {
final Violation prefixViolation = validatePrefix(newConfig);
if (prefixViolation != null) {
return... | @Test
public void testDataTieringByDefaultDisabledInCloud() {
final IndexSet indexSet = mock(IndexSet.class);
when(indexSet.getIndexPrefix()).thenReturn("foo");
when(indexSetRegistry.iterator()).thenReturn(Collections.singleton(indexSet).iterator());
this.validator = new IndexSetVal... |
@Override
public int read() {
return (mPosition < mLimit) ? (mData[mPosition++] & 0xff) : -1;
} | @Test
void testReadEmptyByteArray() {
Assertions.assertThrows(NullPointerException.class, () -> {
UnsafeByteArrayInputStream stream = new UnsafeByteArrayInputStream("abc".getBytes());
stream.read(null, 0, 1);
});
} |
public static Optional<PrimaryKey> getPrimaryKey(DatabaseMetaData metaData, TablePath tablePath)
throws SQLException {
// According to the Javadoc of java.sql.DatabaseMetaData#getPrimaryKeys,
// the returned primary key columns are ordered by COLUMN_NAME, not by KEY_SEQ.
// We need t... | @Test
void testPrimaryKeysNameWithOutSpecialChar() throws SQLException {
Optional<PrimaryKey> primaryKey =
CatalogUtils.getPrimaryKey(new TestDatabaseMetaData(), TablePath.of("test.test"));
Assertions.assertEquals("testfdawe_", primaryKey.get().getPrimaryKey());
} |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitSSSSameDelimiterAsDefaultValue() {
assertThat(JOrphanUtils.split("a,bc,,", ",", ","), CoreMatchers.equalTo(new String[]{"a", "bc", ",", ","}));
} |
public static String getCityCodeByIdCard(String idcard) {
int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 4);
}
return null;
} | @Test
public void getCityCodeByIdCardTest() {
String codeByIdCard = IdcardUtil.getCityCodeByIdCard(ID_18);
assertEquals("3210", codeByIdCard);
} |
@Override
protected void setProperties(Map<String, String> properties) throws DdlException {
Preconditions.checkState(properties != null);
for (String key : properties.keySet()) {
if (!DRIVER_URL.equals(key) && !URI.equals(key) && !USER.equals(key) && !PASSWORD.equals(key)
... | @Test(expected = DdlException.class)
public void testWithUnknownProperty() throws Exception {
Map<String, String> configs = getMockConfigs();
configs.put("xxx", "xxx");
JDBCResource resource = new JDBCResource("jdbc_resource_test");
resource.setProperties(configs);
} |
@Override
public void cycle() {
if (!getConfig().isWritable()) {
LOG.debug("Not cycling non-writable index set <{}> ({})", getConfig().id(), getConfig().title());
return;
}
int oldTargetNumber;
try {
oldTargetNumber = getNewestIndexNumber();
... | @Test
public void cycleSwitchesIndexAliasToNewTarget() {
final String oldIndexName = config.indexPrefix() + "_0";
final String newIndexName = config.indexPrefix() + "_1";
final String deflector = "graylog_deflector";
final Map<String, Set<String>> indexNameAliases = ImmutableMap.of(
... |
static void handleJvmOptions(String[] args, String lsJavaOpts) {
final JvmOptionsParser parser = new JvmOptionsParser(args[0]);
final String jvmOpts = args.length == 2 ? args[1] : null;
try {
Optional<Path> jvmOptions = parser.lookupJvmOptionsFile(jvmOpts);
parser.handleJ... | @Test
public void givenLS_JAVA_OPTS_containingMultipleDefinitionsWithAlsoMaxOrderThenNoDuplicationOfMaxOrderOptionShouldHappen() throws IOException {
JvmOptionsParser.handleJvmOptions(new String[] {temp.toString()}, "-Xblabla -Dio.netty.allocator.maxOrder=13");
// Verify
final String output... |
@Override
public OAuth2AccessTokenDO grantRefreshToken(String refreshToken, String clientId) {
return oauth2TokenService.refreshAccessToken(refreshToken, clientId);
} | @Test
public void testGrantRefreshToken() {
// 准备参数
String refreshToken = randomString();
String clientId = randomString();
// mock 方法
OAuth2AccessTokenDO accessTokenDO = randomPojo(OAuth2AccessTokenDO.class);
when(oauth2TokenService.refreshAccessToken(eq(refreshToken... |
@Override
public void add(long item, long count) {
if (count < 0) {
// Actually for negative increments we'll need to use the median
// instead of minimum, and accuracy will suffer somewhat.
// Probably makes sense to add an "allow negative increments"
// para... | @Test(expected = IllegalStateException.class)
public void sizeOverflow() {
CountMinSketch sketch = new CountMinSketch(0.0001, 0.99999, 1);
sketch.add(3, Long.MAX_VALUE);
sketch.add(4, 1);
} |
public ImmutableSetMultimap<String, Pipeline> resolveStreamConnections(Map<String, Pipeline> currentPipelines) {
// Read all stream connections of those pipelines to allow processing messages through them
final HashMultimap<String, Pipeline> connections = HashMultimap.create();
try (final var p... | @Test
void resolveStreamConnections() {
final var registry = PipelineMetricRegistry.create(metricRegistry, Pipeline.class.getName(), Rule.class.getName());
final var resolver = new PipelineResolver(
new PipelineRuleParser(new FunctionRegistry(Map.of())),
PipelineResol... |
@Override
public JSONObject getPresetProperties() {
return new JSONObject();
} | @Test
public void getPresetProperties() {
JSONObject jsonObject = mSensorsAPI.getPresetProperties();
Assert.assertEquals(0, jsonObject.length());
} |
public static String formatSql(final AstNode root) {
final StringBuilder builder = new StringBuilder();
new Formatter(builder).process(root, 0);
return StringUtils.stripEnd(builder.toString(), "\n");
} | @Test
public void shouldFormatCreateTableStatementWithExplicitTimestamp() {
// Given:
final CreateSourceProperties props = CreateSourceProperties.from(
new ImmutableMap.Builder<String, Literal>()
.putAll(SOME_WITH_PROPS.copyOfOriginalLiterals())
.put(CommonCreateConfigs.TIMESTA... |
public FEELFnResult<TemporalAccessor> invoke(@ParameterName("from") String val) {
if ( val == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));
}
try {
TemporalAccessor parsed = FEEL_TIME.parse(val);
i... | @Test
void invokeStringParamNotDateOrTime() {
FunctionTestUtil.assertResultError(timeFunction.invoke("test"), InvalidParametersEvent.class);
} |
@Override
public PageResult<CombinationActivityDO> getCombinationActivityPage(CombinationActivityPageReqVO pageReqVO) {
return combinationActivityMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetCombinationActivityPage() {
// mock 数据
CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class, o -> { // 等会查询到
o.setName(null);
//o.setSpuId(null);
o.set... |
static public int convert(ILoggingEvent event) {
Level level = event.getLevel();
switch (level.levelInt) {
case Level.ERROR_INT:
return SyslogConstants.ERROR_SEVERITY;
case Level.WARN_INT:
return SyslogConstants.WARNING_SEVERITY;
case Level.INFO_INT:
... | @Test
public void smoke() {
assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.TRACE)));
assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.DEBUG)));
assertEquals(SyslogConstants.INFO_SEVERIT... |
public static boolean instanceOfBottomNavigationItemView(Object view) {
return ReflectUtil.isInstance(view, "com.google.android.material.bottomnavigation.BottomNavigationItemView", "android.support.design.internal.NavigationMenuItemView");
} | @Test
public void instanceOfBottomNavigationItemView() {
CheckBox textView1 = new CheckBox(mApplication);
textView1.setText("child1");
Assert.assertFalse(SAViewUtils.instanceOfActionMenuItem(textView1));
} |
public AutoDetectParserConfig getAutoDetectParserConfig() {
return autoDetectParserConfig;
} | @Test
public void testAutoDetectParserConfig() throws Exception {
TikaConfig tikaConfig =
new TikaConfig(TikaConfigTest.class.getResourceAsStream("TIKA-3594.xml"));
AutoDetectParserConfig config = tikaConfig.getAutoDetectParserConfig();
assertEquals(12345, config.getSpoolToDi... |
public HtmlCreator title(String title) {
html.append("<title>").append(title).append("</title>");
return this;
} | @Test
public void testTitle() {
htmlCreator.title("Blade");
Assert.assertEquals(true, htmlCreator.html().contains("<title>Blade</title>"));
} |
public static Timestamp previous(Timestamp timestamp) {
if (timestamp.equals(Timestamp.MIN_VALUE)) {
return timestamp;
}
final int nanos = timestamp.getNanos();
final long seconds = timestamp.getSeconds();
if (nanos - 1 >= 0) {
return Timestamp.ofTimeSecondsAndNanos(seconds, nanos - 1);... | @Test
public void testPreviousDecrementsSecondsWhenNanosUnderflow() {
assertEquals(
Timestamp.ofTimeSecondsAndNanos(9L, 999999999),
TimestampUtils.previous(Timestamp.ofTimeSecondsAndNanos(10L, 0)));
} |
@Restricted(NoExternalUse.class)
public static String extractPluginNameFromIconSrc(String iconSrc) {
if (iconSrc == null) {
return "";
}
if (!iconSrc.contains("plugin-")) {
return "";
}
String[] arr = iconSrc.split(" ");
for (String element :... | @Test
public void extractPluginNameFromIconSrcHandlesNull() {
String result = Functions.extractPluginNameFromIconSrc(null);
assertThat(result, is(emptyString()));
} |
@Override
public Path move(final Path file, final Path target, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final EueApiClient client = new EueApiClient(session);
if(status.isExists()) {
... | @Test
public void testMoveFileOverride() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path folder = new EueDirectoryFeature(session, fileid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.direc... |
@ConstantFunction(name = "bitShiftRightLogical", argTypes = {TINYINT, BIGINT}, returnType = TINYINT)
public static ConstantOperator bitShiftRightLogicalTinyInt(ConstantOperator first, ConstantOperator second) {
byte b = first.getTinyInt();
int i = b >= 0 ? b : (((int) b) + 256);
return Const... | @Test
public void bitShiftRightLogicalTinyInt() {
assertEquals(1, ScalarOperatorFunctions.bitShiftRightLogicalTinyInt(O_TI_10, O_BI_3).getTinyInt());
} |
public static Field getField(Class<?> beanClass, String name) throws SecurityException {
final Field[] fields = getFields(beanClass);
return ArrayUtil.firstMatch(field -> name.equals(getFieldName(field)), fields);
} | @Test
public void getFieldTest() {
Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField");
Assert.assertNotNull(privateField);
Field field = ReflectUtil.getField(TestSubClass.class, "field");
Assert.assertNotNull(field);
} |
@VisibleForTesting
static Object convertAvroField(Object avroValue, Schema schema) {
if (avroValue == null) {
return null;
}
switch (schema.getType()) {
case NULL:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
... | @Test(expectedExceptions = UnsupportedOperationException.class,
expectedExceptionsMessageRegExp = "Unsupported avro schema type.*")
public void testNotSupportedAvroTypesRecord() {
BaseJdbcAutoSchemaSink.convertAvroField(new Object(), createFieldAndGetSchema((builder) ->
builder.n... |
protected static boolean isDoubleQuoted(String input) {
if (input == null || input.isBlank()) {
return false;
}
return input.matches("(^" + QUOTE_CHAR + "{2}([^" + QUOTE_CHAR + "]+)" + QUOTE_CHAR + "{2})");
} | @Test
public void testDoubleQuoted() {
assertTrue(isDoubleQuoted("\"\"c:\\program files\\test\\\"\""));
} |
public void insert(String data) {
this.insert(this.root, data);
} | @Test
public void insert() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("abc");
trieTree.insert("abcd");
} |
public static Object del(final ConvertedMap data, final FieldReference field) {
final Object target = findParent(data, field);
if (target instanceof ConvertedMap) {
return ((ConvertedMap) target).remove(field.getKey());
} else {
return target == null ? null : delFromList(... | @Test
public void testDel() throws Exception {
final ConvertedMap data = new ConvertedMap(1);
List<Object> inner = new ConvertedList(1);
data.put("foo", inner);
inner.add("bar");
data.put("bar", "baz");
assertEquals("bar", del(data, "[foo][0]"));
assertNull(d... |
@Override
public void validateInputFilePatternSupported(String filepattern) {
getGcsPath(filepattern);
verifyPath(filepattern);
verifyPathIsAccessible(filepattern, "Could not find file %s");
} | @Test
public void testValidFilePattern() {
validator.validateInputFilePatternSupported("gs://bucket/path");
} |
@Override
public int capacity() {
return capacity;
} | @Test
public void testCapacity() {
assertEquals(CAPACITY, queue.capacity());
} |
@Override
public ContentHandler getNewContentHandler() {
if (type == HANDLER_TYPE.BODY) {
return new BodyContentHandler(
new WriteOutContentHandler(new ToTextContentHandler(), writeLimit,
throwOnWriteLimitReached, parseContext));
} else if (type =... | @Test
public void testBody() throws Exception {
Parser p = new MockParser(OVER_DEFAULT);
BasicContentHandlerFactory.HANDLER_TYPE type = BasicContentHandlerFactory.HANDLER_TYPE.BODY;
ContentHandler handler = new BasicContentHandlerFactory(type, -1).getNewContentHandler();
assertTrue(... |
static void closeSilently(
final ServerWebSocket webSocket,
final int code,
final String message) {
try {
final ImmutableMap<String, String> finalMessage = ImmutableMap.of(
"error",
message != null ? message : ""
);
final String json = ApiJsonMapper.INSTANCE.g... | @Test
public void shouldCloseQuietly() throws Exception {
// Given:
doThrow(new RuntimeException("Boom")).when(websocket)
.close(any(Short.class), any(String.class));
// When:
SessionUtil.closeSilently(websocket, INVALID_MESSAGE_TYPE.code(), "reason");
// Then:
verify(websocket).clo... |
@Override
public void check(final DataSource dataSource) {
try (
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SHOW_VARIABLES_SQL)) {
int parameterIndex = 1;
for (Entry<String, Str... | @Test
void assertCheckVariableWithWrong() throws SQLException {
when(preparedStatement.executeQuery()).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true, true, false);
when(resultSet.getString(1)).thenReturn("BINLOG_FORMAT", "LOG_BIN");
when(resultSet.getString(2)).thenRe... |
@Override
public void removeEdge(E edge) {
checkArgument(edge.src().equals(edge.dst()) ||
edges.indexOf(edge) == 0 ||
edges.lastIndexOf(edge) == edges.size() - 1,
"Edge must be at start or end of path, or it must be a cyclic e... | @Test
public void removeEdge() {
MutablePath<TestVertex, TestEdge> p = new DefaultMutablePath<>();
p.appendEdge(new TestEdge(A, B));
p.appendEdge(new TestEdge(B, C));
p.appendEdge(new TestEdge(C, C));
p.appendEdge(new TestEdge(C, D));
validatePath(p, A, D, 4);
... |
String getServiceDns() {
return serviceDns;
} | @Test
public void propertyServiceNameIsEmpty() {
// given
Map<String, Comparable> properties = createProperties();
properties.put(SERVICE_NAME.key(), " ");
String serviceDns = "service-dns";
properties.put(SERVICE_DNS.key(), serviceDns);
//when
KubernetesCon... |
public PluginDescriptor getDescriptor() {
Iterator<PluginInfo> iterator = this.iterator();
if (!iterator.hasNext()) {
throw new RuntimeException("Cannot get descriptor. Could not find any plugin information.");
}
return iterator.next().getDescriptor();
} | @Test
public void shouldGetDescriptorOfPluginUsingAnyPluginInfo() {
PluginDescriptor descriptor = mock(PluginDescriptor.class);
NotificationPluginInfo notificationPluginInfo = new NotificationPluginInfo(descriptor, null);
PluggableTaskPluginInfo pluggableTaskPluginInfo = new PluggableTaskPl... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendDocument() {
Message message = bot.execute(new SendDocument(chatId, docFileId)).message();
MessageTest.checkMessage(message);
DocumentTest.check(message.document());
message = bot.execute(
new SendDocument(chatId, docBytes).thumb(thumbBy... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeDropStatementsCorrectly() {
Assert.assertEquals("DROP STREAM IF EXISTS stream1 DELETE TOPIC;",
anon.anonymize("DROP STREAM IF EXISTS my_stream DELETE TOPIC;"));
Assert.assertEquals("DROP TABLE IF EXISTS table1 DELETE TOPIC;",
anon.anonymize("DROP TABLE IF EXIST... |
@Override
public String name() {
return store.name();
} | @Test
public void shouldGetNameForVersionedStore() {
givenWrapperWithVersionedStore();
when(versionedStore.name()).thenReturn(STORE_NAME);
assertThat(wrapper.name(), equalTo(STORE_NAME));
} |
public static void checkNullOrNonNullNonEmptyEntries(
@Nullable Collection<String> values, String propertyName) {
if (values == null) {
// pass
return;
}
for (String value : values) {
Preconditions.checkNotNull(
value, "Property '" + propertyName + "' cannot contain null en... | @Test
public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyValueFail() {
try {
Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap("key1", " "), "test");
Assert.fail();
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Property 'test' cannot contain empty st... |
@Override
public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility(
TypeSerializerSnapshot<T> oldSerializerSnapshot) {
if (!(oldSerializerSnapshot instanceof PojoSerializerSnapshot)) {
return TypeSerializerSchemaCompatibility.incompatible();
}
PojoSeria... | @Test
void testResolveSchemaCompatibilityWithNewFields() {
final PojoSerializerSnapshot<TestPojo> oldSnapshot =
buildTestSnapshot(Collections.singletonList(HEIGHT_FIELD));
final PojoSerializerSnapshot<TestPojo> newSnapshot =
buildTestSnapshot(Arrays.asList(ID_FIELD, ... |
@VisibleForTesting
public int getFailApplicationAttemptFailedRetrieved() {
return numFailAppAttemptFailedRetrieved.value();
} | @Test
public void testFailApplicationAttemptFailed() {
long totalBadBefore = metrics.getFailApplicationAttemptFailedRetrieved();
badSubCluster.getFailApplicationAttempt();
Assert.assertEquals(totalBadBefore + 1, metrics.getFailApplicationAttemptFailedRetrieved());
} |
@Bean
public TimeLimiterRegistry timeLimiterRegistry(
TimeLimiterConfigurationProperties timeLimiterConfigurationProperties,
EventConsumerRegistry<TimeLimiterEvent> timeLimiterEventConsumerRegistry,
RegistryEventConsumer<TimeLimiter> timeLimiterRegistryEventConsumer,
@Qualifier("comp... | @Test
public void testCreateTimeLimiterRegistryWithUnknownConfig() {
TimeLimiterConfigurationProperties timeLimiterConfigurationProperties = new TimeLimiterConfigurationProperties();
io.github.resilience4j.common.timelimiter.configuration.CommonTimeLimiterConfigurationProperties.InstanceProperties ... |
public static boolean isBasicInfoChanged(Member actual, Member expected) {
if (null == expected) {
return null != actual;
}
if (!expected.getIp().equals(actual.getIp())) {
return true;
}
if (expected.getPort() != actual.getPort()) {
return true... | @Test
void testIsBasicInfoChangedForMoreBasicExtendInfo() {
Member newMember = buildMember();
newMember.setExtendVal(MemberMetaDataConstants.VERSION, "TEST");
assertTrue(MemberUtil.isBasicInfoChanged(newMember, originalMember));
} |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the fe... | @Test
void testApplyLigaturesCalibri() throws IOException
{
File file = new File("c:/windows/fonts/calibri.ttf");
Assumptions.assumeTrue(file.exists(), "calibri ligature test skipped");
CmapLookup cmapLookup;
GsubWorker gsubWorkerForLatin;
try (TrueTypeFont ttf = new TTF... |
@Override
public boolean isInputConsumable(
SchedulingExecutionVertex executionVertex,
Set<ExecutionVertexID> verticesToDeploy,
Map<ConsumedPartitionGroup, Boolean> consumableStatusCache) {
for (ConsumedPartitionGroup consumedPartitionGroup :
executionVert... | @Test
void testAllFinishedBlockingInput() {
final TestingSchedulingTopology topology = new TestingSchedulingTopology();
final List<TestingSchedulingExecutionVertex> producers =
topology.addExecutionVertices().withParallelism(2).finish();
final List<TestingSchedulingExecutio... |
public void pruneColumns(Configuration conf, Path inputFile, Path outputFile, List<String> cols)
throws IOException {
RewriteOptions options = new RewriteOptions.Builder(conf, inputFile, outputFile)
.prune(cols)
.build();
ParquetRewriter rewriter = new ParquetRewriter(options);
rewrite... | @Test
public void testPruneNestedParentColumn() throws Exception {
// Create Parquet file
String inputFile = createParquetFile("input");
String outputFile = createTempFile("output");
// Remove parent column. All of it's children will be removed.
List<String> cols = Arrays.asList("Links");
col... |
@Override
public boolean hasNext() {
try {
if (iteratorClosed) {
return false;
}
getNextItem();
if (!hasNext) {
close();
}
hasNextMethodCalled = true;
return hasNext;
} catch (SQLExcep... | @Test
void testHasNext() throws SQLException {
try (Connection connection = DriverManager.getConnection(dbConnectionUrl)) {
JoinPredicateScanResultSetIterator<String> iterator = createIterator(connection);
ArrayList<String> tableNameList = new ArrayList<>();
while (iterat... |
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
int seconds = payload.getByteBuf().readInt();
if (0 == seconds) {
return MySQLTimeValueUtils.DATETIME_OF_ZERO;
}
int nanos = columnDef.getColumnMeta() > 0 ? new My... | @Test
void assertReadNullTime() {
when(byteBuf.readInt()).thenReturn(0);
assertThat(new MySQLTimestamp2BinlogProtocolValue().read(columnDef, payload), is(MySQLTimeValueUtils.DATETIME_OF_ZERO));
} |
@Override // mappedStatementId 参数,暂时没有用。以后,可以基于 mappedStatementId + DataPermission 进行缓存
public List<DataPermissionRule> getDataPermissionRule(String mappedStatementId) {
// 1. 无数据权限
if (CollUtil.isEmpty(rules)) {
return Collections.emptyList();
}
// 2. 未配置,则默认开启
D... | @Test
public void testGetDataPermissionRule_05() {
// 准备参数
String mappedStatementId = randomString();
// mock 方法
DataPermissionContextHolder.add(AnnotationUtils.findAnnotation(TestClass05.class, DataPermission.class));
// 调用
List<DataPermissionRule> result = dataPerm... |
@Override
public Map<T, Double> getWeightedSubset(Map<T, Double> weightMap, DeterministicSubsettingMetadata metadata)
{
if (metadata != null)
{
List<T> points = new ArrayList<>(weightMap.keySet());
Collections.sort(points);
Collections.shuffle(points, new Random(_randomSeed));
List<D... | @Test(dataProvider = "uniformWeightData")
public void testDistributionWithUniformWeight(int clientNum, int hostNum, int minSubsetSize)
{
double[] weights = new double[hostNum];
Arrays.fill(weights, 1D);
Map<String, Double> pointsMap = constructPointsMap(weights);
Map<String, Double> distributionMap... |
public void replaceChars(int startPosition, int endPosition, String replacement) {
try {
sourceBuilder.replace(startPosition, endPosition, replacement);
} catch (StringIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException(
String.format(
"Replacement cannot be ma... | @Test
public void replaceChars() {
sourceFile.replaceChars(3, 8, "Sasquatch");
assertThat(sourceFile.getSourceText()).isEqualTo(SOURCE_TEXT.replace("Lorem", "Sasquatch"));
assertThat(sourceFile.getLines().get(0))
.isEqualTo("// Sasquatch ipsum dolor sit amet, consectetur adipisicing elit, sed do")... |
@Override
public Object removeVariable(String name) {
if (variables.containsKey(name)) {
return variables.remove(name);
}
if (parent != null) {
return parent.removeVariable(name);
}
return null;
} | @Test
public void testRemoveVariable() {
ProcessContextImpl context = new ProcessContextImpl();
ProcessContextImpl parentContext = new ProcessContextImpl();
parentContext.setVariable("key", "value");
context.setParent(parentContext);
context.setVariable("key1", "value1");
... |
public void bootstrap(String device, int rootBandwidthMbit, int
yarnBandwidthMbit)
throws ResourceHandlerException {
if (device == null) {
throw new ResourceHandlerException("device cannot be null!");
}
String tmpDirBase = conf.get("hadoop.tmp.dir");
if (tmpDirBase == null) {
th... | @Test
public void testBootstrapRecoveryEnabled() {
conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, true);
TrafficController trafficController = new TrafficController(conf,
privilegedOperationExecutorMock);
try {
//Return a default tc state when attempting to read state
when(pr... |
@Override
public Collection<RejectedAwarePlugin> getRejectedAwarePluginList() {
return mainLock.applyWithReadLock(rejectedAwarePluginList::getPlugins);
} | @Test
public void testGetRejectedAwarePluginList() {
manager.register(new TestRejectedAwarePlugin());
Assert.assertEquals(1, manager.getRejectedAwarePluginList().size());
} |
@Override
public Optional<SimpleAddress> selectAddress(Optional<String> addressSelectionContext)
{
if (addressSelectionContext.isPresent()) {
return addressSelectionContext
.map(HostAndPort::fromString)
.map(SimpleAddress::new);
}
List<... | @Test
public void testAddressSelectionNoContext()
{
InMemoryNodeManager internalNodeManager = new InMemoryNodeManager();
RandomResourceManagerAddressSelector selector = new RandomResourceManagerAddressSelector(internalNodeManager, hostAndPorts -> Optional.of(hostAndPorts.get(0)));
inter... |
public CompletableFuture<Acknowledge> triggerSavepoint(
AsynchronousJobOperationKey operationKey,
String targetDirectory,
SavepointFormatType formatType,
TriggerSavepointMode savepointMode,
Time timeout) {
return registerOperationIdempotently(
... | @Test
public void triggerSavepointRepeatedly() throws ExecutionException, InterruptedException {
CompletableFuture<Acknowledge> firstAcknowledge =
handler.triggerSavepoint(
operationKey,
targetDirectory,
SavepointFormatT... |
void shuffle()
{
close();
clearExclusion();
final Random random = ThreadLocalRandom.current();
for (int i = endpoints.length; --i > -1;)
{
final int j = random.nextInt(i + 1);
final String tmp = endpoints[i];
endpoints[i] = endpoints[j];
... | @Test
void shouldEventuallyGetADifferentOrderAfterShuffle()
{
final String[] originalOrder = Arrays.copyOf(endpoints, endpoints.length);
int differenceCount = 0;
for (int i = 0; i < 100; i++)
{
publicationGroup.shuffle();
differenceCount += !Arrays.equals(... |
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.GET;
} | @Test
void testHttpMethod() {
assertThat(metricsHandlerHeaders.getHttpMethod()).isEqualTo(HttpMethodWrapper.GET);
} |
public <E extends Enum<E>> void logUntetheredSubscriptionStateChange(
final E oldState, final E newState, final long subscriptionId, final int streamId, final int sessionId)
{
final int length = untetheredSubscriptionStateChangeLength(oldState, newState);
final int captureLength = captureLen... | @Test
void logUntetheredSubscriptionStateChange()
{
final int recordOffset = align(192, ALIGNMENT);
logBuffer.putLong(CAPACITY + TAIL_POSITION_OFFSET, recordOffset);
final TimeUnit from = TimeUnit.DAYS;
final TimeUnit to = TimeUnit.NANOSECONDS;
final long subscriptionId =... |
@JsonCreator
public static DataSize parse(CharSequence size) {
return parse(size, DataSizeUnit.BYTES);
} | @Test
void unableParseWrongDataSizeCount() {
assertThatIllegalArgumentException()
.isThrownBy(() -> DataSize.parse("three bytes"))
.withMessage("Invalid size: three bytes");
} |
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
} | @Test
public void compute_duplicated_blocks_one_for_original_one_for_each_InnerDuplicate() {
TextBlock original = new TextBlock(1, 1);
duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(2, 2), new TextBlock(4, 4), new TextBlock(3, 4));
setNewLines(FILE_1);
underTest.execute(new ... |
@Override
public TradePriceCalculateRespBO calculatePrice(TradePriceCalculateReqBO calculateReqBO) {
// 1.1 获得商品 SKU 数组
List<ProductSkuRespDTO> skuList = checkSkuList(calculateReqBO);
// 1.2 获得商品 SPU 数组
List<ProductSpuRespDTO> spuList = checkSpuList(skuList);
// 2.1 计算价格
... | @Test
public void testCalculatePrice() {
// 准备参数
TradePriceCalculateReqBO calculateReqBO = new TradePriceCalculateReqBO()
.setUserId(10L)
.setCouponId(20L).setAddressId(30L)
.setItems(Arrays.asList(
new TradePriceCalculateReqBO.... |
public void register(RegisterRequest request) {
Optional<User> userOptional = userRepository.findByIdentificationNumber(request.getIdentificationNumber());
if (userOptional.isPresent()) {
throw GenericException.builder()
.httpStatus(HttpStatus.BAD_... | @Test
void register_successfulRegistration() {
// Arrange
RegisterRequest request = new RegisterRequest("1234567890", "John", "Doe", "password");
when(userRepository.findByIdentificationNumber(request.getIdentificationNumber())).thenReturn(Optional.empty());
// Act
userServi... |
@NonNull
public static Permutor<FeedItem> getPermutor(@NonNull SortOrder sortOrder) {
Comparator<FeedItem> comparator = null;
Permutor<FeedItem> permutor = null;
switch (sortOrder) {
case EPISODE_TITLE_A_Z:
comparator = (f1, f2) -> itemTitle(f1).compareTo(itemTi... | @Test
public void testPermutorForRule_DATE_ASC() {
Permutor<FeedItem> permutor = FeedItemPermutors.getPermutor(SortOrder.DATE_OLD_NEW);
List<FeedItem> itemList = getTestList();
assertTrue(checkIdOrder(itemList, 1, 3, 2)); // before sorting
permutor.reorder(itemList);
assertT... |
@Override
public void onNewResourcesAvailable() {
checkDesiredOrSufficientResourcesAvailable();
} | @Test
void testSchedulingWithSufficientResourcesAndNoStabilizationTimeout() {
Duration noStabilizationTimeout = Duration.ofMillis(0);
WaitingForResources wfr =
new WaitingForResources(ctx, LOG, Duration.ofSeconds(1000), noStabilizationTimeout);
ctx.setHasDesiredResources(() ... |
public FEELFnResult<Object> invoke(@ParameterName("list") List list) {
if ( list == null || list.isEmpty() ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null or empty"));
} else {
try {
return FEELFnResult.ofResult(C... | @Test
void invokeEmptyArray() {
FunctionTestUtil.assertResultError(maxFunction.invoke(new Object[]{}), InvalidParametersEvent.class);
} |
@Override
public boolean isNeedRewrite(final SQLStatementContext sqlStatementContext) {
return sqlStatementContext instanceof InsertStatementContext
&& ((InsertStatementContext) sqlStatementContext).getGeneratedKeyContext().isPresent()
&& ((InsertStatementContext) sqlStatemen... | @Test
void assertIsNeedRewrite() {
GeneratedKeyInsertValueParameterRewriter paramRewriter = new GeneratedKeyInsertValueParameterRewriter();
SelectStatementContext selectStatementContext = mock(SelectStatementContext.class);
assertFalse(paramRewriter.isNeedRewrite(selectStatementContext));
... |
public void notifyOfError(Throwable error) {
if (error != null && this.error == null) {
this.error = error;
// this should wake up any blocking calls
try {
connectedSocket.close();
} catch (Throwable ignored) {
}
try {
... | @Test
void testIteratorWithException() throws Exception {
final SocketStreamIterator<Long> iterator =
new SocketStreamIterator<>(LongSerializer.INSTANCE);
// asynchronously set an error
new Thread() {
@Override
public void run() {
try... |
public synchronized int sendFetches() {
final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests();
sendFetchesInternal(
fetchRequests,
(fetchTarget, data, clientResponse) -> {
synchronized (Fetcher.this) {
... | @Test
public void testFetchPositionAfterException() {
// verify the advancement in the next fetch offset equals to the number of fetched records when
// some fetched partitions cause Exception. This ensures that consumer won't lose record upon exception
buildFetcher(OffsetResetStrategy.NONE,... |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (statement.getStatement() instanceof CreateSource) {
return handleCreateSource((ConfiguredStatement<CreateSource>) statement);
}
return statem... | @Test
public void shouldInjectMissingValueFormat() {
// Given
givenConfig(ImmutableMap.of(
KsqlConfig.KSQL_DEFAULT_VALUE_FORMAT_CONFIG, "JSON"
));
givenSourceProps(ImmutableMap.of(
"KEY_FORMAT", new StringLiteral("KAFKA")
));
// When
final ConfiguredStatement<?> result = i... |
@PublicAPI(usage = ACCESS)
public JavaClasses importClasses(Class<?>... classes) {
return importClasses(Arrays.asList(classes));
} | @Test
public void imports_enclosing_constructor_of_local_class() throws ClassNotFoundException {
@SuppressWarnings("unused")
class ClassCreatingLocalClassInConstructor {
ClassCreatingLocalClassInConstructor() {
class SomeLocalClass {
}
}
... |
private List<Configserver> getConfigServers(DeployState deployState, TreeConfigProducer<AnyConfigProducer> parent, Element adminE) {
Element configserversE = XML.getChild(adminE, "configservers");
if (configserversE == null) {
Element adminserver = XML.getChild(adminE, "adminserver");
... | @Test
void noAdminServerOrConfigServer() {
Admin admin = buildAdmin(servicesAdminNoAdminServerOrConfigServer());
assertEquals(1, admin.getConfigservers().size());
} |
public static Map<String, PluginConfiguration> load(final File agentRootPath) throws IOException {
return YamlPluginConfigurationLoader.load(new File(agentRootPath, Paths.get("conf", "agent.yaml").toString())).map(YamlPluginsConfigurationSwapper::swap).orElse(Collections.emptyMap());
} | @Test
void assertLoad() throws IOException {
Map<String, PluginConfiguration> actual = PluginConfigurationLoader.load(new File(getResourceURL()));
assertThat(actual.size(), is(3));
assertLoggingPluginConfiguration(actual.get("log_fixture"));
assertMetricsPluginConfiguration(actual.ge... |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
cachedNanoClock.update(nowNs);
dutyCycleTracker.measureAndUpdate(nowNs);
final int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT);
final long shortSendsBefore = shortSen... | @Test
void shouldSendLastDataFrameAsHeartbeatWhenIdle()
{
final StatusMessageFlyweight msg = mock(StatusMessageFlyweight.class);
when(msg.consumptionTermId()).thenReturn(INITIAL_TERM_ID);
when(msg.consumptionTermOffset()).thenReturn(0);
when(msg.receiverWindowLength()).thenReturn... |
@Override
protected String[] getTypeNames() {
return new String[] { TYPE_NAME };
} | @Test
public void getTypeNames() {
assertArrayEquals( new String[] { ElementTransfer.TYPE_NAME }, elementTransfer.getTypeNames() );
} |
Map<String, Object> sourceAdminConfig(String role) {
Map<String, Object> props = new HashMap<>();
props.putAll(originalsWithPrefix(SOURCE_CLUSTER_PREFIX));
props.keySet().retainAll(MirrorClientConfig.CLIENT_CONFIG_DEF.names());
props.putAll(originalsWithPrefix(ADMIN_CLIENT_PREFIX));
... | @Test
public void testSourceAdminConfigWithSourcePrefix() {
String prefix = MirrorConnectorConfig.SOURCE_PREFIX + MirrorConnectorConfig.ADMIN_CLIENT_PREFIX;
Map<String, String> connectorProps = makeProps(prefix + "connections.max.idle.ms", "10000");
MirrorConnectorConfig config = new TestMir... |
public Optional<Object> retrieveSingleValue(final Object jsonObject, final String valueName) {
final Map<String, Object> map = objectMapper.convertValue(jsonObject, new TypeReference<>() {});
return Optional.ofNullable(map.get(valueName));
} | @Test
void testRetrievesSingleValue() {
Optional<Object> value = toTest.retrieveSingleValue(new TestJson(42, "ho!"), "test_string");
assertEquals(Optional.of("ho!"), value);
value = toTest.retrieveSingleValue(new TestJson(42, "ho!"), "test_int");
assertEquals(Optional.of(42), value)... |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldOverrideStreamsConfigProperties() {
Map<String, Object> originals = new HashMap<>();
originals.put(KsqlConfig.KSQL_STREAMS_PREFIX + SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG,
"kafka.jks");
originals.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG,
"https.jks")... |
public AgentConfigurationsTable readAgentConfigurationsTable() {
AgentConfigurationsTable agentConfigurationsTable = new AgentConfigurationsTable();
try {
if (Objects.nonNull(yamlData)) {
Map configurationsData = (Map) yamlData.get("configurations");
if (confi... | @Test
public void testReadAgentConfigurations() {
AgentConfigurationsReader reader = new AgentConfigurationsReader(
this.getClass().getClassLoader().getResourceAsStream("agent-dynamic-configuration.yml"));
Map<String, AgentConfigurations> configurationCache = reader.readAgentConfigurati... |
@Override
public void process(Exchange exchange) throws Exception {
String operation = getOperation(exchange);
switch (operation) {
case GlanceConstants.RESERVE:
doReserve(exchange);
break;
case OpenstackConstants.CREATE:
doCre... | @Test
public void uploadWithUpdatingTest() throws Exception {
final String newName = "newName";
dummyImage.setName(newName);
when(osImage.getName()).thenReturn(newName);
msg.setHeader(OpenstackConstants.OPERATION, GlanceConstants.UPLOAD);
final String id = "id";
msg.s... |
public void processAg31(Ag31 ag31, Afnemersbericht afnemersbericht){
String aNummer = CategorieUtil.findANummer(ag31.getCategorie());
String bsn = CategorieUtil.findBsn(ag31.getCategorie());
digidXClient.setANummer(bsn, aNummer);
if(ag31.getStatus() != null && ag31.getDatum() != null){... | @Test
public void testProcessAg31StatusA(){
String testBsn = "SSSSSSSSS";
Ag31 testAg31 = TestDglMessagesUtil.createTestAg31(testBsn, "A", "SSSSSSSS");
classUnderTest.processAg31(testAg31, afnemersbericht);
verify(digidXClient, times(1)).setANummer(testBsn,"A" + testBsn);
v... |
public void validate(ExternalIssueReport report, Path reportPath) {
if (report.rules != null && report.issues != null) {
Set<String> ruleIds = validateRules(report.rules, reportPath);
validateIssuesCctFormat(report.issues, ruleIds, reportPath);
} else if (report.rules == null && report.issues != nul... | @Test
public void validate_whenMissingMandatoryCleanCodeAttributeField_shouldThrowException() throws IOException {
ExternalIssueReport report = read(REPORTS_LOCATION);
report.rules[0].cleanCodeAttribute = null;
assertThatThrownBy(() -> validator.validate(report, reportPath))
.isInstanceOf(IllegalSt... |
@Override
public String generateSqlType(Dialect dialect) {
return switch (dialect.getId()) {
case MsSql.ID -> "VARBINARY(MAX)";
case Oracle.ID, H2.ID -> "BLOB";
case PostgreSql.ID -> "BYTEA";
default -> throw new IllegalArgumentException("Unsupported dialect id " + dialect.getId());
};... | @Test
public void generateSqlType_for_Oracle() {
assertThat(underTest.generateSqlType(new Oracle())).isEqualTo("BLOB");
} |
public Response<AiMessage> execute( String input, List<IntermediateStep> intermediateSteps ) {
var userMessageTemplate = PromptTemplate.from( "{{input}}" )
.apply( mapOf( "input", input));
var messages = new ArrayList<ChatMessage>();
messages... | @Test
public void runAgentTest() throws Exception {
assertTrue(DotEnvConfig.valueOf("OPENAI_API_KEY").isPresent());
var chatLanguageModel = OpenAiChatModel.builder()
.apiKey( DotEnvConfig.valueOf("OPENAI_API_KEY").get() )
.modelName( "gpt-3.5-turbo-0613" )
... |
@SuppressWarnings("unchecked")
@Override
public void handle(LogHandlerEvent event) {
switch (event.getType()) {
case APPLICATION_STARTED:
LogHandlerAppStartedEvent appStartedEvent =
(LogHandlerAppStartedEvent) event;
this.appOwners.put(appStartedEvent.getApplicationId(),
... | @Test
public void testDelayedDelete() throws IOException {
File[] localLogDirs = getLocalLogDirFiles(this.getClass().getName(), 2);
String localLogDirsString =
localLogDirs[0].getAbsolutePath() + ","
+ localLogDirs[1].getAbsolutePath();
conf.set(YarnConfiguration.NM_LOG_DIRS, localLog... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.