focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Optional<IntentProcessPhase> execute() {
try {
List<Intent> compiled = processor.compile(data.intent(),
//TODO consider passing an optional here in the future
stored.map(IntentData::installables).orElse(null));
return Optional.... | @Test
public void testWhenIntentCompilationExceptionOccurs() {
IntentData pending = new IntentData(input, INSTALL_REQ, version);
expect(processor.compile(input, null)).andThrow(new IntentCompilationException());
replay(processor);
Compiling sut = new Compiling(processor, pending, O... |
public Method methodDefinition() {
return method;
} | @Test
public void server_dispatches_log_messages_from_log_request() {
List<LogMessage> messages = List.of(MESSAGE_1, MESSAGE_2);
LogDispatcher logDispatcher = mock(LogDispatcher.class);
try (RpcServer server = new RpcServer(0)) {
server.addMethod(new ArchiveLogMessagesMethod(logD... |
@Override
public String pluginNamed() {
return PluginEnum.LOGGING_PULSAR.getName();
} | @Test
public void testPluginNamed() {
Assertions.assertEquals(loggingPulsarPluginDataHandler.pluginNamed(), "loggingPulsar");
} |
@Override
public List<Feature> get() {
List<URI> featurePaths = featureOptions.getFeaturePaths();
List<Feature> features = loadFeatures(featurePaths);
if (features.isEmpty()) {
if (featurePaths.isEmpty()) {
log.warn(() -> "Got no path to feature directory or featu... | @Test
void logs_message_if_no_features_are_found(LogRecordListener logRecordListener) {
Options featureOptions = () -> singletonList(FeaturePath.parse("classpath:io/cucumber/core/options"));
FeaturePathFeatureSupplier supplier = new FeaturePathFeatureSupplier(classLoader, featureOptions, parser);
... |
public static ValueReference createParameter(String value) {
return ValueReference.builder()
.valueType(ValueType.PARAMETER)
.value(value)
.build();
} | @Test
public void deserializeParameter() throws IOException {
assertThat(objectMapper.readValue("{\"@type\":\"parameter\",\"@value\":\"Test\"}", ValueReference.class)).isEqualTo(ValueReference.createParameter("Test"));
assertThatThrownBy(() -> objectMapper.readValue("{\"@type\":\"parameter\",\"@valu... |
@Udf(description = "Converts a string representation of a date in the given format"
+ " into the TIMESTAMP value."
+ " Single quotes in the timestamp format can be escaped with '',"
+ " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.")
public Timestamp parseTimestamp(
@UdfParameter(
descrip... | @Test
public void shouldSupportEmbeddedChars() throws ParseException {
// When:
final Object result = udf.parseTimestamp("2021-12-01T12:10:11.123Fred",
"yyyy-MM-dd'T'HH:mm:ss.SSS'Fred'");
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Fred'");
sdf.setTimeZone(Tim... |
@Override
public Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer) {
return update(transactionTemplate, jdbcTemplate, modifyRequests, consumer);
} | @Test
void testUpdate4() {
List<ModifyRequest> modifyRequests = new ArrayList<>();
ModifyRequest modifyRequest1 = new ModifyRequest();
String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;";
modifyRequest1.setSql(sql);
Object[] args = new Object[] {1};
m... |
public static String camelCaseToUnderScore(String key) {
if (key.isEmpty())
return key;
StringBuilder sb = new StringBuilder(key.length());
for (int i = 0; i < key.length(); i++) {
char c = key.charAt(i);
if (Character.isUpperCase(c))
sb.appen... | @Test
public void testCamelCaseToUnderscore() {
assertEquals("test_case", Helper.camelCaseToUnderScore("testCase"));
assertEquals("test_case_t_b_d", Helper.camelCaseToUnderScore("testCaseTBD"));
assertEquals("_test_case", Helper.camelCaseToUnderScore("TestCase"));
assertEquals("_tes... |
public static HttpRequest toNettyRequest(RestRequest request) throws Exception
{
HttpMethod nettyMethod = HttpMethod.valueOf(request.getMethod());
URL url = new URL(request.getURI().toString());
String path = url.getFile();
// RFC 2616, section 5.1.2:
// Note that the absolute path cannot be emp... | @Test
public void testStreamToNettyRequestContentLengthIgnoreCase() throws Exception
{
StreamRequestBuilder streamRequestBuilder = new StreamRequestBuilder(new URI(ANY_URI));
streamRequestBuilder.setHeader("CONTENT-LENGTH", Integer.toString(ANY_ENTITY.length()));
StreamRequest streamRequest = streamRequ... |
static ColumnExtractor create(final Column column) {
final int index = column.index();
Preconditions.checkArgument(index >= 0, "negative index: " + index);
return column.namespace() == Namespace.KEY
? new KeyColumnExtractor(index)
: new ValueColumnExtractor(index);
} | @Test
public void shouldExtractKeyColumn() {
// Given:
when(column.namespace()).thenReturn(Namespace.KEY);
when(column.index()).thenReturn(0);
when(key.get(0)).thenReturn("some value");
final ColumnExtractor extractor = TimestampColumnExtractors.create(column);
// When:
final Object res... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void editMessageText() {
String text = "Update " + System.currentTimeMillis();
BaseResponse response = bot.execute(new EditMessageText(chatId, 925, text)
.parseMode(ParseMode.Markdown)
.disableWebPagePreview(true)
.replyMarkup(new InlineK... |
@Override
public String toString() {
return "QJM to " + loggers;
} | @Test
public void testToString() throws Exception {
GenericTestUtils.assertMatches(
qjm.toString(),
"QJM to \\[127.0.0.1:\\d+, 127.0.0.1:\\d+, 127.0.0.1:\\d+\\]");
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof NiciraSetNshSpi) {
NiciraSetNshSpi that = (NiciraSetNshSpi) obj;
return Objects.equals(nshSpi, that.nshSpi);
}
return false;
} | @Test
public void testEquals() {
new EqualsTester().addEqualityGroup(nshSpi1, sameAsNshSpi1).addEqualityGroup(nshSpi2).testEquals();
} |
@Override
public Object toConnectRow(final Object ksqlData) {
if (!(ksqlData instanceof Struct)) {
return ksqlData;
}
final Schema schema = getSchema();
final Struct struct = new Struct(schema);
Struct originalData = (Struct) ksqlData;
Schema originalSchema = originalData.schema();
... | @Test
public void shouldThrowIfExtraFieldNotOptionalOrDefault() {
// Given:
final Schema schema = SchemaBuilder.struct()
.field("f1", SchemaBuilder.OPTIONAL_STRING_SCHEMA)
.field("f2", SchemaBuilder.OPTIONAL_INT32_SCHEMA)
.field("f3", SchemaBuilder.OPTIONAL_INT64_SCHEMA)
.field... |
@VisibleForTesting
static List<Set<PlanFragmentId>> extractPhases(Collection<PlanFragment> fragments)
{
// Build a graph where the plan fragments are vertexes and the edges represent
// a before -> after relationship. For example, a join hash build has an edge
// to the join probe.
... | @Test
public void testJoinWithDeepSources()
{
PlanFragment buildSourceFragment = createTableScanPlanFragment("buildSource");
PlanFragment buildMiddleFragment = createExchangePlanFragment("buildMiddle", buildSourceFragment);
PlanFragment buildTopFragment = createExchangePlanFragment("buil... |
@Override
public DataNodeDto startNode(String nodeId) throws NodeNotFoundException {
final DataNodeDto node = nodeService.byNodeId(nodeId);
if (node.getDataNodeStatus() != DataNodeStatus.UNAVAILABLE && node.getDataNodeStatus() != DataNodeStatus.PREPARED) {
throw new IllegalArgumentExcep... | @Test
public void startNodeFailsWhenNodeNotStopped() throws NodeNotFoundException {
final String testNodeId = "node";
nodeService.registerServer(buildTestNode(testNodeId, DataNodeStatus.AVAILABLE));
Exception e = assertThrows(IllegalArgumentException.class, () -> {
classUnderTest... |
@Override
public Predicate negate() {
return new GreaterLessPredicate(attributeName, value, !equal, !less);
} | @Test
public void negate_whenEqualsFalseAndLessTrue_thenReturnNewInstanceWithEqualsTrueAndLessFalse() {
String attribute = "attribute";
Comparable value = 1;
GreaterLessPredicate original = new GreaterLessPredicate(attribute, value, false, true);
GreaterLessPredicate negate = (Great... |
public static String getAddress(ECKeyPair ecKeyPair) {
return getAddress(ecKeyPair.getPublicKey());
} | @Test
public void testGetAddressString() {
assertEquals(Keys.getAddress(SampleKeys.PUBLIC_KEY_STRING), (SampleKeys.ADDRESS_NO_PREFIX));
} |
public synchronized T getConfig(String configId) {
try (ConfigSubscriber subscriber = new ConfigSubscriber()) {
ConfigHandle<T> handle = subscriber.subscribe(clazz, configId);
subscriber.nextConfig(true);
return handle.getConfig();
}
} | @Test
public void testsStaticGetConfig() {
int times = 11;
String message = "testGetConfig";
String a0 = "a0";
String configId = "raw:times " + times + "\nmessage " + message + "\na[1]\na[0].name " + a0;
AppConfig config = ConfigGetter.getConfig(AppConfig.class, configId);
... |
public static String generateDatabaseId(String baseString) {
checkArgument(baseString.length() != 0, "baseString cannot be empty!");
String databaseId =
generateResourceId(
baseString,
ILLEGAL_DATABASE_CHARS,
REPLACE_DATABASE_CHAR,
MAX_DATABASE_ID_LENGTH,... | @Test
public void testGenerateDatabaseIdShouldReplaceNonLetterFirstCharWithLetter() {
String testBaseString = "0_database";
String actual = generateDatabaseId(testBaseString);
assertThat(actual).matches("[a-z]_datab_\\d{8}_\\d{6}_\\d{6}");
} |
@Override
public CurrentStateInformation trigger(MigrationStep step, Map<String, Object> args) {
context.setCurrentStep(step);
if (Objects.nonNull(args) && !args.isEmpty()) {
context.addActionArguments(step, args);
}
String errorMessage = null;
try {
s... | @Test
public void smThrowsErrorOnWrongArgumentType() {
StateMachine<MigrationState, MigrationStep> stateMachine = testStateMachineWithAction((context) -> {
context.getActionArgument("k1", Integer.class);
});
migrationStateMachine = new MigrationStateMachineImpl(stateMachine, pers... |
public void createPartitionMetadataTable() {
List<String> ddl = new ArrayList<>();
if (this.isPostgres()) {
// Literals need be added around literals to preserve casing.
ddl.add(
"CREATE TABLE \""
+ tableName
+ "\"(\""
+ COLUMN_PARTITION_TOKEN
... | @Test
public void testCreatePartitionMetadataTableWithTimeoutException() throws Exception {
when(op.get(10, TimeUnit.MINUTES)).thenThrow(new TimeoutException(TIMED_OUT));
try {
partitionMetadataAdminDao.createPartitionMetadataTable();
fail();
} catch (SpannerException e) {
assertTrue(e.g... |
@Override
public int read(long position, byte[] buffer, int offset, int length)
throws IOException {
// When bufferedPreadDisabled = true, this API does not use any shared buffer,
// cursor position etc. So this is implemented as NOT synchronized. HBase
// kind of random reads on a shared file input... | @Test
public void testOlderReadAheadFailure() throws Exception {
AbfsClient client = getMockAbfsClient();
AbfsRestOperation successOp = getMockRestOp();
// Stub :
// First Read request leads to 3 readahead calls: Fail all 3 readahead-client.read()
// A second read request will see that readahead ... |
@Override
public HttpHeaders set(HttpHeaders headers) {
if (headers instanceof DefaultHttpHeaders) {
this.headers.set(((DefaultHttpHeaders) headers).headers);
return this;
} else {
return super.set(headers);
}
} | @Test
public void testSetNullHeaderValueNotValidate() {
final HttpHeaders headers = new DefaultHttpHeaders(false);
assertThrows(NullPointerException.class, new Executable() {
@Override
public void execute() {
headers.set(of("test"), (CharSequence) null);
... |
@Override
public long position() throws IOException {
return delegate.position();
} | @Test
public void testPosition() throws IOException {
int newPosition = 5;
channelUnderTest.position(newPosition);
assertEquals(newPosition, delegate.position());
assertEquals(newPosition, channelUnderTest.position());
} |
@Override
protected int command() {
if (!validateConfigFilePresent()) {
return 1;
}
final MigrationConfig config;
try {
config = MigrationConfig.load(getConfigFile());
} catch (KsqlException | MigrationException e) {
LOGGER.error(e.getMessage());
return 1;
}
retur... | @Test
public void shouldCleanMigrationsStreamAndTable() {
// When:
final int status = command.command(config, cfg -> client);
// Then:
assertThat(status, is(0));
verify(client).executeStatement("TERMINATE " + CTAS_QUERY_ID + ";");
verify(client).executeStatement("DROP TABLE " + MIGRATIONS_TA... |
@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
&& (node.has("minLength") || node.has("maxLength"))
&& isApplicableType(field... | @Test
public void testMaxAndMinLengthGenericsOnType() {
when(config.isIncludeJsr303Annotations()).thenReturn(true);
final int minValue = new Random().nextInt();
final int maxValue = new Random().nextInt();
JsonNode maxSubNode = Mockito.mock(JsonNode.class);
when(subNode.asInt... |
public static void trimRecordTemplate(RecordTemplate recordTemplate, MaskTree override, final boolean failOnMismatch)
{
trimRecordTemplate(recordTemplate.data(), recordTemplate.schema(), override, failOnMismatch);
} | @Test
public void testOverrideMask() throws CloneNotSupportedException
{
RecordBar bar = new RecordBar();
bar.setLocation("mountain view");
bar.data().put("SF", "CA");
RecordBar expected = bar.clone();
MaskTree maskTree = new MaskTree();
maskTree.addOperation(new PathSpec("SF"), MaskOperati... |
public boolean checkPermission(String user, List<String> groups, AclAction action) {
return getPermission(user, groups).contains(action);
} | @Test
public void checkPermission() {
AccessControlList acl = new AccessControlList();
setPermissions(acl);
assertTrue(checkMode(acl, OWNING_USER, Collections.emptyList(), Mode.Bits.ALL));
assertTrue(checkMode(acl, NAMED_USER, Collections.emptyList(), Mode.Bits.READ_EXECUTE));
assertFalse(checkM... |
public double parseDouble(String name) {
return Double.parseDouble(getProperties().getProperty(name));
} | @Test
public void testParseDouble() {
System.out.println("parseDouble");
double expResult;
double result;
Properties props = new Properties();
props.put("value1", "12345.6789");
props.put("value2", "-9000.001");
props.put("empty", "");
props.put("str"... |
public ApiClient createApiClient(@NonNull String baseUrl, String token, String truststoreLocation)
throws MalformedURLException, SSLException {
WebClient webClient = createWebClient(baseUrl, token, truststoreLocation);
ApiClient apiClient = new ApiClient(webClient);
if (token != null && !token.isEmpty... | @Test
public void testSetClientNameCalled() throws Exception {
ArgumentCaptor<String> clientNameCapture = ArgumentCaptor.forClass(String.class);
tablesApiClientFactorySpy.setClientName("trino");
tablesApiClientFactorySpy.createApiClient(
"https://test.openhouse.com", "", tmpCert.getAbsolutePath()... |
void handleFinish(HttpResponse response, Span span) {
if (response == null) throw new NullPointerException("response == null");
if (span == null) throw new NullPointerException("span == null");
if (span.isNoop()) return;
if (response.error() != null) {
span.error(response.error()); // Ensures Mut... | @Test void handleFinish_nothingOnNoop() {
when(span.isNoop()).thenReturn(true);
handler.handleFinish(response, span);
verify(span, never()).finish();
} |
public int getListReservationFailedRetrieved() {
return numListReservationFailedRetrieved.value();
} | @Test
public void testGetListReservationRetrievedFailed() {
long totalBadBefore = metrics.getListReservationFailedRetrieved();
badSubCluster.getListReservationFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getListReservationFailedRetrieved());
} |
public static String unescape(String str) {
if (str == null) {
return null;
}
int len = str.length();
StringWriter writer = new StringWriter(len);
StringBuilder unicode = new StringBuilder(4);
boolean hadSlash = false;
boolean inUnicode = false;
... | @Test
public void testUnescapeThrow() {
Assertions.assertThrows(JsonPathException.class, () -> Utils.unescape("\\uuuuu"));
} |
@Override
public ConfigOperateResult insertOrUpdateBeta(final ConfigInfo configInfo, final String betaIps, final String srcIp,
final String srcUser) {
if (findConfigInfo4BetaState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()) == null) {
return addConfigInfo4B... | @Test
void testInsertOrUpdateBetaOfUpdate() {
String dataId = "betaDataId113";
String group = "group";
String tenant = "tenant";
//mock exist beta
ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper();
mockedConfigInfoStateWrapper.setDataI... |
public TypeDescriptor<T> getEncodedTypeDescriptor() {
return (TypeDescriptor<T>)
TypeDescriptor.of(getClass()).resolveType(new TypeDescriptor<T>() {}.getType());
} | @Test
public void testTypeIsPreserved() throws Exception {
assertThat(VoidCoder.of().getEncodedTypeDescriptor(), equalTo(TypeDescriptor.of(Void.class)));
} |
public static HCatSchema getTableSchemaWithPtnCols(Table table) throws IOException {
HCatSchema tableSchema = new HCatSchema(HCatUtil.getHCatFieldSchemaList(table.getCols()));
if (table.getPartitionKeys().size() != 0) {
// add partition keys to table schema
// NOTE : this assumes that we do not ev... | @Test
public void testGetTableSchemaWithPtnColsApi() throws IOException {
// Check the schema of a table with one field & no partition keys.
StorageDescriptor sd = new StorageDescriptor(
Lists.newArrayList(new FieldSchema("username", serdeConstants.STRING_TYPE_NAME, null)),
"location", "org.ap... |
public static CurlOption parse(String cmdLine) {
List<String> args = ShellWords.parse(cmdLine);
URI url = null;
HttpMethod method = HttpMethod.PUT;
List<Entry<String, String>> headers = new ArrayList<>();
Proxy proxy = NO_PROXY;
while (!args.isEmpty()) {
Str... | @Test
public void must_provide_a_valid_uri() {
String uri = "'https://example.com/path with spaces'";
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> CurlOption.parse(uri));
assertThat(exception.getCause(), instanceOf(URISyntaxException.class));
} |
@Override
public ChannelFuture writePushPromise(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
Http2Headers headers, int padding, ChannelPromise promise) {
try {
if (connection.goAwayReceived()) {
throw connectionError(PROTOCOL_ERROR, "Sending PUSH_PRO... | @Test
public void pushPromiseWriteShouldReserveStream() throws Exception {
createStream(STREAM_ID, false);
ChannelPromise promise = newPromise();
encoder.writePushPromise(ctx, STREAM_ID, PUSH_STREAM_ID, EmptyHttp2Headers.INSTANCE, 0, promise);
assertEquals(RESERVED_LOCAL, stream(PUSH... |
public static void getSemanticPropsSingleFromString(
SingleInputSemanticProperties result,
String[] forwarded,
String[] nonForwarded,
String[] readSet,
TypeInformation<?> inType,
TypeInformation<?> outType) {
getSemanticPropsSingleFromStrin... | @Test
void testNonForwardedInvalidString() {
String[] nonForwardedFields = {"notValid"};
SingleInputSemanticProperties sp = new SingleInputSemanticProperties();
assertThatThrownBy(
() ->
SemanticPropUtil.getSemanticPropsSingleFromString... |
@ScalarOperator(GREATER_THAN_OR_EQUAL)
@SqlType(StandardTypes.BOOLEAN)
public static boolean greaterThanOrEqual(@SqlType(StandardTypes.TINYINT) long left, @SqlType(StandardTypes.TINYINT) long right)
{
return left >= right;
} | @Test
public void testGreaterThanOrEqual()
{
assertFunction("TINYINT'37' >= TINYINT'37'", BOOLEAN, true);
assertFunction("TINYINT'37' >= TINYINT'17'", BOOLEAN, true);
assertFunction("TINYINT'17' >= TINYINT'37'", BOOLEAN, false);
assertFunction("TINYINT'17' >= TINYINT'17'", BOOLEA... |
@Override protected String propagationField(String keyName) {
if (keyName == null) throw new NullPointerException("keyName == null");
Key<String> key = nameToKey.get(keyName);
if (key == null) {
assert false : "We currently don't support getting headers except propagation fields";
return null;
... | @Test void propagationField_lastValue() {
headers.put(b3Key, "0");
headers.put(b3Key, "1");
assertThat(request.propagationField("b3")).isEqualTo("1");
} |
public static <UserT, DestinationT, OutputT> WriteFiles<UserT, DestinationT, OutputT> to(
FileBasedSink<UserT, DestinationT, OutputT> sink) {
checkArgument(sink != null, "sink can not be null");
return new AutoValue_WriteFiles.Builder<UserT, DestinationT, OutputT>()
.setSink(sink)
.setComp... | @Test
@Category(NeedsRunner.class)
public void testUnboundedNeedsWindowed() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(
"Must use windowed writes when applying WriteFiles to an unbounded PCollection");
SimpleSink<Void> sink = makeSimpleSink();
p.apply(Create.of("f... |
@Override
public Rule getByKey(RuleKey key) {
verifyKeyArgument(key);
ensureInitialized();
Rule rule = rulesByKey.get(key);
checkArgument(rule != null, "Can not find rule for key %s. This rule does not exist in DB", key);
return rule;
} | @Test
public void first_call_to_getByKey_triggers_call_to_db_and_any_subsequent_get_or_find_call_does_not() {
underTest.getByKey(AB_RULE.getKey());
verify(ruleDao, times(1)).selectAll(any(DbSession.class));
verifyNoMethodCallTriggersCallToDB();
} |
@VisibleForTesting
void validateMenu(Long parentId, String name, Long id) {
MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name);
if (menu == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的菜单
if (id == null) {
throw exception(MENU_NAME_DUPLI... | @Test
public void testValidateMenu_success() {
// mock 父子菜单
MenuDO sonMenu = createParentAndSonMenu();
// 准备参数
Long parentId = sonMenu.getParentId();
Long otherSonMenuId = randomLongId();
String otherSonMenuName = randomString();
// 调用,无需断言
menuServic... |
@Override
public URL getUrl() {
return channel.getUrl();
} | @Test
void getUrlTest() {
Assertions.assertEquals(header.getUrl(), URL.valueOf("dubbo://localhost:20880"));
} |
public static int checkLessThan(int n, int expected, String name)
{
if (n >= expected)
{
throw new IllegalArgumentException(name + ": " + n + " (expected: < " + expected + ')');
}
return n;
} | @Test
public void checkLessThanMustPassIfArgumentIsLessThanExpected()
{
final int n = 0;
final int actual = RangeUtil.checkLessThan(n, 1, "var");
assertThat(actual, is(equalTo(n)));
} |
protected void initializeXulMenu( Document doc, List<StepMeta> selection, StepMeta stepMeta ) throws KettleException {
XulMenuitem item = (XulMenuitem) doc.getElementById( "trans-graph-entry-newhop" );
int sels = selection.size();
item.setDisabled( sels != 2 );
item = (XulMenuitem) doc.getElementById( ... | @SuppressWarnings( "unchecked" )
@Test
public void testInitializeXulMenu() throws KettleException {
StepMeta stepMeta = mock( StepMeta.class );
TransGraph transGraph = mock( TransGraph.class );
TransMeta transMeta = mock( TransMeta.class );
Document document = mock( Document.class );
XulMenuitem... |
@Override
public VersionedRecord<V> get(final K key) {
final ValueAndTimestamp<V> valueAndTimestamp = internal.get(key);
return valueAndTimestamp == null
? null
: new VersionedRecord<>(valueAndTimestamp.value(), valueAndTimestamp.timestamp());
} | @Test
public void shouldThrowNullPointerOnGetIfKeyIsNull() {
assertThrows(NullPointerException.class, () -> store.get(null));
} |
@Override
public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner)
throws Exception {
privateToPublic = getAddresses.call();
Set<Address> addresses = privateToPublic.keySet();
listenerRunner.onPossibleAddressesCollected(addresses);
return new... | @Test
public void testLoadAddresses() throws Exception {
RemoteAddressProvider provider = new RemoteAddressProvider(() -> expectedAddresses, true);
Collection<Address> addresses = provider.loadAddresses(createConnectionProcessListenerRunner()).primary();
assertEquals(3, addresses.size());
... |
public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException {
UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream)));
return parser.parse();
} | @Test
public void testParseIssue85() throws IOException {
UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(
UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue85.diff"));
assertThat(diff.getFiles().size()).isEqualTo(1);
assertEquals(1, diff.getFiles().s... |
@Override
public SocialUserDO getSocialUser(Long id) {
return socialUserMapper.selectById(id);
} | @Test
public void testGetSocialUser_id() {
// mock 数据
SocialUserDO socialUserDO = randomPojo(SocialUserDO.class);
socialUserMapper.insert(socialUserDO);
// 参数准备
Long id = socialUserDO.getId();
// 调用
SocialUserDO dbSocialUserDO = socialUserService.getSocialUse... |
@Override
public void reset() {
super.reset();
this.minDeltaInCurrentBlock = Long.MAX_VALUE;
} | @Test
public void shouldReset() throws IOException {
shouldReadWriteWhenDataIsNotAlignedWithBlock();
long[] data = new long[5 * blockSize];
for (int i = 0; i < blockSize * 5; i++) {
data[i] = i * 2;
}
writer.reset();
shouldWriteAndRead(data);
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldReturnStatementUnchangedIfHasKeySchemaAndValueFormatNotSupported() {
// Given:
givenKeyButNotValueInferenceSupported();
when(cs.getElements()).thenReturn(SOME_KEY_ELEMENTS_STREAM);
// When:
final ConfiguredStatement<?> result = injector.inject(csStatement);
// Then:
... |
public void runOnStateAppliedFilters(Job job) {
new JobPerformingFilters(job, jobDefaultFilters).runOnStateAppliedFilters();
} | @Test
void jobFiltersAreNotAppliedIfJobHasNoStateChange() {
// GIVEN
Job aJob = anEnqueuedJob().build();
aJob.startProcessingOn(backgroundJobServer);
aJob.getStateChangesForJobFilters(); // clear
// WHEN
aJob.updateProcessing();
jobFilterUtils.runOnStateAppl... |
@Override
public HttpRestResult<String> httpGet(String path, Map<String, String> headers, Map<String, String> paramValues,
String encode, long readTimeoutMs) throws Exception {
final long endTime = System.currentTimeMillis() + readTimeoutMs;
String currentServerAddr = serverListMgr.getCu... | @Test
void testHttpGetFailed() throws Exception {
assertThrows(ConnectException.class, () -> {
when(nacosRestTemplate.<String>get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class),
any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult);
... |
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the"
+ " string representation of the timestamp in the given format. Single quotes in the"
+ " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'."
+ " The system default time zon... | @Test
public void testTimeZoneInUniversalTime() {
// Given:
final long timestamp = 1534353043000L;
// When:
final String universalTime = udf.timestampToString(timestamp,
"yyyy-MM-dd HH:mm:ss zz", "UTC");
// Then:
assertThat(universalTime, is("2018-08-15 17:10:43 UTC"));
} |
public B loadbalance(String loadbalance) {
this.loadbalance = loadbalance;
return getThis();
} | @Test
void loadbalance() {
MethodBuilder builder = new MethodBuilder();
builder.loadbalance("mockloadbalance");
Assertions.assertEquals("mockloadbalance", builder.build().getLoadbalance());
} |
public static Comparator<Object[]> getComparator(List<OrderByExpressionContext> orderByExpressions,
ColumnContext[] orderByColumnContexts, boolean nullHandlingEnabled) {
return getComparator(orderByExpressions, orderByColumnContexts, nullHandlingEnabled, 0, orderByExpressions.size());
} | @Test
public void testAscNullsLast() {
List<OrderByExpressionContext> orderBys =
Collections.singletonList(new OrderByExpressionContext(COLUMN1, ASC, NULLS_LAST));
setUpSingleColumnRows();
_rows.sort(OrderByComparatorFactory.getComparator(orderBys, ENABLE_NULL_HANDLING));
assertEquals(extrac... |
@ApiOperation(value = "Get Tenant Entity Views (getTenantEntityViews)",
notes = "Returns a page of entity views owned by tenant. " + ENTITY_VIEW_DESCRIPTION +
PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = ... | @Test
public void testGetTenantEntityViews() throws Exception {
List<ListenableFuture<EntityViewInfo>> entityViewInfoFutures = new ArrayList<>(178);
for (int i = 0; i < 178; i++) {
ListenableFuture<EntityView> entityViewFuture = getNewSavedEntityViewAsync("Test entity view" + i);
... |
public static int fromLogical(Schema schema, java.util.Date value) {
if (!(LOGICAL_NAME.equals(schema.name())))
throw new DataException("Requested conversion of Time object but the schema does not match.");
Calendar calendar = Calendar.getInstance(UTC);
calendar.setTime(value);
... | @Test
public void testFromLogicalInvalidHasDateComponents() {
assertThrows(DataException.class,
() -> Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_DATE_COMPONENT.getTime()));
} |
public Expression rewrite(final Expression expression) {
return new ExpressionTreeRewriter<>(new OperatorPlugin()::process)
.rewrite(expression, null);
} | @Test
public void shouldReplaceComparisonOfWindowStartAndString() {
// Given:
final Expression predicate = getPredicate(
"SELECT * FROM orders where WINDOWSTART > '2017-01-01T00:00:00.000';");
// When:
final Expression rewritten = rewriter.rewrite(predicate);
// Then:
assertThat(rewr... |
public NearCacheConfig setInMemoryFormat(InMemoryFormat inMemoryFormat) {
this.inMemoryFormat = isNotNull(inMemoryFormat, "inMemoryFormat");
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testSetInMemoryFormat_withString_whenNull() {
config.setInMemoryFormat((String) null);
} |
public static Long validateIssuedAt(String claimName, Long claimValue) throws ValidateException {
if (claimValue != null && claimValue < 0)
throw new ValidateException(String.format("%s value must be null or non-negative; value given was \"%s\"", claimName, claimValue));
return claimValue;
... | @Test
public void testValidateIssuedAt() {
Long expected = 1L;
Long actual = ClaimValidationUtils.validateIssuedAt("iat", expected);
assertEquals(expected, actual);
} |
@EventListener
@Async
void onApplicationEvent(HaloDocumentRebuildRequestEvent event) {
getSearchEngine()
.doOnNext(SearchEngine::deleteAll)
.flatMap(searchEngine -> extensionGetter.getExtensions(HaloDocumentsProvider.class)
.flatMap(HaloDocumentsProvider::fetchAll... | @Test
void shouldDeleteDocsWhenReceivingDeleteRequestEvent() {
var searchEngine = mock(SearchEngine.class);
when(searchEngine.available()).thenReturn(true);
when(extensionGetter.getEnabledExtension(SearchEngine.class))
.thenReturn(Mono.just(searchEngine));
var docIds = Li... |
@Override
public void renameTable(TableIdentifier from, TableIdentifier to) {
throw new UnsupportedOperationException("Cannot rename Hadoop tables");
} | @Test
public void testRenameTable() throws Exception {
HadoopCatalog catalog = hadoopCatalog();
TableIdentifier testTable = TableIdentifier.of("db", "tbl1");
catalog.createTable(testTable, SCHEMA, PartitionSpec.unpartitioned());
assertThatThrownBy(() -> catalog.renameTable(testTable, TableIdentifier.o... |
static String strip(final String line) {
return new Parser(line).parse();
} | @Test
public void shouldReturnLineWithCommentInBackQuotesAsIs() {
// Given:
final String line = "no comment here `-- even this is not a comment`...";
// Then:
assertThat(CommentStripper.strip(line), is(sameInstance(line)));
} |
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) {
LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName);
if (keyProperties == null) {
keyProperties = new LinkedHashMap<>();
String properties = mbeanName.getKeyPropertyListS... | @Test
public void testSingleObjectName() throws Throwable {
JmxMBeanPropertyCache testCache = new JmxMBeanPropertyCache();
LinkedHashMap<String, String> parameterList =
testCache.getKeyPropertyList(new ObjectName("com.organisation:name=value"));
assertSameElementsAndOrder(par... |
public boolean isValid() {
return (mPrimaryColor != mPrimaryTextColor) && (mPrimaryDarkColor != mPrimaryTextColor);
} | @Test
public void isValidIfTextColorIsDifferentThanBackground() {
Assert.assertTrue(overlay(Color.GRAY, Color.GRAY, Color.BLACK).isValid());
Assert.assertTrue(overlay(Color.GRAY, Color.BLACK, Color.BLUE).isValid());
} |
@Override
public boolean contains(int i) {
return false;
} | @Test
public void testContains1() throws Exception {
assertFalse(es.contains(Integer.valueOf(5)));
assertFalse(es.contains(Integer.valueOf(3)));
} |
public static java.util.Date convertToTimestamp(Schema schema, Object value) {
if (value == null) {
throw new DataException("Unable to convert a null value to a schema that requires a value");
}
return convertToTimestamp(Timestamp.SCHEMA, schema, value);
} | @Test
public void shouldConvertTimestampValues() {
java.util.Date current = new java.util.Date();
long currentMillis = current.getTime() % MILLIS_PER_DAY;
// java.util.Date - just copy
java.util.Date ts1 = Values.convertToTimestamp(Timestamp.SCHEMA, current);
assertEquals(cu... |
@Nonnull
public static <T> AggregateOperation1<T, LongDoubleAccumulator, Double> averagingDouble(
@Nonnull ToDoubleFunctionEx<? super T> getDoubleValueFn
) {
checkSerializable(getDoubleValueFn, "getDoubleValueFn");
// count == accumulator.value1
// sum == accumulator.value2
... | @Test
public void when_averagingDouble_noInput_then_NaN() {
// Given
AggregateOperation1<Double, LongDoubleAccumulator, Double> aggrOp = averagingDouble(Double::doubleValue);
LongDoubleAccumulator acc = aggrOp.createFn().get();
// When
double result = aggrOp.finishFn().apply... |
BackgroundJobRunner getBackgroundJobRunner(Job job) {
assertJobExists(job.getJobDetails());
return backgroundJobRunners.stream()
.filter(jobRunner -> jobRunner.supports(job))
.findFirst()
.orElseThrow(() -> problematicConfigurationException("Could not find... | @Test
void getBackgroundJobRunnerForNonIoCJobWithInstance() {
jobActivator.clear();
final Job job = anEnqueuedJob()
.withJobDetails(() -> testService.doWork())
.build();
assertThat(backgroundJobServer.getBackgroundJobRunner(job))
.isNotNull()
... |
Object getEventuallyWeightedResult(Object rawObject, MULTIPLE_MODEL_METHOD multipleModelMethod,
double weight) {
switch (multipleModelMethod) {
case MAJORITY_VOTE:
case MODEL_CHAIN:
case SELECT_ALL:
case SELECT_FIRST:
... | @Test
void getEventuallyWeightedResultValueWeightNoNumber() {
VALUE_WEIGHT_METHODS.forEach(multipleModelMethod -> {
try {
evaluator.getEventuallyWeightedResult("OBJ", multipleModelMethod, 34.2);
fail(multipleModelMethod + " is supposed to throw exception because r... |
@Transactional
public ChecklistQuestionsResponse readChecklistQuestions(User user) {
List<CustomChecklistQuestion> customChecklistQuestions = customChecklistQuestionRepository.findAllByUser(user);
Map<Category, List<Question>> categoryQuestions = customChecklistQuestions.stream()
.m... | @DisplayName("체크리스트 질문 조회 성공")
@Test
void readChecklistQuestions() {
// given
customChecklistQuestionRepository.saveAll(CustomChecklistFixture.CUSTOM_CHECKLIST_QUESTION_DEFAULT);
// given & when
ChecklistQuestionsResponse checklistQuestionsResponse = checklistService.readCheckli... |
public static List<String> filterMatches(@Nullable List<String> candidates,
@Nullable Pattern[] positivePatterns,
@Nullable Pattern[] negativePatterns) {
if (candidates == null || candidates.isEmpty()) {
return Collections.e... | @Test
public void filterMatchesNegative() {
List<String> candidates = ImmutableList.of("a", "b");
List<String> expected = ImmutableList.of("a");
assertThat(filterMatches(candidates, null, new Pattern[]{Pattern.compile("b")}),
is(expected));
} |
@Override
public DescribeClusterResult describeCluster(DescribeClusterOptions options) {
final KafkaFutureImpl<Collection<Node>> describeClusterFuture = new KafkaFutureImpl<>();
final KafkaFutureImpl<Node> controllerFuture = new KafkaFutureImpl<>();
final KafkaFutureImpl<String> clusterIdFut... | @Test
public void testDescribeCluster() throws Exception {
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(4, 0),
AdminClientConfig.RETRIES_CONFIG, "2")) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
// Prepare the describe cl... |
Properties getProperties() {
return m_properties;
} | @Test
public void checkDefaultOptions() {
Properties props = m_parser.getProperties();
// verifyDefaults(props);
assertTrue(props.isEmpty());
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetBlockByNumber() throws Exception {
web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(Numeric.toBigInt("0x1b4")), true)
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\","
+ "\"pa... |
public static Map<String, String> validate(Map<String, String> configs) {
Map<String, String> invalidConfigs = new HashMap<>();
// No point to validate when connector is disabled.
if ("false".equals(configs.getOrDefault(ENABLED, "true"))) {
return invalidConfigs;
}
... | @Test
public void testSkipValidationIfConnectorDisabled() {
Map<String, String> configValues = MirrorCheckpointConfig.validate(makeProps(
MirrorConnectorConfig.ENABLED, "false",
MirrorCheckpointConfig.EMIT_CHECKPOINTS_ENABLED, "false",
MirrorCheckpointConfig.S... |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final java.nio.file.Path p = session.toPath(file);
final Set<OpenOption> options = new HashSet<>();
options.... | @Test
public void testWriteContentRange() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLoginCallback(), new DisabledCancelC... |
@Override
public String getId() {
return codec.getId();
} | @Test
public void delegatesGetId() {
Mockito.when(codec.getId()).thenReturn("MyLogstashPluginId");
final JavaCodecDelegator codecDelegator = constructCodecDelegator();
assertEquals("MyLogstashPluginId", codecDelegator.getId());
} |
@Override
public String getExtraNameCharacters() {
return null;
} | @Test
void assertGetExtraNameCharacters() {
assertNull(metaData.getExtraNameCharacters());
} |
@Override
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream,
final ValueJoiner<? super V, ? super VO, ? extends VR> joiner,
final JoinWindows windows) {
return join(otherStream, toValueJoinerWithKey(joiner), w... | @Test
public void shouldNotAllowNullValueJoinerOnJoinWithGlobalTable() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.join(testGlobalTable, MockMapper.selectValueMapper(), (ValueJoiner<? super String, ? super String, ?>) null));
... |
public static double convertToSeconds(long duration, TimeUnit timeUnit) {
return timeUnit.toNanos(duration) / NANOS_IN_SECOND;
} | @Test
public void testConvertToSeconds() {
assertThat(MetricsUtil.convertToSeconds(1, TimeUnit.HOURS)).isEqualTo(3600.0);
assertThat(MetricsUtil.convertToSeconds(1, TimeUnit.MINUTES)).isEqualTo(60.0);
assertThat(MetricsUtil.convertToSeconds(1, TimeUnit.SECONDS)).isEqualTo(1.0);
asser... |
@Override
public String getName() {
return this.name;
} | @Test
public void allCircuitBreakerStatesAllowTransitionToItsOwnState() {
for (final CircuitBreaker.State state : CircuitBreaker.State.values()) {
assertThatNoException().isThrownBy(() -> CircuitBreaker.StateTransition.transitionBetween(circuitBreaker.getName(), state, state));
}
} |
@Override
public void start() {
this.all = registry.meter(name(getName(), "all"));
this.trace = registry.meter(name(getName(), "trace"));
this.debug = registry.meter(name(getName(), "debug"));
this.info = registry.meter(name(getName(), "info"));
this.warn = registry.meter(nam... | @Test
public void usesSharedRegistries() {
String registryName = "registry";
SharedMetricRegistries.add(registryName, registry);
final InstrumentedAppender shared = new InstrumentedAppender(registryName);
shared.start();
when(event.getLevel()).thenReturn(Level.INFO);
... |
public RuntimeOptionsBuilder parse(Map<String, String> properties) {
return parse(properties::get);
} | @Test
void should_parse_plugin_publish_token() {
properties.put(Constants.PLUGIN_PUBLISH_TOKEN_PROPERTY_NAME, "some/value");
RuntimeOptions options = cucumberPropertiesParser
.parse(properties)
.enablePublishPlugin()
.build();
assertThat(option... |
static List<ClassLoader> selectClassLoaders(ClassLoader classLoader) {
// list prevents reordering!
List<ClassLoader> classLoaders = new ArrayList<>();
if (classLoader != null) {
classLoaders.add(classLoader);
}
// check if TCCL is same as given classLoader
... | @Test
public void selectingSimpleGivenClassLoader() {
List<ClassLoader> classLoaders = ServiceLoader.selectClassLoaders(new URLClassLoader(new URL[0]));
assertEquals(2, classLoaders.size());
} |
public static boolean shouldLoadInIsolation(String name) {
return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches());
} | @Test
public void testAllowedJsonConverterClasses() {
List<String> jsonConverterClasses = Arrays.asList(
"org.apache.kafka.connect.json.",
"org.apache.kafka.connect.json.DecimalFormat",
"org.apache.kafka.connect.json.JsonConverter",
"org.apache.kafka.connect.j... |
public List<QueuePath> getWildcardedQueuePaths(int maxAutoCreatedQueueDepth) {
List<QueuePath> wildcardedPaths = new ArrayList<>();
// Start with the most explicit format (without wildcard)
wildcardedPaths.add(this);
String[] pathComponents = getPathComponents();
int supportedWildcardLevel = getSup... | @Test
public void testWildcardedQueuePathsWithTwoLevelWildCard() {
int maxAutoCreatedQueueDepth = 2;
List<QueuePath> expectedPaths = new ArrayList<>();
expectedPaths.add(TEST_QUEUE_PATH);
expectedPaths.add(ONE_LEVEL_WILDCARDED_TEST_PATH);
expectedPaths.add(TWO_LEVEL_WILDCARDED_TEST_PATH);
Li... |
public MutableTree<K> beginWrite() {
return new MutableTree<>(this);
} | @Test
public void tailReverseIterationTest() {
Random random = new Random(239786);
Persistent23Tree.MutableTree<Integer> tree = new Persistent23Tree<Integer>().beginWrite();
int[] p = genPermutation(random);
TreeSet<Integer> added = new TreeSet<>();
for (int i = 0; i < ENTRIE... |
public static void main(String[] args) throws IOException {
runSqlLine(args, null, System.out, System.err);
} | @Test
public void classLoader_readFile() throws Exception {
File simpleTable = folder.newFile();
BeamSqlLine.main(
new String[] {
"-e",
"CREATE EXTERNAL TABLE test (id INTEGER) TYPE 'text' LOCATION '"
+ simpleTable.getAbsolutePath()
+ "';",
"-... |
long remove(final long recordingId)
{
ensurePositive(recordingId, "recordingId");
final long[] index = this.index;
final int lastPosition = lastPosition();
final int position = find(index, recordingId, lastPosition);
if (position < 0)
{
return NULL_VALUE;... | @Test
void removeReturnsNullValueWhenIndexIsEmpty()
{
assertEquals(NULL_VALUE, catalogIndex.remove(1));
} |
static Expression getResultUpdaterExpression(final RegressionModel.NormalizationMethod normalizationMethod) {
if (UNSUPPORTED_NORMALIZATION_METHODS.contains(normalizationMethod)) {
return new NullLiteralExpr();
} else {
return getResultUpdaterSupportedExpression(normalizationMeth... | @Test
void getResultUpdaterExpression() {
UNSUPPORTED_NORMALIZATION_METHODS.forEach(normalizationMethod -> {
Expression retrieved =
KiePMMLRegressionTableFactory.getResultUpdaterExpression(normalizationMethod);
assertThat(retrieved).isInstanceOf(NullLiteralExpr.cl... |
public static DateTime convertToDateTime(@Nonnull Object value) {
if (value instanceof DateTime) {
return (DateTime) value;
}
if (value instanceof Date) {
return new DateTime(value, DateTimeZone.UTC);
} else if (value instanceof ZonedDateTime) {
final... | @Test
void convertFromOffsetDateTime() {
final OffsetDateTime input = OffsetDateTime.of(2021, 11, 20, 14, 50, 10, 0, ZoneOffset.UTC);
final DateTime output = DateTimeConverter.convertToDateTime(input);
final DateTime expectedOutput = new DateTime(2021, 11, 20, 14, 50, 10, DateTimeZone.UTC)... |
@Override
public Thread newThread(Runnable runnable) {
String name = mPrefix + mThreadNum.getAndIncrement();
Thread ret = new Thread(mGroup, runnable, name, 0);
ret.setDaemon(mDaemon);
return ret;
} | @Test
void testNewThread() {
NamedThreadFactory factory = new NamedThreadFactory();
Thread t = factory.newThread(Mockito.mock(Runnable.class));
assertThat(t.getName(), allOf(containsString("pool-"), containsString("-thread-")));
assertFalse(t.isDaemon());
// since security ma... |
public Choice<T> or(Choice<T> other) {
checkNotNull(other);
if (other == none()) {
return this;
} else {
Choice<T> thisChoice = this;
return new Choice<T>() {
@Override
protected Iterator<T> iterator() {
return Iterators.concat(thisChoice.iterator(), other.iterato... | @Test
public void or() {
assertThat(Choice.of(2).or(Choice.from(ImmutableList.of(1, 3))).asIterable())
.containsExactly(2, 1, 3)
.inOrder();
} |
@VisibleForTesting
static Properties extractCommonsHikariProperties(Properties properties) {
Properties result = new Properties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
if (!ALLOWED_SONAR_PROPERTIES.contains(key)) {
if (DEPREC... | @Test
public void logWarningIfDeprecatedPropertyUsed() {
Properties props = new Properties();
props.setProperty("sonar.jdbc.maxIdle", "5");
props.setProperty("sonar.jdbc.minEvictableIdleTimeMillis", "300000");
props.setProperty("sonar.jdbc.timeBetweenEvictionRunsMillis", "1000");
props.setPropert... |
public static FingerprintTrustManagerFactoryBuilder builder(String algorithm) {
return new FingerprintTrustManagerFactoryBuilder(algorithm);
} | @Test
public void testFingerprintWithUnexpectedCharacters() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
FingerprintTrustManagerFactory.builder("SHA-256").fingerprints("00:00:00\n").build();
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.