focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testAutoMPGLAD() {
test(Loss.lad(), "autoMPG", AutoMPG.formula, AutoMPG.data, 3.0979);
} |
public static List<UpdateRequirement> forUpdateTable(
TableMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid table metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Bui... | @Test
public void setAndRemoveStatistics() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.SetStatistics(0L, mock(StatisticsFile.class))));
requirements.forEach(req -> req.validate(metadata));
assert... |
public static String readFile(String path) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(path);
if (classPathResource.exists() && classPathResource.isReadable()) {
try (InputStream inputStream = classPathResource.getInputStream()) {
return StreamUtils.copyToString(inputSt... | @Test
public void testReadExistedFile() throws IOException {
String content = ResourceFileUtils.readFile("test.txt");
assertThat(content).isEqualTo("just for test");
} |
@Override
public void submitPopConsumeRequest(
final List<MessageExt> msgs,
final PopProcessQueue processQueue,
final MessageQueue messageQueue) {
final int consumeBatchSize = this.defaultMQPushConsumer.getConsumeMessageBatchMaxSize();
if (msgs.size() <= consumeBatchSize) {
... | @Test
public void testSubmitPopConsumeRequestWithMultiMsg() throws IllegalAccessException {
List<MessageExt> msgs = Arrays.asList(createMessageExt(), createMessageExt());
PopProcessQueue processQueue = mock(PopProcessQueue.class);
MessageQueue messageQueue = mock(MessageQueue.class);
... |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(ap... | @Test
public void status_YELLOW_when_single_GREEN_application_node() {
Set<NodeHealth> nodeHealths = nodeHealths(GREEN).collect(toSet());
Health check = underTest.check(nodeHealths);
assertThat(check)
.forInput(nodeHealths)
.hasStatus(Health.Status.YELLOW)
.andCauses("There should be a... |
public static byte[] signMessage(
final RawPrivateTransaction privateTransaction, final Credentials credentials) {
final byte[] encodedTransaction = encode(privateTransaction);
final Sign.SignatureData signatureData =
Sign.signMessage(encodedTransaction, credentials.getEcKeyP... | @Test
public void testSignBesuTransaction() {
final String expected =
"0xf8b1808203e8832dc6c094627306090abab3a6e1400e9345bc60c78a8bef578080820fe7a060c70c3f989ef5459021142959f8fc1ad6e5fe8542cf238484c6d6b8c8a6dbcca075727642ce691c4bf5ae945523cdd172d44b451ddfe11ae67c376f1e5c7069eea0035695b4cc4b0... |
@Override
public void v(String tag, String message, Object... args) { } | @Test
public void infoNotLogged() {
String expectedTag = "TestTag";
logger.v(expectedTag, "Hello %s", "World");
assertNotLogged();
} |
@Override
public int sizeInBytes() {
return LOG_OVERHEAD + buffer.getInt(LENGTH_OFFSET);
} | @Test
public void testSizeInBytes() {
Header[] headers = new Header[] {
new RecordHeader("foo", "value".getBytes()),
new RecordHeader("bar", null)
};
long timestamp = System.currentTimeMillis();
SimpleRecord[] records = new SimpleRecord[] {
new Si... |
@Override
public void run() {
log.info("Starting file watcher to watch for changes: " + file);
try {
while (!shutdown && key.isValid()) {
try {
handleNextWatchNotification();
} catch (Exception e) {
log.error("Watch service caught exception, will continue:" + e);
... | @Test
public void shouldDetectFileCreated() throws Exception {
// Given:
watcher = new FileWatcher(filePath, callback);
watcher.start();
// When:
Files.write(filePath, someBytes, StandardOpenOption.CREATE_NEW);
// Then:
verify(callback, new Timeout(TimeUnit.MINUTES.toMillis(1), atLeastOn... |
static AnnotatedClusterState generatedStateFrom(final Params params) {
final ContentCluster cluster = params.cluster;
final ClusterState workingState = ClusterState.emptyState();
final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>();
for (final NodeInfo nodeInfo : cluster.... | @Test
void distribution_bits_bounded_by_config_parameter() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().idealDistributionBits(12);
final AnnotatedClusterState state = ClusterSt... |
@VisibleForTesting
Path getBuildFile() {
if (buildFileUnprocessed == null) {
return contextRoot.resolve("jib.yaml");
}
return buildFileUnprocessed;
} | @Test
public void testParse_buildFileDefaultForContext() {
Build buildCommand =
CommandLine.populateCommand(
new Build(), "--target", "test-image-ref", "--context", "test-context");
assertThat(buildCommand.buildFileUnprocessed).isNull();
assertThat(buildCommand.getBuildFile()).isEqualT... |
public static char toCloseByNumber(int number) {
if (number > 20) {
throw new IllegalArgumentException("Number must be [1-20]");
}
return (char) ('①' + number - 1);
} | @Test
public void toCloseByNumberTest(){
assertEquals('②', CharUtil.toCloseByNumber(2));
assertEquals('⑫', CharUtil.toCloseByNumber(12));
assertEquals('⑳', CharUtil.toCloseByNumber(20));
} |
@Override
public T next() {
try {
return item;
} finally {
item = null;
}
} | @Test
public void when_acceptNotCalled_thenNextReturnsNull() {
// When
Integer item = trav.next();
// Then
assertNull(item);
} |
public B version(String version) {
this.version = version;
return getThis();
} | @Test
void version() {
ServiceBuilder builder = new ServiceBuilder();
builder.version("version");
Assertions.assertEquals("version", builder.build().getVersion());
} |
@Override
public String createRandomNickname() {
return NicknamePrefix.getPrefix() +
NicknameCandidate.getCandidate() +
"_" +
generateUUID();
} | @Test
void 닉네임이_성공적으로_생성된다() {
// when
String createdNickname = nicknameGenerator.createRandomNickname();
// then
assertThat(createdNickname).isNotBlank();
} |
@Override
public Set<ComponentDerivationRecord> getChangeRecords( GetXMLDataMeta meta )
throws MetaverseAnalyzerException {
Set<ComponentDerivationRecord> changes = new HashSet<>();
boolean isInFields = meta.isInFields();
boolean isAFile = meta.getIsAFile();
boolean isAUrl = meta.isReadUrl();
... | @Test
public void testGetChangeRecords() throws Exception {
when( meta.isInFields() ).thenReturn( true );
when( meta.getIsAFile() ).thenReturn( false );
when( meta.isReadUrl() ).thenReturn( false );
when( meta.getXMLField() ).thenReturn( "xml" );
analyzer.setBaseStepMeta( meta );
GetXMLDataF... |
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
} | @Test(expected = IllegalArgumentException.class)
public void assertNotNullAndMessageIsNull() {
Assert.notNull(null);
} |
public static Map<String, String> resolveAttachments(Object invocation, boolean isApache) {
if (invocation == null) {
return Collections.emptyMap();
}
final Map<String, String> attachments = new HashMap<>();
if (isApache) {
attachments.putAll(getAttachmentsFromCon... | @Test
public void testAlibabaInvocation() {
final TestStringInvocation testStringInvocation = new TestStringInvocation(null);
String key = "a";
String value = "c";
com.alibaba.dubbo.rpc.RpcContext.getContext().getAttachments().put(key, value);
final Map<String, String> map = ... |
public void process()
throws Exception {
if (_segmentMetadata.getTotalDocs() == 0) {
LOGGER.info("Skip preprocessing empty segment: {}", _segmentMetadata.getName());
return;
}
// Segment processing has to be done with a local directory.
File indexDir = new File(_indexDirURI);
// ... | @Test
public void testV1CleanupIndices()
throws Exception {
constructV1Segment(Collections.emptyList(), Collections.emptyList(), Collections.emptyList(),
Collections.emptyList());
SegmentMetadataImpl segmentMetadata = new SegmentMetadataImpl(_indexDir);
assertEquals(segmentMetadata.getVersi... |
@Override
public Object convert(String value) {
if (isNullOrEmpty(value)) {
return value;
}
if (value.contains("=")) {
final Map<String, String> fields = new HashMap<>();
Matcher m = PATTERN.matcher(value);
while (m.find()) {
... | @Test
public void testFilterRetainsNestedDoubleQuotesInSingleQuotedValues() {
TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>());
@SuppressWarnings("unchecked")
Map<String, String> result = (Map<String, String>) f.convert("otters in k1= v1 k2=' \"v2\"' k3=' \"v3\" ... |
public MediaType detect(InputStream input, Metadata metadata) {
// Look for a resource name in the input metadata
String name = metadata.get(TikaCoreProperties.RESOURCE_NAME_KEY);
if (name != null) {
// If the name is a URL, skip the trailing query
int question = name.ind... | @Test
public void testDetect() {
assertDetect(MediaType.TEXT_PLAIN, "text.txt");
assertDetect(MediaType.TEXT_PLAIN, "text.txt "); // trailing space
assertDetect(MediaType.TEXT_PLAIN, "text.txt\n"); // trailing newline
assertDetect(MediaType.TEXT_PLAIN, "text.txt?a=b"); // URL qu... |
protected void showModels(EpoxyModel<?>... models) {
showModels(Arrays.asList(models));
} | @Test
public void testShowModels() {
TestModel testModel1 = new TestModel();
testModel1.hide();
TestModel testModel2 = new TestModel();
testModel2.hide();
testAdapter.addModels(testModel1, testModel2);
testAdapter.showModels(testAdapter.models);
verify(observer).onItemRangeChanged(0, 1,... |
@Bean
public PluginDataHandler websocketPluginDataHandler() {
return new WebSocketPluginDataHandler();
} | @Test
public void testWebSocketPluginDataHandler() {
applicationContextRunner.run(context -> {
PluginDataHandler handler = context.getBean("websocketPluginDataHandler", PluginDataHandler.class);
assertNotNull(handler);
}
);
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleAliasedDataSources() {
// Given:
final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1 t;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
assertThat(result.getFrom(), is(new AliasedRelation(TEST1, SourceName.of("T"))... |
public static String extractFromURIParams(String paramsRule, String uri) {
Multimap<String, String> criteriaMap = TreeMultimap.create();
if (uri.contains("?") && uri.contains("=")) {
String parameters = uri.substring(uri.indexOf("?") + 1);
for (String parameter : parameters.split("&")) {... | @Test
void testExtractFromURIParams() {
// Check with parameters in no particular order.
String requestPath = "/v2/pet/findByDate/2017/01/04?user_key=998bac0775b1d5f588e0a6ca7c11b852&status=available";
// Only 1 parameter should be taken into account according to rules.
String dispatchCriter... |
static Schema getSchema(Class<? extends Message> clazz) {
return getSchema(ProtobufUtil.getDescriptorForClass(clazz));
} | @Test
public void testOneOfSchema() {
assertEquals(
TestProtoSchemas.ONEOF_SCHEMA,
ProtoSchemaTranslator.getSchema(Proto3SchemaMessages.OneOf.class));
} |
@PublicAPI(usage = ACCESS)
public static Set<Location> ofPackage(String pkg) {
ImmutableSet.Builder<Location> result = ImmutableSet.builder();
for (Location location : getLocationsOf(asResourceName(pkg))) {
result.add(location);
}
return result.build();
} | @Test
@SuppressWarnings("EmptyTryBlock")
public void locations_of_packages_within_JAR_URIs_that_do_not_contain_package_folder() throws Exception {
independentClasspathRule.configureClasspath();
Set<Location> locations = Locations.ofPackage(independentClasspathRule.getIndependentTopLevelPackage(... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testCallJsFunctionSharedJson() {
run(
"def myFn = function(x){ return { myVar: x.foo } }",
"call myFn { foo: 'bar' }"
);
assertEquals(get("myVar"), "bar");
} |
private synchronized boolean validateClientAcknowledgement(long h) {
if (h < 0) {
throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h);
}
if (h > MASK) {
throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa... | @Test
public void testValidateClientAcknowledgement_clientAcksSentStanza() throws Exception
{
// Setup test fixture.
final long h = 1;
final long oldH = 0;
final Long lastUnackedX = 1L;
// Execute system under test.
final boolean result = StreamManager.validateCl... |
@Deprecated
public static Duration toDuration(Time time) {
return Duration.of(time.getSize(), toChronoUnit(time.getUnit()));
} | @Test
void testToDuration() {
final Time time = Time.of(1337, TimeUnit.MICROSECONDS);
final Duration duration = TimeUtils.toDuration(time);
assertThat(duration.toNanos()).isEqualTo(time.getUnit().toNanos(time.getSize()));
} |
public static String getActualIndexName(final String logicIndexName, final String actualTableName) {
return Strings.isNullOrEmpty(actualTableName) ? logicIndexName : logicIndexName + UNDERLINE + actualTableName;
} | @Test
void assertGetActualIndexNameWithoutActualTableName() {
assertThat(IndexMetaDataUtils.getActualIndexName("order_index", null), is("order_index"));
} |
@Override
public String getColumnName(int columnIndex) {
return _columnsArray.get(columnIndex).asText();
} | @Test
public void testGetColumnName() {
// Run the test
final String result = _selectionResultSetUnderTest.getColumnName(0);
// Verify the results
assertEquals("column1", result);
} |
@Override
public void checkCanDropSchema(Identity identity, AccessControlContext context, CatalogSchemaName schema)
{
if (!isSchemaOwner(identity, schema)) {
denyDropSchema(schema.toString());
}
} | @Test
public void testSchemaRulesForCheckCanDropSchema() throws IOException
{
TransactionManager transactionManager = createTestTransactionManager();
AccessControlManager accessControlManager = newAccessControlManager(transactionManager, "file-based-system-access-schema.json");
transact... |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @SuppressWarnings("unchecked")
@Test(timeout=10000)
public void testCopyFromHostOnAnyException() throws Exception {
InMemoryMapOutput<Text, Text> immo = mock(InMemoryMapOutput.class);
Fetcher<Text,Text> underTest = new FakeFetcher<Text,Text>(job, id, ss, mm,
r, metrics, except, key, connection);
... |
public void processRow(GenericRow decodedRow, Result reusedResult)
throws Exception {
reusedResult.reset();
if (_complexTypeTransformer != null) {
// TODO: consolidate complex type transformer into composite type transformer
decodedRow = _complexTypeTransformer.transform(decodedRow);
}
... | @Test
public void testSingleRow()
throws Exception {
TableConfig config = createTestTableConfig();
Schema schema = Fixtures.createSchema();
TransformPipeline pipeline = new TransformPipeline(config, schema);
GenericRow simpleRow = Fixtures.createSingleRow(9527);
TransformPipeline.Result resu... |
@Override
public final synchronized V get() throws InterruptedException, ExecutionException {
while (result == null && exception == null && !cancelled) {
futureWait();
}
return getOrThrowExecutionException();
} | @Test(expected = TimeoutException.class)
public void simpleSmackFutureTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
InternalProcessStanzaSmackFuture<Boolean, Exception> future = new SimpleInternalProcessStanzaSmackFuture<Boolean, Exception>() {
@Override
... |
@Override
public Object plugin(final Object target) {
return Plugin.wrap(target, this);
} | @Test
public void pluginTest() {
final PostgreSQLQueryInterceptor postgreSQLQueryInterceptor = new PostgreSQLQueryInterceptor();
Assertions.assertDoesNotThrow(() -> postgreSQLQueryInterceptor.plugin(new Object()));
} |
public static boolean isUri(String potentialUri) {
if (StringUtils.isBlank(potentialUri)) {
return false;
}
try {
URI uri = new URI(potentialUri);
return uri.getScheme() != null && uri.getHost() != null;
} catch (URISyntaxException e) {
re... | @Test public void
returns_false_when_uri_doesnt_contain_scheme() {
assertThat(UriValidator.isUri("127.0.0.1"), is(false));
} |
public HollowOrdinalIterator findKeysWithPrefix(String prefix) {
TST current;
HollowOrdinalIterator it;
do {
current = prefixIndexVolatile;
it = current.findKeysWithPrefix(prefix);
} while (current != this.prefixIndexVolatile);
return it;
} | @Test
public void testSetReference() throws Exception {
MovieSetReference movieSetReference = new MovieSetReference(1, 1999, "The Matrix", new HashSet<String>(Arrays.asList("Keanu Reeves", "Laurence Fishburne", "Carrie-Anne Moss")));
objectMapper.add(movieSetReference);
StateEngineRoundTripp... |
@Override
public Properties loadProperties() {
final Properties answer = new Properties();
final Config config = ConfigProvider.getConfig();
for (String name : config.getPropertyNames()) {
try {
if (isValidForActiveProfiles(name)) {
answer.put(... | @Test
public void testLoadAll() {
PropertiesComponent pc = context.getPropertiesComponent();
Properties properties = pc.loadProperties();
Assertions.assertThat(properties.get("start")).isEqualTo("direct:start");
Assertions.assertThat(properties.get("hi")).isEqualTo("World");
... |
@SuppressWarnings("unchecked")
@Udf
public <T> List<T> union(
@UdfParameter(description = "First array of values") final List<T> left,
@UdfParameter(description = "Second array of values") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> combined ... | @Test
public void shouldReturnNullForNullRightInput() {
final List<String> input1 = Arrays.asList("foo");
final List<String> result = udf.union(null, input1);
assertThat(result, is(nullValue()));
} |
public final void setData(T data) {
currentData = data;
allowModelBuildRequests = true;
requestModelBuild();
allowModelBuildRequests = false;
} | @Test
public void setData() {
TestTypedController controller = new TestTypedController();
controller.setData("data");
controller.setData("data");
controller.cancelPendingModelBuild();
controller.setData("data");
controller.setData("data");
assertEquals(4, controller.numTimesBuiltModels... |
public static BytesInput from(InputStream in, int bytes) {
return new StreamBytesInput(in, bytes);
} | @Test
public void testFromByteArray() throws IOException {
byte[] data = new byte[1000];
RANDOM.nextBytes(data);
byte[] input = new byte[data.length + 20];
RANDOM.nextBytes(input);
System.arraycopy(data, 0, input, 10, data.length);
Supplier<BytesInput> factory = () -> BytesInput.from(input, 10... |
public static String getFieldToNullName( LogChannelInterface log, String field, boolean isUseExtId ) {
String fieldToNullName = field;
if ( isUseExtId ) {
// verify if the field has correct syntax
if ( !FIELD_NAME_WITH_EXTID_PATTERN.matcher( field ).matches() ) {
if ( log.isDebug() ) {
... | @Test
public void testIncorrectExternalKeySyntaxWarnIsNotLoggedInNotDebugMode() {
when( logMock.isDebug() ).thenReturn( false );
inputFieldName = "AccountId";
verify( logMock, never() ).logDebug( anyString() );
SalesforceUtils.getFieldToNullName( logMock, inputFieldName, true );
verify( logMock, n... |
@Override
protected boolean isStepCompleted(@NonNull Context context) {
return SetupSupport.isThisKeyboardEnabled(context);
} | @Test
public void testClickToEnableReachesSettings() {
WizardPageEnableKeyboardFragment fragment = startFragment();
Assert.assertFalse(fragment.isStepCompleted(getApplicationContext()));
final View linkToClick = fragment.getView().findViewById(R.id.go_to_language_settings_action);
View.OnClickListene... |
@Override
@SuppressWarnings("unchecked")
public <T> T get(final PluginConfigSpec<T> configSpec) {
if (rawSettings.containsKey(configSpec.name())) {
Object o = rawSettings.get(configSpec.name());
if (configSpec.type().isAssignableFrom(o.getClass())) {
return (T) o;... | @Test
public void testDefaultValues() {
Configuration unsetConfig = new ConfigurationImpl(new HashMap<>());
String defaultStringValue = "defaultStringValue";
long defaultLongValue = 43L;
boolean defaultBooleanValue = false;
PluginConfigSpec<String> stringConfig = PluginConf... |
@Override
protected CompletableFuture<LogListInfo> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway)
throws RestHandlerException {
if (logDir == null) {
return CompletableFuture.completedFuture(new LogListInfo(Collections.e... | @Test
void testGetJobManagerLogsListWhenLogDirIsNull() throws Exception {
JobManagerLogListHandler jobManagerLogListHandler = createHandler(null);
LogListInfo logListInfo =
jobManagerLogListHandler.handleRequest(testRequest, dispatcherGateway).get();
assertThat(logListInfo.g... |
static String headerLine(CSVFormat csvFormat) {
return String.join(String.valueOf(csvFormat.getDelimiter()), csvFormat.getHeader());
} | @Test
public void givenHeaderComment_isNoop() {
CSVFormat csvFormat = csvFormat().withHeaderComments("abc", "def", "xyz");
PCollection<String> input =
pipeline.apply(Create.of(headerLine(csvFormat), "a,1,1.1", "b,2,2.2", "c,3,3.3"));
CsvIOStringToCsvRecord underTest = new CsvIOStringToCsvRecord(c... |
public static long parseBytes(String text) throws IllegalArgumentException {
Objects.requireNonNull(text, "text cannot be null");
final String trimmed = text.trim();
if (trimmed.isEmpty()) {
throw new IllegalArgumentException("argument is an empty- or whitespace-only string");
... | @Test
void testParseNumberTimeUnitOverflow() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> MemorySize.parseBytes("100000000000000 tb"));
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final WindowRangeQuery<GenericKey, GenericRow> query = WindowR... | @Test
public void shouldReturnAllSessionsForRangeAll() {
// Given:
givenSingleSession(Instant.now().minusSeconds(1000), Instant.now().plusSeconds(1000));
givenSingleSession(Instant.now().minusSeconds(1000), Instant.now().plusSeconds(1000));
// When:
final KsMaterializedQueryResult<WindowedRow> re... |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldAddAliasForExpression() {
// Given:
final Statement stmt = givenQuery("SELECT 1 + 2 FROM ORDERS;");
// When:
final Query result = (Query) AstSanitizer.sanitize(stmt, META_STORE);
// Then:
final SingleColumn col = (SingleColumn) result.getSelect().getSelectItems().get(... |
@ApiOperation(value = "添加功能按钮资源", notes = "返回新增id")
@PostMapping
public ApiResult<Long> add(@Validated @RequestBody ActionForm actionForm){
return ApiResult.<Long>success().data(baseActionService.addAction(actionForm));
} | @Test
void add() {
} |
static String trimFieldsAndRemoveEmptyFields(String str) {
char[] chars = str.toCharArray();
char[] res = new char[chars.length];
/*
* set when reading the first non trimmable char after a separator char (or the beginning of the string)
* unset when reading a separator
*/
boolean inField ... | @Test
@UseDataProvider("plains")
public void trimFieldsAndRemoveEmptyFields_ignores_EmptyFields(String str) {
assertThat(trimFieldsAndRemoveEmptyFields("")).isEmpty();
assertThat(trimFieldsAndRemoveEmptyFields(str)).isEqualTo(str);
assertThat(trimFieldsAndRemoveEmptyFields(',' + str)).isEqualTo(str);
... |
public boolean hasPersistentLocalStore() {
for (final StateStore store : stateStores) {
if (store.persistent()) {
return true;
}
}
return false;
} | @Test
public void inMemoryStoreShouldNotResultInPersistentLocalStore() {
final ProcessorTopology processorTopology = createLocalStoreTopology(Stores.inMemoryKeyValueStore("my-store"));
assertFalse(processorTopology.hasPersistentLocalStore());
} |
@Override
public int run(String[] args) throws Exception {
YarnConfiguration yarnConf =
getConf() == null ? new YarnConfiguration() : new YarnConfiguration(
getConf());
boolean isHAEnabled =
yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED,
YarnConfiguration.DEFAULT_... | @Test
public void testAccessRemoteNodeLabelManager() throws Exception {
String[] args =
{ "-addToClusterNodeLabels", "x,y" };
assertEquals(0, rmAdminCLI.run(args));
// localNodeLabelsManager shouldn't accessed
assertTrue(dummyNodeLabelsManager.getClusterNodeLabelNames().isEmpty());
... |
@Override
public Boolean parse(final String value) {
return Boolean.valueOf(value);
} | @Test
void assertParse() {
assertTrue(new PostgreSQLBoolValueParser().parse("true"));
} |
static int calcSetBitSeq(int by, int startBit, int bitSize, int val)
{
int mask = ((1 << bitSize) - 1);
int truncatedVal = val & mask;
mask = ~(mask << startBit);
return (by & mask) | (truncatedVal << startBit);
} | @Test
void testCalcSetBitSeq()
{
assertEquals(Integer.parseInt("00000000", 2), calcSetBitSeq(Integer.parseInt("11111111", 2), 0, 8, 0));
assertEquals(Integer.parseInt("00000001", 2), calcSetBitSeq(Integer.parseInt("11111111", 2), 0, 8, 1));
assertEquals(Integer.parseInt("11111111", 2), c... |
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".groovy");
} | @Test
void testGroovyFileFilter() {
GroovyFileFilter filter = new GroovyFileFilter();
assertFalse(filter.accept(new File("/"), "file.mikey"));
assertTrue(filter.accept(new File("/"), "file.groovy"));
} |
public PipelineConfigs getFirstEditablePartOrNull() {
for (PipelineConfigs part : parts) {
if (isEditable(part))
return part;
}
return null;
} | @Test
public void shouldReturnNullWhenFirstEditablePartNotExists() {
PipelineConfig pipe1 = PipelineConfigMother.pipelineConfig("pipeline1");
BasicPipelineConfigs part1 = new BasicPipelineConfigs(pipe1);
MergePipelineConfigs group = new MergePipelineConfigs(
part1, new BasicP... |
public void checkForUpgradeAndExtraProperties() throws IOException {
if (upgradesEnabled()) {
checkForUpgradeAndExtraProperties(systemEnvironment.getAgentMd5(), systemEnvironment.getGivenAgentLauncherMd5(),
systemEnvironment.getAgentPluginsMd5(), systemEnvironment.getTfsImplMd5()... | @Test
void checkForUpgradeShouldKillAgentIfPluginZipMd5doesNotMatch() {
when(systemEnvironment.getAgentMd5()).thenReturn("not-changing");
expectHeaderValue(SystemEnvironment.AGENT_CONTENT_MD5_HEADER, "not-changing");
when(systemEnvironment.getGivenAgentLauncherMd5()).thenReturn("not-changin... |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 0) {
if ("getAsText".equals(methodName)) {
return SelString.of(val.getAsText(Locale.US));
} else if ("withMinimumValue".equals(methodName)) {
return SelJodaDateTime.of(val.withMinimumValue());
}... | @Test(expected = UnsupportedOperationException.class)
public void testInvalidCallMethod() {
one.call("getAsString", new SelType[] {});
} |
@Override
public void setQueues(List<CSQueue> queues) {
this.queues = queues;
} | @Test
public void testPriorityUtilizationOrdering() {
PriorityUtilizationQueueOrderingPolicy policy =
new PriorityUtilizationQueueOrderingPolicy(true);
// Case 1, one queue
policy.setQueues(mockCSQueues(new String[] { "a" }, new int[] { 1 },
new float[] { 0.1f }, new float[] {0.2f}, ""));... |
public static void insert(
final UnsafeBuffer termBuffer, final int termOffset, final UnsafeBuffer packet, final int length)
{
if (0 == termBuffer.getInt(termOffset))
{
termBuffer.putBytes(termOffset + HEADER_LENGTH, packet, HEADER_LENGTH, length - HEADER_LENGTH);
te... | @Test
void shouldFillGapButNotMoveTailOrHwm()
{
final int frameLength = 50;
final int alignedFrameLength = BitUtil.align(frameLength, FRAME_ALIGNMENT);
final int srcOffset = 0;
final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocate(alignedFrameLength));
final in... |
public void steal() {
method.steal();
} | @Test
void testSteal() {
final var method = spy(StealingMethod.class);
final var thief = new HalflingThief(method);
thief.steal();
verify(method).steal();
String target = verify(method).pickTarget();
verify(method).confuseTarget(target);
verify(method).stealTheItem(target);
verifyNoM... |
@Override
public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc,
boolean addFieldName, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
// Unused in vertica
// int preci... | @Test
public void testGetFieldDefinition() throws Exception {
assertEquals( "FOO TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) );
assertEquals( "TIMESTAMP",
nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, fals... |
@Override
public void writeChar(final int v) throws IOException {
ensureAvailable(CHAR_SIZE_IN_BYTES);
MEM.putChar(buffer, ARRAY_BYTE_BASE_OFFSET + pos, (char) v);
pos += CHAR_SIZE_IN_BYTES;
} | @Test
public void testWriteCharV() throws Exception {
char expected = 100;
out.writeChar(expected);
char actual = Bits.readChar(out.buffer, 0, ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN);
assertEquals(expected, actual);
} |
@Bean
public PluginDataHandler redirectPluginDataHandler() {
return new RedirectPluginDataHandler();
} | @Test
public void testRedirectPluginDataHandler() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(RedirectPluginConfiguration.class))
.withBean(RedirectPluginConfigurationTest.class)
.withBean(DispatcherHandler.class)
.withPropertyVal... |
public static long getDateTime(String timestamp) throws ParseException, IllegalArgumentException {
if (timestamp == null) {
throw new IllegalArgumentException("Error parsing timestamp with null value");
}
final String[] timestampParts = timestamp.split("T");
if (timestampPar... | @Test
public void shouldThrowOnInvalidDateFormatOrNullTimestamp() {
// check some invalid formats
// test null timestamp
assertTrue(assertThrows(IllegalArgumentException.class, () ->
Utils.getDateTime(null)
).getMessage().contains("Error parsing timestamp with null value"... |
@Override
public <VR> KTable<Windowed<K>, VR> aggregate(final Initializer<VR> initializer,
final Aggregator<? super K, ? super V, VR> aggregator) {
return aggregate(initializer, aggregator, Materialized.with(keySerde, null));
} | @Test
public void shouldThrowIllegalArgumentWhenRetentionIsTooSmall() {
assertThrows(IllegalArgumentException.class, () -> windowedStream
.aggregate(
MockInitializer.STRING_INIT,
MockAggregator.TOSTRING_ADDER,
Materialized
.<Str... |
public static List<LionBundle> generateBundles(String base, String... tags) {
List<LionBundle> bundles = new ArrayList<>(tags.length);
BundleStitcher stitcher = new BundleStitcher(base);
for (String tag : tags) {
try {
LionBundle lion = stitcher.stitch(tag);
... | @Test
public void generateBundles() {
title("generateBundles");
List<LionBundle> bundles =
BundleStitcher.generateBundles(LION_BASE, LION_TAGS);
print(bundles);
assertEquals("missing the bundle", 1, bundles.size());
LionBundle b = bundles.get(0);
asse... |
@Override
public void addPermits(int permits) {
get(addPermitsAsync(permits));
} | @Test
public void testAddPermits() throws InterruptedException {
RPermitExpirableSemaphore s = redisson.getPermitExpirableSemaphore("test");
s.trySetPermits(10);
s.addPermits(5);
assertThat(s.availablePermits()).isEqualTo(15);
s.addPermits(-10);
assertThat(s.... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
OSMValueExtractor.extractTons(edgeId, edgeIntAccess, way, maxAxleLoadEncoder, Collections.singletonList("maxaxleload"));
} | @Test
public void testRounding() {
ReaderWay readerWay = new ReaderWay(1);
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
readerWay.setTag("maxaxleload", "4.8");
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
assertEquals(5... |
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 invokeEmptyList() {
FunctionTestUtil.assertResultError(minFunction.invoke(Collections.emptyList()), InvalidParametersEvent.class);
} |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void doNotCastNumberLiteralDouble() {
final TypedExpression left = expr("getValue()", java.lang.Object.class);
final TypedExpression right = expr("20", double.class);
final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, false).coerce();
... |
public static URL getResourceUrl(String resource) throws IOException {
if (resource.startsWith(CLASSPATH_PREFIX)) {
String path = resource.substring(CLASSPATH_PREFIX.length());
ClassLoader classLoader = ResourceUtils.class.getClassLoader();
URL url =... | @Test
void testGetResourceUrlFromLoader() throws IOException {
URL url = ResourceUtils.getResourceUrl(this.getClass().getClassLoader(), "test-tls-cert.pem");
assertNotNull(url);
} |
public void assignStates() {
checkStateMappingCompleteness(allowNonRestoredState, operatorStates, tasks);
Map<OperatorID, OperatorState> localOperators = new HashMap<>(operatorStates);
// find the states of all operators belonging to this task and compute additional
// information in f... | @Test
void testChannelStateAssignmentNoRescale() throws JobException, JobExecutionException {
List<OperatorID> operatorIds = buildOperatorIds(2);
Map<OperatorID, OperatorState> states = buildOperatorStates(operatorIds, 2);
Map<OperatorID, ExecutionJobVertex> vertices =
build... |
@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException {
return new Checksum(HashAlgorithm.sha512, this.digest("SHA-512",
this.normalize(in, status), status));
} | @Test
public void testCompute() throws Exception {
assertEquals("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
new SHA512ChecksumCompute().compute(new NullInputStream(0), new TransferStatus()).hash);
} |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnSimpleResourceWithCollectionLevelAction() {
@RestLiSimpleResource(name = "simpleResourceWithUnsupportedMethod")
class LocalClass extends SimpleResourceTemplate<EmptyRecord>
{
@Action(name = "badAction", resourceLevel = Res... |
public boolean matches(Evidence evidence) {
return sourceMatches(evidence)
&& confidenceMatches(evidence)
&& name.equalsIgnoreCase(evidence.getName())
&& valueMatches(evidence);
} | @Test
public void testWildcardSourceMatching() throws Exception {
final EvidenceMatcher wildcardSourceMatcher = new EvidenceMatcher(null, "name", "value", false, Confidence.MEDIUM);
assertFalse("wildcard source matcher should not match EVIDENCE_HIGHEST", wildcardSourceMatcher.matches(EVIDENCE_HIGHES... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestFindLastMatchingRecording()
{
internalEncodeLogHeader(buffer, 0, 90, 90, () -> 10_325_000_000L);
final FindLastMatchingRecordingRequestEncoder requestEncoder = new FindLastMatchingRecordingRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LEN... |
@Override
public void onMetadataUpdate(
MetadataDelta delta,
MetadataImage newImage,
LoaderManifest manifest
) {
boolean checkBrokerRegistration = false;
if (delta.featuresDelta() != null) {
if (delta.metadataVersionChanged().isPresent()) {
if ... | @Test
public void testBrokerUpdateWithoutNewMvDoesNothing() {
BrokerRegistrationTrackerTestContext ctx = new BrokerRegistrationTrackerTestContext();
MetadataDelta delta = ctx.newDelta();
delta.replay(new RegisterBrokerRecord().
setBrokerId(1).
setIncarnationId(INCARN... |
public ProducerBuilderImpl(PulsarClientImpl client, Schema<T> schema) {
this(client, new ProducerConfigurationData(), schema);
} | @Test
public void testProducerBuilderImpl() throws PulsarClientException {
Map<String, String> properties = new HashMap<>();
properties.put("Test-Key2", "Test-Value2");
producerBuilderImpl = new ProducerBuilderImpl<>(client, Schema.BYTES);
Producer<?> producer = producerBuilderImpl.... |
@Override
public void run() {
try { // make sure we call afterRun() even on crashes
// and operate countdown latches, else we may hang the parallel runner
if (steps == null) {
beforeRun();
}
if (skipped) {
return;
}
... | @Test
void testStepLog() {
run(
"print 'hello world'"
);
List<StepResult> results = sr.result.getStepResults();
assertEquals(1, results.size());
String log = results.get(0).getStepLog();
assertTrue(log.contains("[print] hello world"));
} |
@Udf
public <T> List<T> remove(
@UdfParameter(description = "Array of values") final List<T> array,
@UdfParameter(description = "Value to remove") final T victim) {
if (array == null) {
return null;
}
return array.stream()
.filter(el -> !Objects.equals(el, victim))
.coll... | @Test
public void shouldReturnAllElementsIfNoNull() {
final List<String> input1 = Arrays.asList("foo");
final String input2 = null;
final List<String> result = udf.remove(input1, input2);
assertThat(result, contains("foo"));
} |
public SubsetItem getClientsSubset(String serviceName,
int minClusterSubsetSize,
int partitionId,
Map<URI, Double> possibleUris,
long version,
SimpleLoadBalancerState state)
{
SubsettingStrategy<URI> subsettingStrategy = _subsettingStrategyFactory.get(serviceName, minClusterSubsetSiz... | @Test
public void testSingleThreadCase()
{
Mockito.when(_subsettingMetadataProvider.getSubsettingMetadata(_state))
.thenReturn(new DeterministicSubsettingMetadata(0, 5, 0));
SubsettingState.SubsetItem subsetItem = _subsettingState.getClientsSubset(SERVICE_NAME, 4, 0,
createUris(30), 0, _sta... |
@Operation(summary = "queryProcessInstanceListByTrigger", description = "QUERY_PROCESS_INSTANCE_BY_TRIGGER_NOTES")
@Parameters({
@Parameter(name = "projectCode", description = "PROJECT_CODE", required = true, schema = @Schema(implementation = Long.class)),
@Parameter(name = "triggerCode", de... | @Test
public void queryProcessInstancesByTriggerCode() throws Exception {
Map<String, Object> mockResult = new HashMap<>();
mockResult.put(Constants.STATUS, Status.SUCCESS);
Mockito.when(processInstanceService
.queryByTriggerCode(Mockito.any(), Mockito.anyLong(), Mockito.any... |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMap("containsAtLeast", k0, v0, rest));
} | @Test
public void containsAtLeastExtraKeyAndMissingKey_failsWithSameToStringForKeys() {
expectFailureWhenTestingThat(ImmutableMap.of(1L, "jan", 2, "feb"))
.containsAtLeast(1, "jan", 2, "feb");
assertFailureKeys(
"missing keys",
"for key",
"expected value",
"---",
... |
@Override
public List<Class<? extends ComputationStep>> orderedStepClasses() {
return STEPS_CLASSES;
} | @Test
public void count_step_classes() {
assertThat(copyOf(underTest.orderedStepClasses())).hasSize(19);
} |
public Map<Integer, List<ProducerBatch>> drain(MetadataSnapshot metadataSnapshot, Set<Node> nodes, int maxSize, long now) {
if (nodes.isEmpty())
return Collections.emptyMap();
Map<Integer, List<ProducerBatch>> batches = new HashMap<>();
for (Node node : nodes) {
List<Pro... | @Test
public void testDrainWithANodeThatDoesntHostAnyPartitions() {
int batchSize = 10;
int lingerMs = 10;
long totalSize = 10 * 1024;
RecordAccumulator accum = createTestRecordAccumulator(batchSize, totalSize, Compression.NONE, lingerMs);
// Create cluster metadata, node2 d... |
@VisibleForTesting
HiveConf hiveConf() {
return hiveConf;
} | @Test
public void testConf() {
HiveConf conf = createHiveConf();
conf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, "file:/mywarehouse/");
HiveClientPool clientPool = new HiveClientPool(10, conf);
HiveConf clientConf = clientPool.hiveConf();
assertThat(clientConf.get(HiveConf.ConfVars.METAST... |
public static Event[] fromJson(final String json) throws IOException {
return fromJson(json, BasicEventFactory.INSTANCE);
} | @Test(expected=ClassCastException.class)
public void testFromJsonWithInvalidJsonArray1() throws Exception {
Event.fromJson("[1,2]");
} |
protected SuppressionRules rules() {
return rules;
} | @Test
public void updateAnnotationRule() {
final String key1 = "key1", key2 = "key2";
final String value1 = "value1", value2 = "value2";
Map<String, String> annotation = new HashMap<>();
annotation.put(key1, value1);
cfg.annotation(annotation);
configEvent(NetworkCo... |
@Override
public boolean canReadView(ViewLike view) {
final String viewId = view.id();
// If a resolved view id is provided, delegate the permissions check to the resolver.
final ViewResolverDecoder decoder = new ViewResolverDecoder(viewId);
if (decoder.isResolverViewId()) {
... | @Test
void testResolvedViewReadAccess() {
// Test that the resolver permission check allows and disallows appropriately.
assertThat(searchUserResolvedRequiringPermission("missing-permission")
.canReadView(new TestView("resolver" + ViewResolverDecoder.SEPARATOR + "resolved-id"))).isFa... |
@Override
public void write(int b) throws IOException {
if (stream.getCount() >= multiPartSize) {
newStream();
uploadParts();
}
stream.write(b);
pos += 1;
writeBytes.increment();
writeOperations.increment();
// switch to multipart upload
if (multipartUploadId == null && p... | @Test
public void testWrite() {
writeTest();
} |
@Override
public Future<Void> closeAsync() {
if (executor.inEventLoop()) {
return close0();
} else {
final Promise<Void> closeComplete = executor.newPromise();
executor.execute(new Runnable() {
@Override
public void run() {
... | @Test
public void testCloseAsync() throws ExecutionException, InterruptedException {
LocalAddress addr = new LocalAddress(getLocalAddrId());
Bootstrap cb = new Bootstrap();
cb.remoteAddress(addr);
cb.group(group).channel(LocalChannel.class);
ServerBootstrap sb = new ServerBo... |
@Override
public int size() {
Node h = putStack.get();
int putStackSize = h == null ? 0 : h.size;
return putStackSize + takeStackSize.get();
} | @Test
public void size_whenEmpty() {
assertEquals(0, queue.size());
} |
public static AscendingLongIterator or(AscendingLongIterator[] iterators) {
return new OrIterator(iterators);
} | @Test
public void testOr() {
long seed = System.nanoTime();
System.out.println(getClass().getSimpleName() + ".testOr seed: " + seed);
actual.add(new SparseBitSet());
expected.add(new TreeSet<>());
verifyOr();
actual.clear();
expected.clear();
generat... |
public static ViewMetadata fromJson(String metadataLocation, String json) {
return JsonUtil.parse(json, node -> ViewMetadataParser.fromJson(metadataLocation, node));
} | @Test
public void replaceViewMetadataWithMultipleSQLsForDialect() throws Exception {
String json =
readViewMetadataInputFile(
"org/apache/iceberg/view/ViewMetadataMultipleSQLsForDialect.json");
// reading view metadata with multiple SQLs for the same dialects shouldn't fail
ViewMetada... |
public Cookie decode(String header) {
final int headerLen = checkNotNull(header, "header").length();
if (headerLen == 0) {
return null;
}
CookieBuilder cookieBuilder = null;
loop: for (int i = 0;;) {
// Skip spaces and separators.
for (;;) ... | @Test
public void testDecodingQuotedCookie() {
Collection<String> sources = new ArrayList<String>();
sources.add("a=\"\",");
sources.add("b=\"1\",");
Collection<Cookie> cookies = new ArrayList<Cookie>();
for (String source : sources) {
cookies.add(ClientCookieDec... |
@Subscribe
public void onGameTick(GameTick event)
{
final Player local = client.getLocalPlayer();
final Duration waitDuration = Duration.ofMillis(config.getIdleNotificationDelay());
lastCombatCountdown = Math.max(lastCombatCountdown - 1, 0);
if (client.getGameState() != GameState.LOGGED_IN
|| local == nul... | @Test
public void testMovementIdle()
{
when(config.movementIdle()).thenReturn(Notification.ON);
when(player.getWorldLocation()).thenReturn(new WorldPoint(0, 0, 0));
plugin.onGameTick(new GameTick());
when(player.getWorldLocation()).thenReturn(new WorldPoint(1, 0, 0));
plugin.onGameTick(new GameTick());
/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.