focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public String buildContext() {
final ResourceDO after = (ResourceDO) getAfter();
if (Objects.isNull(getBefore())) {
return String.format("the resource [%s] is %s", after.getTitle(), StringUtils.lowerCase(getType().getType().toString()));
}
return String.format("... | @Test
public void resourceChangeBuildContextTest() {
final StringBuilder contrast = new StringBuilder();
contrast.append(String.format("name[%s => %s] ", before.getName(), after.getName()));
contrast.append(String.format("component[%s => %s] ", before.getComponent(), after.getComponent()));... |
@Udtf
public <T> List<List<T>> cube(final List<T> columns) {
if (columns == null) {
return Collections.emptyList();
}
return createAllCombinations(columns);
} | @Test
public void shouldCubeColumnsWithDifferentTypes() {
// Given:
final Object[] args = {1, "foo"};
// When:
final List<List<Object>> result = cubeUdtf.cube(Arrays.asList(args));
// Then:
assertThat(result.size(), is(4));
assertThat(result.get(0), is(Arrays.asList(null, null)));
as... |
@Udf(description = "Returns the cotangent of an INT value")
public Double cot(
@UdfParameter(
value = "value",
description = "The value in radians to get the cotangent of."
) final Integer value
) {
return cot(value == null ? null : value.doubleValue());
... | @Test
public void shouldHandleNull() {
assertThat(udf.cot((Integer) null), is(nullValue()));
assertThat(udf.cot((Long) null), is(nullValue()));
assertThat(udf.cot((Double) null), is(nullValue()));
} |
public void remove() {
int index = this.model.getModelObjects().indexOf( this.model.getSelectedItem() );
if ( index >= 1 ) {
index -= 1;
}
this.model.getModelObjects().remove( this.model.getSelectedItem() );
if ( !model.getModelObjects().isEmpty() ) {
this.model.setSelectedItem( mode... | @Test
public void testRemove() {
controller.addProviders( providers );
controller.getModel().setSelectedItem( controller.getModel().getModelObjects().get( 0 ) );
controller.remove();
assertEquals( 7, controller.getModel().getModelObjects().size() );
} |
public static Optional<ParsedMetricName> parseMetricName(String metricName) {
if (metricName.isEmpty()) {
return Optional.empty();
}
List<String> metricNameSplit =
Splitter.on(METRIC_NAME_DELIMITER).limit(2).splitToList(metricName);
if (metricNameSplit.size() == 0 || metricNameSplit.get(... | @Test
public void testParseMetricName_malformedMetricLabels() {
String metricName = "baseLabel*malformed_kv_pair;key2:val2;";
LabeledMetricNameUtils.ParsedMetricName expectedName =
LabeledMetricNameUtils.ParsedMetricName.create("baseLabel");
Optional<LabeledMetricNameUtils.ParsedMetricName> parse... |
public double weight() {
double w = 0;
if (user != null) {
w += 1;
}
if (role != null) {
w += 1;
}
if (planCpuCostRange != null) {
w += 1;
}
if (planMemCostRange != null) {
w += 1;
}
if (query... | @Test
public void testWeight() {
ResourceGroupClassifier classifier = new ResourceGroupClassifier();
for (int i = 0; i <= 32; i++) {
classifier.setSourceIp("192.168.0.1/" + i);
assertThat(classifier.weight()).isCloseTo(1 + i / 64., within(1e-5));
}
} |
public DirectGraph getGraph() {
checkState(finalized, "Can't get a graph before the Pipeline has been completely traversed");
return DirectGraph.create(
producers, viewWriters, perElementConsumers, rootTransforms, stepNames);
} | @Test
public void getStepNamesContainsAllTransforms() {
PCollection<String> created = p.apply(Create.of("1", "2", "3"));
PCollection<String> transformed =
created.apply(
ParDo.of(
new DoFn<String, String>() {
@ProcessElement
public void p... |
Interned() {} | @Test
public void interned() {
var node = new Interned<Object, Boolean>(new WeakReference<>(null));
assertThat(node.getValue()).isTrue();
assertThat(node.isRetired()).isFalse();
assertThat(node.getValueReference()).isTrue();
node.retire();
assertThat(node.isRetired()).isTrue();
node.die(... |
protected boolean isAssumeIdentity(ConnectionReference conn) {
return isAnonymousAccessAllowed() ||
(isSystemConnection(conn) && !isVmConnectionAuthenticationRequired());
} | @Test
public void testIsAssumeIdentityWithSystemConnection() {
ConnectionContext ctx = new ConnectionContext();
Connection connection = new Connection() {
private final long connectedTimestamp = System.currentTimeMillis();
@Override
public Connector getConnecto... |
public ApolloAuditScope startActiveSpan(OpType type, String name, String description) {
ApolloAuditSpan startSpan = startSpan(type, name, description);
return activate(startSpan);
} | @Test
public void testStartActiveSpan() {
ApolloAuditSpan activeSpan = Mockito.mock(ApolloAuditSpan.class);
{
doReturn(activeSpan).when(tracer).startSpan(Mockito.eq(opType), Mockito.eq(opName), Mockito.eq(description));
}
tracer.startActiveSpan(opType, opName, description);
Mockito.verify(tr... |
@Udf(description = "Splits a string into an array of substrings based on a delimiter.")
public List<String> split(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The delimiter to spli... | @Test
public void shouldSplitAndAddEmptySpacesIfDelimiterStringIsFoundAtTheBeginningOrEnd() {
assertThat(splitUdf.split("$A", "$"), contains("", "A"));
assertThat(splitUdf.split("$A$B", "$"), contains("", "A", "B"));
assertThat(splitUdf.split("A$", "$"), contains("A", ""));
assertThat(splitUdf.split("... |
public static ByteBuf wrappedBuffer(byte[] array) {
if (array.length == 0) {
return EMPTY_BUFFER;
}
return new UnpooledHeapByteBuf(ALLOC, array, array.length);
} | @Test
public void shouldAllowEmptyBufferToCreateCompositeBuffer() {
ByteBuf buf = wrappedBuffer(
EMPTY_BUFFER,
wrappedBuffer(new byte[16]).order(LITTLE_ENDIAN),
EMPTY_BUFFER);
try {
assertEquals(16, buf.capacity());
} finally {
... |
@Override
public void onPartitionsRevoked(final Collection<TopicPartition> partitions) {
log.debug("Current state {}: revoked partitions {} because of consumer rebalance.\n" +
"\tcurrently assigned active tasks: {}\n" +
"\tcurrently assigned standby tasks: {}\n",
... | @Test
public void shouldHandleRevokedPartitions() {
final Collection<TopicPartition> partitions = Collections.singletonList(new TopicPartition("topic", 0));
when(streamThread.setState(State.PARTITIONS_REVOKED)).thenReturn(State.RUNNING);
streamsRebalanceListener.onPartitionsRevoked(partitio... |
public void deleteUser(final User user) {
if (provider.isReadOnly()) {
throw new UnsupportedOperationException("User provider is read-only.");
}
final String username = user.getUsername();
// Make sure that the username is valid.
try {
/*username =*/ Stri... | @Test
public void deleteInvalidUserWillGetError() throws Exception{
User user = new User("!@#ED",null,null,null,null);
assertThrows(IllegalArgumentException.class, () -> userManager.deleteUser(user));
} |
public static List<Integer> changedLines(String oldText, String newText) {
if (oldText == null || oldText.equals(newText)) {
return Collections.emptyList();
}
List<Integer> changed = new ArrayList<>();
String[] oldLines = oldText.split("\n");
String[] newLines = new... | @Test
public void testChangedLines() {
String oldText = "Hello\nWorld\nHow are you";
String newText = "Hello\nWorld\nHow are you";
List<Integer> changed = StringHelper.changedLines(oldText, newText);
assertEquals(0, changed.size());
oldText = "Hello\nWorld\nHow are you";
... |
public boolean promptForSave() throws KettleException {
List<TabMapEntry> list = delegates.tabs.getTabs();
for ( TabMapEntry mapEntry : list ) {
TabItemInterface itemInterface = mapEntry.getObject();
if ( !itemInterface.canBeClosed() ) {
// Show the tab
tabfolder.setSelected( mapEn... | @Test
public void testCanClosePromptToSave() throws Exception {
setPromptToSave( SWT.YES, true );
assertTrue( spoon.promptForSave() );
} |
public void close() {
try {
ioExecutor.shutdown();
if (!ioExecutor.awaitTermination(5L, TimeUnit.MINUTES)) {
throw new TimeoutException("Shutdown spilling thread timeout.");
}
dataFileChannel.close();
} catch (Exception e) {
Exc... | @Test
void testClose() throws Exception {
memoryDataSpiller = createMemoryDataSpiller(dataFilePath);
List<BufferWithIdentity> bufferWithIdentityList =
new ArrayList<>(
createBufferWithIdentityList(
false,
... |
static void checkValidTableName(String nameToCheck) {
if (nameToCheck.length() < MIN_TABLE_ID_LENGTH) {
throw new IllegalArgumentException("Table name cannot be empty. ");
}
if (nameToCheck.length() > MAX_TABLE_ID_LENGTH) {
throw new IllegalArgumentException(
"Table name "
... | @Test
public void testCheckValidTableNameThrowsErrorWhenContainsPeriod() {
assertThrows(IllegalArgumentException.class, () -> checkValidTableName("table.name"));
} |
int[] sortEncodedSet(int[] encodedSet, int validIndex) {
int[] result = new int[validIndex];
for (int i = 0; i < validIndex; ++i) {
result[i] = transformToSortRepresentation(encodedSet[i]);
}
Arrays.sort(result);
for (int i = 0; i < validIndex; ++i) {
re... | @Test
public void testSortEncodedSet() {
int[] testSet = new int[3];
testSet[0] = 655403;
testSet[1] = 655416;
testSet[2] = 655425;
HyperLogLogPlus hyperLogLogPlus = new HyperLogLogPlus(14, 25);
testSet = hyperLogLogPlus.sortEncodedSet(testSet, 3);
assertEqual... |
@Override
public void insertConfigHistoryAtomic(long configHistoryId, ConfigInfo configInfo, String srcIp, String srcUser,
final Timestamp time, String ops) {
String appNameTmp = StringUtils.defaultEmptyIfBlank(configInfo.getAppName());
String tenantTmp = StringUtils.defaultEmptyIfBlank(... | @Test
void testInsertConfigHistoryAtomic() {
String dataId = "dateId243";
String group = "group243";
String tenant = "tenant243";
String content = "content243";
String appName = "appName243";
long id = 123456787765432L;
String srcUser = "user12345";
St... |
void printStats(PrintStream out) {
printNonZeroResultScenarios(out);
if (stepSubCounts.getTotal() == 0) {
out.println("0 Scenarios");
out.println("0 Steps");
} else {
printScenarioCounts(out);
printStepCounts(out);
}
printDuration(o... | @Test
void should_print_zero_scenarios_zero_steps_if_nothing_has_executed() {
Stats counter = createMonochromeSummaryCounter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
counter.printStats(new PrintStream(baos));
assertThat(baos.toString(), startsWith(String.format(
... |
public LogoutRequestModel parseLogoutRequest(HttpServletRequest request) throws SamlValidationException, SamlParseException, SamlSessionException, DienstencatalogusException {
final LogoutRequestModel logoutRequestModel = new LogoutRequestModel();
try {
final BaseHttpServletRequestXMLMessa... | @Test
public void parseLogoutRequestNoSignature() {
httpRequestMock.setParameter("SAMLRequest", "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS... |
public T pollFirst() {
if (head == null) {
return null;
}
T first = head.element;
this.remove(first);
return first;
} | @Test
public void testPollOneElement() {
LOG.info("Test poll one element");
set.add(list.get(0));
assertEquals(list.get(0), set.pollFirst());
assertNull(set.pollFirst());
LOG.info("Test poll one element - DONE");
} |
static QueryId buildId(
final Statement statement,
final EngineContext engineContext,
final QueryIdGenerator idGenerator,
final OutputNode outputNode,
final boolean createOrReplaceEnabled,
final Optional<String> withQueryId) {
if (withQueryId.isPresent()) {
final String que... | @Test
public void shouldReturnWithQueryIdInUppercase(){
// When:
final QueryId queryId = QueryIdUtil.buildId(statement, engineContext, idGenerator, plan,
false, Optional.of("my_query_id"));
// Then:
assertThat(queryId, is(new QueryId("MY_QUERY_ID")));
} |
@VisibleForTesting
void validateParentDept(Long id, Long parentId) {
if (parentId == null || DeptDO.PARENT_ID_ROOT.equals(parentId)) {
return;
}
// 1. 不能设置自己为父部门
if (Objects.equals(id, parentId)) {
throw exception(DEPT_PARENT_ERROR);
}
// 2. 父部... | @Test
public void testValidateParentDept_parentError() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> deptService.validateParentDept(id, id),
DEPT_PARENT_ERROR);
} |
static UWildcard create(Kind kind, @Nullable UTree<?> bound) {
checkArgument(BOUND_KINDS.containsKey(kind));
// verify bound is null iff kind is UNBOUNDED_WILDCARD
checkArgument((bound == null) == (kind == Kind.UNBOUNDED_WILDCARD));
return new AutoValue_UWildcard(kind, bound);
} | @Test
public void equality() {
UExpression objectIdent = UClassIdent.create("java.lang.Object");
UExpression setIdent = UTypeApply.create("java.util.Set", objectIdent);
new EqualsTester()
.addEqualityGroup(UWildcard.create(Kind.UNBOUNDED_WILDCARD, null))
.addEqualityGroup(UWildcard.create... |
@Override
public <VOut> CogroupedKStream<K, VOut> cogroup(final Aggregator<? super K, ? super V, VOut> aggregator) {
Objects.requireNonNull(aggregator, "aggregator can't be null");
return new CogroupedKStreamImpl<K, VOut>(name, subTopologySourceNodes, graphNode, builder)
.cogroup(this, a... | @Test
public void shouldNotHaveNullAggregatorOnCogroup() {
assertThrows(NullPointerException.class, () -> groupedStream.cogroup(null));
} |
public static String s3aToS3(String s3aUrl) {
return s3aUrl.replaceFirst("(?i)^s3a://", "s3://");
} | @Test
void testS3aToS3_AWS() {
// Test cases for AWS S3 URLs
assertEquals("s3://my-bucket/path/to/object", S3Utils.s3aToS3("s3a://my-bucket/path/to/object"));
assertEquals("s3://my-bucket", S3Utils.s3aToS3("s3a://my-bucket"));
assertEquals("s3://MY-BUCKET/PATH/TO/OBJECT", S3Utils.s3aToS3("s3a://MY-BUC... |
@Override
public Output run(RunContext runContext) throws Exception {
LogService logService = ((DefaultRunContext)runContext).getApplicationContext().getBean(LogService.class);
FlowService flowService = ((DefaultRunContext)runContext).getApplicationContext().getBean(FlowService.class);
// v... | @Test
void run() throws Exception {
// create an execution to delete
var logEntry = LogEntry.builder()
.namespace("namespace")
.flowId("flowId")
.timestamp(Instant.now())
.level(Level.INFO)
.message("Hello World")
.build();
... |
public boolean isAnyServiceErrorListDefined()
{
return _serviceErrors != null || _resourceMethodDescriptors.stream()
.map(ResourceMethodDescriptor::getServiceErrors)
.anyMatch(Objects::nonNull);
} | @Test(dataProvider = "isAnyServiceErrorListDefinedData")
public void testIsAnyServiceErrorListDefined(ServiceError[] resourceLevelServiceErrors,
ResourceMethodDescriptor[] resourceMethodDescriptors, boolean expected) {
// Create dummy resource model
final ResourceModel resourceModel = new ResourceModel(... |
public static boolean parseBoolean(String bool, boolean defaultInt) {
if (bool == null) {
return defaultInt;
} else {
return Boolean.parseBoolean(bool);
}
} | @Test
public void parseBoolean() {
Assert.assertTrue(CommonUtils.parseBoolean(null, true));
Assert.assertTrue(CommonUtils.parseBoolean("true", true));
Assert.assertFalse(CommonUtils.parseBoolean("falSE", true));
Assert.assertFalse(CommonUtils.parseBoolean("xxx", true));
Asse... |
public static boolean setProperty(Object target, String name, Object value) {
try {
Class<?> clazz = target.getClass();
if (target instanceof SSLServerSocket) {
// overcome illegal access issues with internal implementation class
clazz = SSLServerSocket.cl... | @Test
public void testSetPropertyPrimitiveWithWrapperValue() {
// Wrapper value
Boolean value = Boolean.TRUE;
DummyClass dummyClass = new DummyClass(false);
dummyClass.setTrace(false);
// dummy field expects a primitive
IntrospectionSupport.setProperty(dummyClass, "... |
public NodeMetricsDbMaintainer(NodeRepository nodeRepository,
MetricsFetcher metricsFetcher,
Duration interval,
Metric metric) {
super(nodeRepository, interval, metric, false); // No locking because this not... | @Test
public void testNodeMetricsDbMaintainer() {
NodeResources resources = new NodeResources(1, 10, 100, 1);
ProvisioningTester tester = new ProvisioningTester.Builder().build();
tester.clock().setInstant(Instant.ofEpochMilli(1400));
tester.makeReadyNodes(2, resources);
test... |
public static byte[] shortToBytesLE(int i, byte[] bytes, int off) {
bytes[off + 1] = (byte) (i >> 8);
bytes[off] = (byte) i;
return bytes;
} | @Test
public void testShortToBytesLE() {
assertArrayEquals(SHORT_12345_LE,
ByteUtils.shortToBytesLE(-12345, new byte[2] , 0));
} |
public void add(int index, NODE element) {
throw e;
} | @Test
void require_that_add_throws_exception() {
assertThrows(NodeVector.ReadOnlyException.class, () -> new TestNodeVector("foo").add(barNode()));
} |
@Override
protected void doStop() throws Exception {
super.doStop();
int openRequestsAtStop = openRequests.get();
log.debug("Stopping with {} open requests", openRequestsAtStop);
if (openRequestsAtStop > 0) {
log.warn("There are still {} open requests", openRequestsAtStop... | @Test
public void doStop() throws Exception {
sut.doStop();
} |
@Override
public CompletableFuture<List<DescribeGroupsResponseData.DescribedGroup>> describeGroups(
RequestContext context,
List<String> groupIds
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(DescribeGroupsRequest.getErrorDescribedGroupList(
... | @Test
public void testDescribeGroups() throws Exception {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
createConfig(),
runtime,
mo... |
public static native int getOsxMemoryInfo(long[] totalAndAvailMem); | @Test
@EnabledOnOs(OS.MAC)
void testOsxMemory() {
long[] mem = new long[2];
assertEquals(0, CLibrary.getOsxMemoryInfo(mem));
assertTrue(mem[0] > 1024, "Total: " + mem[0]);
assertTrue(mem[1] > 1024, "Free: " + mem[1]);
assertTrue(mem[1] < mem[0], "Free (" + mem[1] + ") < T... |
public static void analyze(CreateTableStmt statement, ConnectContext context) {
final TableName tableNameObject = statement.getDbTbl();
MetaUtils.normalizationTableName(context, tableNameObject);
final String catalogName = tableNameObject.getCatalog();
MetaUtils.checkCatalogExistAndRepo... | @Test
public void testAnalyze() throws Exception {
String sql = "CREATE TABLE test_create_table_db.starrocks_test_table\n" +
"(\n" +
" `tag_id` string,\n" +
" `tag_name` string\n" +
") ENGINE = OLAP PRIMARY KEY(`id`)\n" +
... |
protected void notifyConnected(Connection connection) {
if (connectionEventListeners.isEmpty()) {
return;
}
LoggerUtils.printIfInfoEnabled(LOGGER, "[{}] Notify connected event to listeners.", rpcClientConfig.name());
for (ConnectionEventListener connectionEventListener : conn... | @Test
void testNotifyConnected() {
ConnectionEventListener listener = mock(ConnectionEventListener.class);
rpcClient.registerConnectionListener(listener);
rpcClient.notifyConnected(null);
verify(listener).onConnected(null);
verify(rpcClientConfig, times(2)).name();
} |
public MonitorBuilder password(String password) {
this.password = password;
return getThis();
} | @Test
void password() {
MonitorBuilder builder = MonitorBuilder.newBuilder();
builder.password("password");
Assertions.assertEquals("password", builder.build().getPassword());
} |
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
List<AclEntry> foundAclSpecEntries =
... | @Test
public void testMergeAclEntriesDefaultMaskPreserved() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, READ))
.add(aclEntry(DEFAULT, USER, ALL))
... |
public static KeyFormat sanitizeKeyFormat(
final KeyFormat keyFormat,
final List<SqlType> newKeyColumnSqlTypes,
final boolean allowKeyFormatChangeToSupportNewKeySchema
) {
return sanitizeKeyFormatWrapping(
!allowKeyFormatChangeToSupportNewKeySchema ? keyFormat :
sanitizeKeyFormat... | @Test
public void shouldRemoveUnapplicableKeyWrappingWhenSanitizingNoKeyCols() {
// Given:
final KeyFormat format = KeyFormat.nonWindowed(
FormatInfo.of(JsonFormat.NAME),
SerdeFeatures.of(SerdeFeature.UNWRAP_SINGLES));
// When:
final KeyFormat sanitized = SerdeFeaturesFactory.sanitize... |
public static Schema create(Type type) {
switch (type) {
case STRING:
return new StringSchema();
case BYTES:
return new BytesSchema();
case INT:
return new IntSchema();
case LONG:
return new LongSchema();
case FLOAT:
return new FloatSchema();
case DOUBLE:
... | @Test
void doubleAsLongDefaultValue() {
assertThrows(AvroTypeException.class, () -> {
new Schema.Field("myField", Schema.create(Schema.Type.LONG), "doc", 1.0);
});
} |
@Subscribe
public void onPostMenuSort(PostMenuSort postMenuSort)
{
// The menu is not rebuilt when it is open, so don't swap or else it will
// repeatedly swap entries
if (client.isMenuOpen())
{
return;
}
MenuEntry[] menuEntries = client.getMenuEntries();
// Build option map for quick lookup in fin... | @Test
public void testShiftDeposit()
{
when(config.bankDepositShiftClick()).thenReturn(ShiftDepositMode.DEPOSIT_ALL);
when(client.isKeyPressed(KeyCode.KC_SHIFT)).thenReturn(true);
entries = new MenuEntry[]{
menu("Cancel", "", MenuAction.CANCEL),
menu("Wield", "Rune arrow", MenuAction.CC_OP_LOW_PRIORITY, ... |
@Override
public ProductSpuDO getSpu(Long id) {
return productSpuMapper.selectById(id);
} | @Test
void getSpu() {
// 准备参数
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
o.setCategoryId(generateId());
o.setBrandId(generateId());
o.setDeliveryTemplateId(generateId());
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
... |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
boolean satisfied = false;
// No trading history or no position opened, no gain
if (tradingRecord != null) {
Position currentPosition = tradingRecord.getCurrentPosition();
if (currentPositi... | @Test
public void testStopGainNotTriggered() {
TradingRecord tradingRecord = new BaseTradingRecord();
tradingRecord.enter(0, series.getBar(0).getClosePrice(), series.numOf(1));
AverageTrueRangeStopGainRule rule = new AverageTrueRangeStopGainRule(series, 3, 2.0);
assertFalse(rule.is... |
@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 testReplaceLabelsOnNode() throws Exception {
// Successfully replace labels
dummyNodeLabelsManager
.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y", "Y"));
String[] args =
{ "-replaceLabelsOnNode",
"node1:8000,x node2:8000=y node3,x node4=... |
@Override
protected void doRefresh(final List<SelectorData> dataList) {
pluginDataSubscriber.refreshSelectorDataSelf(dataList);
dataList.forEach(pluginDataSubscriber::onSelectorSubscribe);
} | @Test
public void testDoRefresh() {
List<SelectorData> selectorDataList = createFakeSelectorDataObjects(3);
selectorDataHandler.doRefresh(selectorDataList);
verify(subscriber).refreshSelectorDataSelf(selectorDataList);
selectorDataList.forEach(verify(subscriber)::onSelectorSubscribe)... |
@Override
public Collection<FileSourceSplit> enumerateSplits(Path[] paths, int minDesiredSplits)
throws IOException {
final ArrayList<FileSourceSplit> splits = new ArrayList<>();
for (Path path : paths) {
final FileSystem fs = path.getFileSystem();
final FileStat... | @Test
void testFileWithMultipleBlocks() throws Exception {
final Path testPath = new Path("testfs:///dir/file");
testFs =
TestingFileSystem.createForFileStatus(
"testfs",
TestingFileSystem.TestFileStatus.forFileWithBlocks(
... |
@Override public HashSlotCursor12byteKey cursor() {
return new CursorIntKey2();
} | @Test
public void testCursor_valueAddress() {
final SlotAssignmentResult slot = insert(randomKey(), randomKey());
HashSlotCursor12byteKey cursor = hsa.cursor();
cursor.advance();
assertEquals(slot.address(), cursor.valueAddress());
} |
@Override
public void execute(GraphModel graphModel) {
Graph graph = graphModel.getUndirectedGraphVisible();
execute(graph);
} | @Test
public void testColumnReplace() {
GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(1);
graphModel.getNodeTable().addColumn(Modularity.MODULARITY_CLASS, String.class);
Modularity h = new Modularity();
h.execute(graphModel);
} |
@Override
public ExportResult<CalendarContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) {
if (!exportInformation.isPresent()) {
return exportCalendars(authData, Optional.empty());
} else {
StringPaginationToken paginationToke... | @Test
public void exportCalendarFirstSet() throws IOException {
setUpSingleCalendarResponse();
// Looking at first page, with at least one page after it
calendarListResponse.setNextPageToken(NEXT_TOKEN);
// Run test
ExportResult<CalendarContainerResource> result = googleCalendarExporter.export(J... |
public synchronized <K, V> KStream<K, V> stream(final String topic) {
return stream(Collections.singleton(topic));
} | @Test
public void shouldAllowSubscribingToSamePattern() {
builder.stream(Pattern.compile("some-regex"));
builder.stream(Pattern.compile("some-regex"));
assertBuildDoesNotThrow(builder);
} |
@Override
public ValidationResult validate(RuleBuilderStep step) {
if (!actions.containsKey(step.function())) {
return new ValidationResult(true, "Function " + step.function() + " not available as action for rule builder.");
}
return new ValidationResult(false, "");
} | @Test
void validate() {
RuleBuilderStep stepWithValidAction = RuleBuilderStep.builder().function(TEST_ACTION).build();
RuleBuilderStep stepWithInvalidAction = RuleBuilderStep.builder().function("invalidAction").build();
assertThat(classUnderTest.validate(stepWithValidAction).failed()).isFal... |
protected static String convertSoapUITemplate(String responseTemplate) {
if (responseTemplate.contains("${")) {
return SOAPUI_TEMPLATE_PARAMETER_REPLACE_PATTERN.matcher(responseTemplate).replaceAll("{{ $1 }}");
}
return responseTemplate;
} | @Test
void testConvertSoapUITemplate() {
String soapUITemplate = "<something>${myParam}</something>";
String microcksTemplate = SoapController.convertSoapUITemplate(soapUITemplate);
assertEquals("<something>{{ myParam }}</something>", microcksTemplate);
soapUITemplate = "<bean><something>${ ... |
@Nonnull
public static <K, V> BatchSource<Entry<K, V>> map(@Nonnull String mapName) {
return batchFromProcessor("mapSource(" + mapName + ')', readMapP(mapName));
} | @Test
public void mapWithFilterAndProjection_byName() {
// Given
List<Integer> input = sequence(itemCount);
putToBatchSrcMap(input);
// When
BatchSource<Object> source = Sources.map(srcName, truePredicate(), singleAttribute("value"));
// Then
p.readFrom(sour... |
public static int getTypeOfFile(String path, boolean isDirectory) {
String mimeType = MimeTypes.getMimeType(path, isDirectory);
if (mimeType == null) return NOT_KNOWN;
Integer type = sMimeIconIds.get(mimeType);
if (type != null) return type;
else {
if (checkType(mimeType, "text")) return TEXT... | @Test
public void testReturnArchiveTypes() {
assertEquals(Icons.COMPRESSED, Icons.getTypeOfFile("archive.zip", false));
assertEquals(Icons.COMPRESSED, Icons.getTypeOfFile("archive.rar", false));
assertEquals(Icons.COMPRESSED, Icons.getTypeOfFile("archive.tar", false));
assertEquals(Icons.COMPRESSED, I... |
@Override
public void executeUpdate(final UnregisterStorageUnitStatement sqlStatement, final ContextManager contextManager) {
if (!sqlStatement.isIfExists()) {
checkExisted(sqlStatement.getStorageUnitNames());
}
checkInUsed(sqlStatement);
try {
contextManager.... | @Test
void assertExecuteUpdateWithStorageUnitNotExisted() {
when(database.getResourceMetaData().getStorageUnits()).thenReturn(Collections.emptyMap());
assertThrows(MissingRequiredStorageUnitsException.class,
() -> executor.executeUpdate(new UnregisterStorageUnitStatement(Collections.... |
@Override
public MapperResult findAllConfigInfoFetchRows(MapperContext context) {
String sql = "SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 "
+ " FROM ( SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT ?,? )"
+ " g, config_info t WHERE g.i... | @Test
void testFindAllConfigInfoFetchRows() {
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigInfoFetchRows(context);
assertEquals(mapperResult.getSql(),
"SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5 FROM ( SELECT id FROM config_info "
... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final List<Header> headers = new ArrayList<Header>(this.headers());
if(status.isAppend()) {
final HttpRange range = HttpRange.withStatus(status)... | @Test
public void testReadInterrupt() throws Exception {
final Path test = new DAVTouchFeature(session).touch(new Path(new DefaultHomeFinderService(session).find(),
new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
// Unknown length i... |
public String nextNonCliCommand() {
String line;
do {
line = terminal.readLine();
} while (maybeHandleCliSpecificCommands(line));
return line;
} | @Test
public void shouldSwallowCliCommandLines() {
// Given:
when(lineSupplier.get())
.thenReturn(CLI_CMD_NAME)
.thenReturn("not a CLI command;");
// When:
final String result = console.nextNonCliCommand();
// Then:
assertThat(result, is("not a CLI command;"));
} |
@Override
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
try {
String partitionColumn = job.get(Constants.JDBC_PARTITION_COLUMN);
int numPartitions = job.getInt(Constants.JDBC_NUM_PARTITIONS, -1);
String lowerBound = job.get(Constants.JDBC_LOW_BOUND);
Strin... | @Test
public void testLimitSplit_noSpillOver() throws HiveJdbcDatabaseAccessException, IOException {
JdbcInputFormat f = new JdbcInputFormat();
when(mockDatabaseAccessor.getTotalNumberOfRecords(any(Configuration.class))).thenReturn(15);
JobConf conf = new JobConf();
conf.set("mapred.input.dir", "/te... |
@Udf(description = "Splits a string into an array of substrings based on a regexp.")
public List<String> regexpSplit(
@UdfParameter(
description = "The string to be split. If NULL, then function returns NULL.")
final String string,
@UdfParameter(
description = "The regular expres... | @Test
public void shouldSplitAndAddEmptySpacesIfRegexIsFoundInContiguousPositions() {
assertThat(udf.regexpSplit("A--A", "-"), contains("A", "", "A"));
assertThat(udf.regexpSplit("z--A--z", "-"), contains("z", "", "A", "", "z"));
assertThat(udf.regexpSplit("--A--A", "-"), contains("", "", "A", "", "A"));
... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Endpoint that = (Endpoint) obj;
return this.port ... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(endpoint1, sameAsEndpoint1)
.addEqualityGroup(endpoint2)
.addEqualityGroup(endpoint3)
.testEquals();
} |
public static boolean isOnList(@Nonnull final Set<String> list, @Nonnull final String ipAddress) {
Ipv4 remoteIpv4;
try {
remoteIpv4 = Ipv4.of(ipAddress);
} catch (IllegalArgumentException e) {
Log.trace("Address '{}' is not an IPv4 address.", ipAddress);
remo... | @Test
public void ipNotOnEmptyList() throws Exception {
// Setup test fixture.
final String input = "203.0.113.251";
final Set<String> list = new HashSet<>();
// Execute system under test.
final boolean result = AuthCheckFilter.isOnList(list, input);
// Verify resul... |
public static Type convertType(TypeInfo typeInfo) {
switch (typeInfo.getOdpsType()) {
case BIGINT:
return Type.BIGINT;
case INT:
return Type.INT;
case SMALLINT:
return Type.SMALLINT;
case TINYINT:
ret... | @Test
public void testConvertTypeCaseDouble() {
TypeInfo typeInfo = TypeInfoFactory.DOUBLE;
Type result = EntityConvertUtils.convertType(typeInfo);
assertEquals(Type.DOUBLE, result);
} |
@Override
public Region createRegion(RegionId regionId, String name, Region.Type type,
Annotations annots, List<Set<NodeId>> masterNodeIds) {
return regionsRepo.compute(regionId, (id, region) -> {
checkArgument(region == null, DUPLICATE_REGION);
return ... | @Test(expected = IllegalArgumentException.class)
public void duplicateCreate() {
store.createRegion(RID1, "R1", METRO, NO_ANNOTS, MASTERS);
store.createRegion(RID1, "R2", CAMPUS, NO_ANNOTS, MASTERS);
} |
@VisibleForTesting
static Map<String, String> parseHeaders(String headerString) {
if (isNullOrEmpty(headerString)) {
return Collections.emptyMap();
}
final Map<String, String> headers = Maps.newHashMap();
for (String headerPart : headerString.trim().split(",")) {
... | @Test
public void testParseHeaders() throws Exception {
assertEquals(0, parseHeaders("").size());
assertEquals(0, parseHeaders(" ").size());
assertEquals(0, parseHeaders(" . ").size());
assertEquals(0, parseHeaders("foo").size());
assertEquals(1, parseHeaders("X-Foo: Bar").si... |
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.OK;
} | @Test
void testResponseStatus() {
assertThat(metricsHandlerHeaders.getResponseStatusCode()).isEqualTo(HttpResponseStatus.OK);
} |
@Override
protected Optional<ErrorResponse> filter(DiscFilterRequest req) {
var now = clock.instant();
var bearerToken = requestBearerToken(req).orElse(null);
if (bearerToken == null) {
log.fine("Missing bearer token");
return Optional.of(new ErrorResponse(Response.St... | @Test
void accepts_valid_token() {
var entry = new AccessLogEntry();
var req = FilterTestUtils.newRequestBuilder()
.withMethod(Method.GET)
.withAccessLogEntry(entry)
.withHeader("Authorization", "Bearer " + READ_TOKEN.secretTokenString())
... |
public QueueCapacityVector parse(String capacityString, QueuePath queuePath) {
if (queuePath.isRoot()) {
return QueueCapacityVector.of(100f, ResourceUnitCapacityType.PERCENTAGE);
}
if (capacityString == null) {
return new QueueCapacityVector();
}
// Trim all spaces from capacity string... | @Test
public void testAbsoluteCapacityVectorConfig() {
CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration();
conf.set(getQueuePrefix(QUEUE_PATH) + CapacitySchedulerConfiguration.CAPACITY,
ABSOLUTE_RESOURCE);
conf.set(YarnConfiguration.RESOURCE_TYPES, RESOURCE_TYPES);
Reso... |
@Override
public void writeBytes(Slice source)
{
writeBytes(source, 0, source.length());
} | @Test
public void testWriteBytes()
throws Exception
{
// fill up some input bytes
int length = 65536;
byte[] inputArray = new byte[length];
for (int i = 0; i < length; i++) {
inputArray[i] = (byte) (i % 128);
}
// pick some offsets to make... |
@PublicAPI(usage = ACCESS)
public String getSimpleName() {
return descriptor.getSimpleClassName();
} | @Test
public void predicate_containAnyConstructorsThat() {
@SuppressWarnings("unused")
class Match {
Match(Serializable param) {
}
}
@SuppressWarnings("unused")
class Mismatch {
Mismatch(String param) {
}
}
JavaC... |
public static <T> T instantiateClassDefConstructor(Class<T> clazz) {
//if constructor present then it should have a no arg constructor
//if not present then default constructor is already their
Objects.requireNonNull(clazz, "class to instantiate should not be null");
if (clazz.getConstru... | @Test
public void shouldFailToInstantiateNoDefaultConstructor() {
assertThatThrownBy(
() -> ClassUtils.instantiateClassDefConstructor(NoDefaultConstructor.class))
.isInstanceOf(InstantiationException.class);
} |
@VisibleForTesting
Job getJob(JobID jobid) throws IOException, InterruptedException {
int maxRetry = getConf().getInt(MRJobConfig.MR_CLIENT_JOB_MAX_RETRIES,
MRJobConfig.DEFAULT_MR_CLIENT_JOB_MAX_RETRIES);
long retryInterval = getConf()
.getLong(MRJobConfig.MR_CLIENT_JOB_RETRY_INTERVAL,
... | @Test
public void testGetJobWithoutRetry() throws Exception {
Configuration conf = new Configuration();
conf.setInt(MRJobConfig.MR_CLIENT_JOB_MAX_RETRIES, 0);
final Cluster mockCluster = mock(Cluster.class);
when(mockCluster.getJob(any(JobID.class))).thenReturn(null);
CLI cli = new CLI(conf);
... |
public boolean retainAll(Collection<?> c) {
throw e;
} | @Test
void require_that_retainAll_throws_exception() {
assertThrows(NodeVector.ReadOnlyException.class, () -> new TestNodeVector("foo").retainAll(null));
} |
public void addDescription(String path, String description)
throws IOException, InvalidTokenException {
Map<String, String[]> tags = new LinkedHashMap<>();
tags.put("description", new String[] {description});
Map<String, Object> body = new LinkedHashMap<>();
body.put("tags", tags);
String url... | @Test
public void testAddDescriptionTokenExpired() throws Exception {
when(credentialFactory.refreshCredential(credential))
.then(
(InvocationOnMock invocation) -> {
final Credential cred = invocation.getArgument(0);
cred.setAccessToken("acc1");
return... |
public synchronized void clear() {
map.clear();
db.clear();
} | @Test
public void testClear() {
Context app = RuntimeEnvironment.application;
HttpUrl url = HttpUrl.parse("http://www.ehviewer.com/");
Cookie cookie = new Cookie.Builder()
.name("user")
.value("1234567890")
.domain("ehviewer.com")
.path("/")
.expiresAt(System.curre... |
public static void putValuesForXPathInListUsingSaxon(
String xmlFile, String xPathQuery,
List<? super String> matchStrings, boolean fragment,
int matchNumber, String namespaces)
throws SaxonApiException, FactoryConfigurationError {
// generating the cache key
... | @Test
public void testputValuesForXPathInListUsingSaxon() throws SaxonApiException, FactoryConfigurationError{
String xPathQuery="//Employees/Employee/role";
ArrayList<String> matchStrings = new ArrayList<>();
boolean fragment = false;
String namespaces = "age=http://www.w3.org/2003/... |
static WebSocketServerHandshaker getHandshaker(Channel channel) {
return channel.attr(HANDSHAKER_ATTR_KEY).get();
} | @Test
public void testWebSocketServerProtocolHandshakeHandlerReplacedBeforeHandshake() {
EmbeddedChannel ch = createChannel(new MockOutboundHandler());
ChannelHandlerContext handshakerCtx = ch.pipeline().context(WebSocketServerProtocolHandshakeHandler.class);
ch.pipeline().addLast(new Channe... |
@Override
public List<V> readAll() {
return get(readAllAsync());
} | @Test
public void testReadAll() {
RTransferQueue<String> queue = redisson.getTransferQueue("queue");
queue.add("1");
queue.add("2");
queue.add("3");
queue.add("4");
assertThat(queue.readAll()).containsExactly("1", "2", "3", "4");
} |
@ScalarOperator(CAST)
@SqlType(StandardTypes.DOUBLE)
public static double castToDouble(@SqlType(StandardTypes.INTEGER) long value)
{
return value;
} | @Test
public void testCastToDouble()
{
assertFunction("cast(INTEGER'37' as double)", DOUBLE, 37.0);
assertFunction("cast(INTEGER'17' as double)", DOUBLE, 17.0);
} |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testTableScanThenIncrementalWithEmptyTable() throws Exception {
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.TABLE_SCAN_THEN_INCREMENTAL)
.build();
ContinuousSplitPlannerImpl splitPlanner =
new ContinuousS... |
public void inputWatermark(Watermark watermark, int channelIndex, DataOutput<?> output)
throws Exception {
final SubpartitionStatus subpartitionStatus;
if (watermark instanceof InternalWatermark) {
int subpartitionStatusIndex = ((InternalWatermark) watermark).getSubpartitionIndex... | @Test
void testMultipleInputDecreasingWatermarksYieldsNoOutput() throws Exception {
StatusWatermarkOutput valveOutput = new StatusWatermarkOutput();
StatusWatermarkValve valve = new StatusWatermarkValve(3);
valve.inputWatermark(new Watermark(25), 0, valveOutput);
valve.inputWatermar... |
public static String getHost(String registry) {
return REGISTRY_HOST_MAP.getOrDefault(registry, registry);
} | @Test
public void testGetHost_noAlias() {
String host = RegistryAliasGroup.getHost("something.gcr.io");
Assert.assertEquals("something.gcr.io", host);
} |
@Override
public CustomResponse<TokenResponse> login(LoginRequest loginRequest) {
return userServiceClient.loginUser(loginRequest);
} | @Test
void givenValidLoginRequest_whenLogin_ReturnsCustomResponse() {
// Given
LoginRequest loginRequest = LoginRequest.builder()
.email("valid.email@example.com")
.password("validPassword123")
.build();
TokenResponse tokenResponse = TokenResp... |
@Override
public WsResponse call(WsRequest wsRequest) {
DefaultLocalRequest localRequest = new DefaultLocalRequest(wsRequest);
LocalConnector.LocalResponse localResponse = localConnector.call(localRequest);
return new ByteArrayResponse(wsRequest.getPath(), localResponse);
} | @Test
public void call_request() throws Exception {
WsRequest wsRequest = new PostRequest("api/issues/search")
.setMediaType(MediaTypes.JSON)
.setParam("foo", "bar");
answer(new DumbLocalResponse(400, MediaTypes.JSON, "{}".getBytes(UTF_8), Collections.<String>emptyList()));
WsResponse wsRespo... |
public StatMap<K> merge(K key, int value) {
if (key.getType() == Type.LONG) {
merge(key, (long) value);
return this;
}
int oldValue = getInt(key);
int newValue = key.merge(oldValue, value);
if (newValue == 0) {
_map.remove(key);
} else {
_map.put(key, newValue);
}
... | @Test(dataProvider = "allTypeStats")
public void singleEncodeDecode(MyStats stat)
throws IOException {
StatMap<MyStats> statMap = new StatMap<>(MyStats.class);
switch (stat.getType()) {
case BOOLEAN:
statMap.merge(stat, true);
break;
case INT:
statMap.merge(stat, 1);
... |
@VisibleForTesting
void checkSourceFileField( String sourceFilenameFieldName, SFTPPutData data ) throws KettleStepException {
// Sourcefilename field
sourceFilenameFieldName = environmentSubstitute( sourceFilenameFieldName );
if ( Utils.isEmpty( sourceFilenameFieldName ) ) {
// source filename field... | @Test
public void checkSourceFileField_NameIsSet_Found() throws Exception {
RowMeta rowMeta = rowOfStringsMeta( "some field", "sourceFileFieldName" );
step.setInputRowMeta( rowMeta );
SFTPPutData data = new SFTPPutData();
step.checkSourceFileField( "sourceFileFieldName", data );
assertEquals( 1, ... |
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId)
throws IOException, InterruptedException {
// We map the input ConnectionID to a new value to restrict the number of tcp connections
connectionId =
new ConnectionID(
co... | @TestTemplate
void testExceptionsAreNotCached() throws Exception {
NettyTestUtil.NettyServerAndClient nettyServerAndClient = createNettyServerAndClient();
try {
final PartitionRequestClientFactory factory =
new PartitionRequestClientFactory(
... |
public static void verifyIncrementPubContent(String content) {
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("publish/delete content can not be null");
}
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);... | @Test
void testVerifyIncrementPubContentFail1() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
String content = null;
ContentUtils.verifyIncrementPubContent(content);
});
assertTrue(exception.getMessage().contains("publish/delete content ... |
@Override
public Collection<SQLToken> generateSQLTokens(final SQLStatementContext sqlStatementContext) {
Collection<ColumnSegment> columnSegments = ((WhereAvailable) sqlStatementContext).getColumnSegments();
Collection<WhereSegment> whereSegments = ((WhereAvailable) sqlStatementContext).getWhereSegm... | @Test
void assertGenerateSQLTokenFromGenerateNewSQLToken() {
generator.setSchemas(Collections.emptyMap());
Collection<SQLToken> substitutableColumnNameTokens = generator.generateSQLTokens(EncryptGeneratorFixtureBuilder.createUpdateStatementContext());
assertThat(substitutableColumnNameTokens... |
public Seckill getSeckill(long seckillId) {
String key = "seckill:" + seckillId;
Seckill seckill = (Seckill) redisTemplate.opsForValue().get(key);
if (seckill != null) {
return seckill;
} else {
seckill = seckillMapper.selectById(seckillId);
if (seckil... | @Test
void getSeckillSuccess() {
long seckillId = 1001L;
String key = "seckill:" + seckillId;
ValueOperations valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
Seckill t = new Seckill();
t.setSeckillId(seckil... |
public static void main(final String[] args)
{
SpringApplication.run(DualStorageDemoApplication.class, args);
} | @Test
void checkPossibilityToSimplyStartAndRestartApplication()
{
this.invoiceConfiguration.getStorageInstance().stop();
this.personConfiguration.getStorageInstance().stop();
DualStorageDemoApplication.main(new String[]{});
} |
public static long memorySize2Byte(final long memorySize, @MemoryConst.Unit final int unit) {
if (memorySize < 0) return -1;
return memorySize * unit;
} | @Test
public void memorySize2ByteInputZeroOutputZero() {
Assert.assertEquals(
0L,
ConvertKit.memorySize2Byte(0L, 0)
);
} |
protected void saveAndRunJobFilters(List<Job> jobs) {
if (jobs.isEmpty()) return;
try {
jobFilterUtils.runOnStateElectionFilter(jobs);
storageProvider.save(jobs);
jobFilterUtils.runOnStateAppliedFilters(jobs);
} catch (ConcurrentJobModificationException concu... | @Test
void ifNoStateChangeHappensStateChangeFiltersAreNotInvoked() {
Job aJobInProgress = aJobInProgress().build();
for (int i = 0; i <= 5; i++) {
task.saveAndRunJobFilters(singletonList(aJobInProgress));
}
assertThat(logAllStateChangesFilter.getStateChanges(aJobInProgr... |
@Override
public Iterable<GenericRow> transform(
final K readOnlyKey,
final GenericRow value,
final KsqlProcessingContext ctx
) {
if (value == null) {
return null;
}
final List<Iterator<?>> iters = new ArrayList<>(tableFunctionAppliers.size());
int maxLength = 0;
for (fi... | @Test
public void shouldFlatMapOneFunction() {
// Given:
final TableFunctionApplier applier = createApplier(Arrays.asList(10, 10, 10));
final KudtfFlatMapper<String> flatMapper =
new KudtfFlatMapper<>(ImmutableList.of(applier), processingLogger);
// When:
final Iterable<GenericRow> iterab... |
@Override
public void process(Tuple input) {
String key = filterMapper.getKeyFromTuple(input);
boolean found;
JedisCommandsContainer jedisCommand = null;
try {
jedisCommand = getInstance();
switch (dataType) {
case STRING:
... | @Test
void smokeTest_exists_keyFound() {
// Define input key
final String inputKey = "ThisIsMyKey";
// Ensure key does exist in redis
jedisHelper.set(inputKey, "some-value");
assertTrue(jedisHelper.exists(inputKey), "Sanity check key exists.");
// Create an input tu... |
public static Builder builder(MetricRegistry metricsRegistry) {
return new Builder().metricsRegistry(metricsRegistry);
} | @Test
public void configurableViaBuilder() {
final MetricRegistry registry = Mockito.mock(MetricRegistry.class);
InstrumentedHttpClientConnectionManager.builder(registry)
.name("some-name")
.name("some-other-name")
.build()
.close();
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.