focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain) {
ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT);
assert shenyuContext != null;
return writerMap.get(shenyuContext.getRpcType()).writeWith(exchange, chain);
} | @Test
public void testExecute() {
ServerWebExchange httpExchange = generateServerWebExchange(RpcTypeEnum.HTTP.getName());
StepVerifier.create(responsePlugin.execute(httpExchange, chain)).expectSubscription().verifyComplete();
ServerWebExchange springCloudExchange = generateServerWebExchange... |
public IndexingResults bulkIndex(final List<MessageWithIndex> messageList) {
return bulkIndex(messageList, false, null);
} | @Test
public void bulkIndexingShouldNotDoAnythingForEmptyList() throws Exception {
final IndexingResults indexingResults = messages.bulkIndex(Collections.emptyList());
assertThat(indexingResults).isNotNull();
assertThat(indexingResults.allResults()).isEmpty();
verify(messagesAdapte... |
public static String toJson(UpdateRequirement updateRequirement) {
return toJson(updateRequirement, false);
} | @Test
public void testAssertDefaultSortOrderIdToJson() {
String requirementType = UpdateRequirementParser.ASSERT_DEFAULT_SORT_ORDER_ID;
int sortOrderId = 10;
String expected =
String.format(
"{\"type\":\"%s\",\"default-sort-order-id\":%d}", requirementType, sortOrderId);
UpdateRequ... |
@Override
public RFuture<Boolean> addAsync(V value) {
CompletableFuture<Boolean> f = CompletableFuture.supplyAsync(() -> add(value), getServiceManager().getExecutor());
return new CompletableFutureWrapper<>(f);
} | @Test
public void testAddAsync() throws InterruptedException, ExecutionException {
RSortedSet<Integer> set = redisson.getSortedSet("simple");
RFuture<Boolean> future = set.addAsync(2);
Assertions.assertTrue(future.get());
Assertions.assertTrue(set.contains(2));
} |
@Override
public boolean wasNull() throws SQLException {
return mergedResult.wasNull();
} | @Test
void assertWasNull() throws SQLException {
assertFalse(new EncryptMergedResult(database, encryptRule, selectStatementContext, mergedResult).wasNull());
} |
void addFunction(final T function) {
final List<ParameterInfo> parameters = function.parameterInfo();
if (allFunctions.put(function.parameters(), function) != null) {
throw new KsqlFunctionException(
"Can't add function " + function.name()
+ " with parameters " + function.parameter... | @Test
public void shouldThrowOnAddIfFunctionWithSameNameAndParamsExists() {
// Given:
givenFunctions(
function(EXPECTED, -1, DOUBLE)
);
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> udfIndex.addFunction(function(EXPECTED, -1, DOUBLE))
);... |
public static String[] getStackFrames(final Throwable throwable) {
if (throwable == null) {
return new String[0];
}
return getStackFrames(getStackTrace(throwable));
} | @Test
void testGetStackFrames() {
String[] stackFrames = ExceptionUtils.getStackFrames(exception);
Assertions.assertNotEquals(0, stackFrames.length);
} |
@Udf
public Map<String, String> records(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final Map<String, String> ret = new HashMap<>... | @Test
public void shouldReturnNullForNull() {
assertNull(udf.records(null));
} |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatNotExpression() {
assertThat(ExpressionFormatter.formatExpression(new NotExpression(new LongLiteral(1))), equalTo("(NOT 1)"));
} |
@Override
public NetconfDevice connectDevice(DeviceId deviceId) throws NetconfException {
return connectDevice(deviceId, true);
} | @Test
public void testConnectDeviceNetConfig10() throws Exception {
NetconfDevice fetchedDevice10 = ctrl.connectDevice(deviceConfig10Id);
assertEquals("Incorrect device fetched - ip",
fetchedDevice10.getDeviceInfo().ip().toString(), DEVICE_10_IP);
assertEquals("Incorrect devi... |
@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 testLoadFiltered() {
PropertiesComponent pc = context.getPropertiesComponent();
Properties properties = pc.loadProperties(k -> k.matches("^start$|.*mock$|.*-profile.*"));
Assertions.assertThat(properties).hasSize(4);
Assertions.assertThat(properties.get("start")).i... |
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCodegen(CodegenUpdateReqVO updateReqVO) {
// 校验是否已经存在
if (codegenTableMapper.selectById(updateReqVO.getTable().getId()) == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
// 校验主表字段存在
... | @Test
public void testUpdateCodegen_sub_masterNotExists() {
// mock 数据
CodegenTableDO table = randomPojo(CodegenTableDO.class,
o -> o.setTemplateType(CodegenTemplateTypeEnum.SUB.getType())
.setScene(CodegenSceneEnum.ADMIN.getScene()));
codegenTableMapp... |
@Nonnull
public Results search(@Nonnull Workspace workspace, @Nonnull Query query) {
return search(workspace, Collections.singletonList(query));
} | @Test
void testEmpty() {
Results results = searchService.search(EmptyWorkspace.get(), new Query() {
// empty query
});
assertTrue(results.isEmpty(), "No results should be found in an empty workspace");
} |
public static UFreeIdent create(CharSequence identifier) {
return new AutoValue_UFreeIdent(StringName.of(identifier));
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(UFreeIdent.create("foo"));
} |
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
if (targetClass != null && targetClass != method.getDeclaringClass() && isOverridable(method, targetClass)) {
try {
if (Modifier.isPublic(method.getModifiers())) {
try {
... | @Test
public void testGetMostSpecificMethodWhichNotExistsInTargetClass() throws NoSuchMethodException {
Method method = ArrayList.class.getDeclaredMethod("sort", Comparator.class);
Method specificMethod = ClassUtils.getMostSpecificMethod(method, Map.class);
assertEquals(ArrayList.class.getDe... |
@Override
public YamlCDCJobConfiguration swapToYamlConfiguration(final CDCJobConfiguration data) {
YamlCDCJobConfiguration result = new YamlCDCJobConfiguration();
result.setJobId(data.getJobId());
result.setDatabaseName(data.getDatabaseName());
result.setSchemaTableNames(data.getSche... | @Test
void assertSwapToYamlConfig() {
CDCJobConfiguration jobConfig = new CDCJobConfiguration("j0302p00007a8bf46da145dc155ba25c710b550220", "test_db", Arrays.asList("t_order", "t_order_item"), true, new MySQLDatabaseType(),
null, null, null, true, new SinkConfiguration(CDCSinkType.SOCKET, ne... |
@Override
public BytesInput getBytes() {
// The Page Header should include: blockSizeInValues, numberOfMiniBlocks, totalValueCount
if (deltaValuesToFlush != 0) {
flushBlockBuffer();
}
return BytesInput.concat(
config.toBytesInput(),
BytesInput.fromUnsignedVarInt(totalValueCount),... | @Test
public void shouldSkipN() throws IOException {
long[] data = new long[5 * blockSize + 1];
for (int i = 0; i < data.length; i++) {
data[i] = i * 32;
}
writeData(data);
reader = new DeltaBinaryPackingValuesReader();
reader.initFromPage(100, writer.getBytes().toInputStream());
int... |
public static HazelcastSqlOperatorTable instance() {
return INSTANCE;
} | @Test
public void testOperandTypeChecker() {
for (SqlOperator operator : HazelcastSqlOperatorTable.instance().getOperatorList()) {
boolean valid = operator instanceof HazelcastOperandTypeCheckerAware
|| operator instanceof HazelcastTableFunction
|| operato... |
public static List<?> convertToList(Schema schema, Object value) {
return convertToArray(ARRAY_SELECTOR_SCHEMA, value);
} | @Test
public void shouldConvertIntegralTypesToDouble() {
double thirdValue = Double.MAX_VALUE;
List<?> list = Values.convertToList(Schema.STRING_SCHEMA, "[1, 2, " + thirdValue + "]");
assertEquals(3, list.size());
assertEquals(1, ((Number) list.get(0)).intValue());
assertEqua... |
@Override
public V get()
throws InterruptedException, ExecutionException {
return peel().get();
} | @Test(expected = InterruptedException.class)
public void get_interrupted() throws Exception {
ScheduledFuture<Object> outer = createScheduledFutureMock();
ScheduledFuture<Object> inner = createScheduledFutureMock();
when(outer.get()).thenThrow(new InterruptedException());
when(inner.... |
@Override
public synchronized Response handle(Request req) { // note the [synchronized]
if (corsEnabled && "OPTIONS".equals(req.getMethod())) {
Response response = new Response(200);
response.setHeader("Allow", ALLOWED_METHODS);
response.setHeader("Access-Control-Allow-Or... | @Test
void testPathParams() {
background().scenario(
"pathMatches('/hello/{name}')",
"def response = 'hello ' + pathParams.name"
);
request.path("/hello/john");
handle();
match(response.getBodyAsString(), "hello john");
} |
@Override
protected double maintain() {
if ( ! nodeRepository().nodes().isWorking()) return 0.0;
// Don't need to maintain spare capacity in dynamically provisioned zones; can provision more on demand.
if (nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0;
NodeList ... | @Test
public void testAllWorksAsSpares() {
var tester = new SpareCapacityMaintainerTester();
tester.addHosts(4, new NodeResources(10, 100, 1000, 1));
tester.addNodes(0, 2, new NodeResources(5, 50, 500, 0.5), 0);
tester.addNodes(1, 2, new NodeResources(5, 50, 500, 0.5), 2);
te... |
public B metadataReportConfig(MetadataReportConfig metadataReportConfig) {
this.metadataReportConfig = metadataReportConfig;
return getThis();
} | @Test
void metadataReportConfig() {
MetadataReportConfig metadataReportConfig = new MetadataReportConfig();
InterfaceBuilder builder = new InterfaceBuilder();
builder.metadataReportConfig(metadataReportConfig);
Assertions.assertEquals(metadataReportConfig, builder.build().getMetada... |
public ImmutableMap<String, Object> readAttributes(File file, String attributes) {
String view = getViewName(attributes);
List<String> attrs = getAttributeNames(attributes);
if (attrs.size() > 1 && attrs.contains(ALL_ATTRIBUTES)) {
// attrs contains * and other attributes
throw new IllegalArgum... | @Test
public void testReadAttributes_asMap_failsForInvalidAttributes() {
File file = createFile();
try {
service.readAttributes(file, "basic:fileKey,isOther,*,creationTime");
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).contains("invalid attribu... |
@Override
public void processInitState(OpenstackNode osNode) {
if (!isOvsdbConnected(osNode, ovsdbPortNum, ovsdbController, deviceService)) {
ovsdbController.connect(osNode.managementIp(), tpPort(ovsdbPortNum));
return;
}
if (!deviceService.isAvailable(osNode.intgBri... | @Test
public void testComputeNodeProcessNodeInitState() {
testNodeManager.createNode(COMPUTE_1);
TEST_DEVICE_SERVICE.devMap.put(COMPUTE_1_OVSDB_DEVICE.id(), COMPUTE_1_OVSDB_DEVICE);
assertEquals(ERR_STATE_NOT_MATCH, INIT,
testNodeManager.node(COMPUTE_1_HOSTNAME).state());
... |
public static final StartTime relative(Duration relativeStart) {
return new StartTime(StartTimeOption.RELATIVE, relativeStart, null);
} | @Test
public void testStartRelative() {
StartTime st = StartTime.relative(Duration.ofMinutes(20));
assertEquals(StartTimeOption.RELATIVE, st.option());
assertEquals(20 * 60, st.relativeTime().getSeconds());
assertNull(st.absoluteTime());
} |
public static String getUniqueSlotName(final Connection connection, final String slotNameSuffix) throws SQLException {
String slotName = DigestUtils.md5Hex(String.join("_", connection.getCatalog(), slotNameSuffix).getBytes());
return String.format("%s_%s", SLOT_NAME_PREFIX, slotName);
} | @Test
void assertGetUniqueSlotName() throws SQLException {
Connection connection = mock(Connection.class);
when(connection.getCatalog()).thenReturn("foo_catalog");
assertThat(PostgreSQLSlotNameGenerator.getUniqueSlotName(connection, "foo_slot"), is("pipeline_9a2b4a79ce8b4fca2835b1e947c446eb"... |
@PostMapping(value = "/listener")
public void listener(final HttpServletRequest request, final HttpServletResponse response) {
longPollingListener.doLongPolling(request, response);
} | @Test
public void testListener() throws Exception {
// Run the test
final MockHttpServletResponse response = mockMvc.perform(post("/configs/listener")
.accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
// Verify the results
assertThat(re... |
@Override
public Buffer.DataType peekNextToConsumeDataType(
int nextBufferToConsume, Collection<Buffer> buffersToRecycle) {
Buffer.DataType dataType = Buffer.DataType.NONE;
try {
dataType =
checkAndGetFirstBufferIndexOrError(nextBufferToConsume, buffersToR... | @Test
void testPeekNextToConsumeDataType() throws Throwable {
TestingSubpartitionConsumerInternalOperation viewNotifier =
new TestingSubpartitionConsumerInternalOperation();
HsSubpartitionFileReaderImpl subpartitionFileReader =
createSubpartitionFileReader(0, viewNoti... |
public void insertSiblingAfter(PDOutlineItem newSibling)
{
requireSingleNode(newSibling);
PDOutlineNode parent = getParent();
newSibling.setParent(parent);
PDOutlineItem next = getNextSibling();
setNextSibling(newSibling);
newSibling.setPreviousSibling(this);
... | @Test
void cannotInsertSiblingAfterAList()
{
PDOutlineItem child = new PDOutlineItem();
child.insertSiblingAfter(new PDOutlineItem());
child.insertSiblingAfter(new PDOutlineItem());
assertThrows(IllegalArgumentException.class, () -> root.insertSiblingAfter(child));
} |
public static LatLong fromString(String latLongString) {
double[] coordinates = parseCoordinateString(latLongString, 2);
return new LatLong(coordinates[0], coordinates[1]);
} | @Test
public void fromStringValidTest() {
LatLong latLong = LatLongUtils.fromString(LATITUDE + DELIMITER + LONGITUDE);
Assert.assertEquals(LATITUDE, latLong.latitude, 0);
Assert.assertEquals(LONGITUDE, latLong.longitude, 0);
} |
public static org.apache.pinot.common.utils.regex.Matcher matcher(Pattern pattern, CharSequence input) {
if (pattern instanceof Re2jPattern) {
return new Re2jMatcher(pattern, input);
} else {
return new JavaUtilMatcher(pattern, input);
}
} | @Test
public void testJavaUtilMatcherFactory() {
JavaUtilPattern javaUtilPattern = new JavaUtilPattern("pattern");
Matcher matcher = MatcherFactory.matcher(javaUtilPattern, "");
Assert.assertTrue(matcher instanceof JavaUtilMatcher);
} |
@SuppressWarnings("unchecked")
public static <T extends SpecificRecord> TypeInformation<Row> convertToTypeInfo(
Class<T> avroClass) {
return convertToTypeInfo(avroClass, true);
} | @Test
void testAvroClassConversion() {
validateUserSchema(AvroSchemaConverter.convertToTypeInfo(User.class));
} |
public JobStatsExtended enrich(JobStats jobStats) {
JobStats latestJobStats = getLatestJobStats(jobStats, previousJobStats);
if (lock.tryLock()) {
setFirstRelevantJobStats(latestJobStats);
setJobStatsExtended(latestJobStats);
setPreviousJobStats(latestJobStats);
... | @Test
void enrichGivenNoPreviousJobStatsAndWorkToDoEnqueuedAndProcessing() {
JobStatsExtended extendedJobStats = jobStatsEnricher.enrich(getJobStats(1L, 1L, 0L, 0L));
assertThat(extendedJobStats.getAmountSucceeded()).isZero();
assertThat(extendedJobStats.getAmountFailed()).isZero();
... |
String getFileName(double lat, double lon) {
int lonInt = getMinLonForTile(lon);
int latInt = getMinLatForTile(lat);
return toLowerCase(getLatString(latInt) + getNorthString(latInt) + getLonString(lonInt) + getEastString(lonInt) + FILE_NAME_END);
} | @Disabled
@Test
public void testGetEleHorizontalBorder() {
// Border between the tiles 50n000e and 50n030e
assertEquals("50n000e_20101117_gmted_mea075", instance.getFileName(53, 29.999999));
assertEquals(143, instance.getEle(53, 29.999999), precision);
assertEquals("50n030e_20101... |
public boolean hasSameNameAs(Header header) {
AssertParameter.notNull(header, Header.class);
return this.name.equalsIgnoreCase(header.getName());
} | @Test
public void header_does_not_have_same_name_as_expected() {
final Header header1 = new Header("foo", "bar");
final Header header2 = new Header("bar", "baz");
assertThat(header2.hasSameNameAs(header1)).isFalse();
} |
@Operation(description = "BSNKActivate retrieves a PIP based on a BSN")
@PostMapping(value = "/bsnk_activate", consumes = "application/json", produces = "application/json")
@ResponseBody
public BsnkActivateResponse bsnkActivate(@Valid @RequestBody BsnkActivateRequest request) throws BsnkException {
... | @Test
public void bsnkActivateResponseOkTest() throws BsnkException {
BsnkActivateRequest request = new BsnkActivateRequest();
request.setBsn("PPPPPPPPP");
Mockito.when(bsnkActivateService.bsnkActivate(any())).thenReturn("pip");
BsnkActivateResponse result = controller.bsnkActivate... |
@Override
public int getTransactionTimeout() throws XAException {
return delegate.getTransactionTimeout();
} | @Test
void assertGetTransactionTimeout() throws XAException {
singleXAResource.getTransactionTimeout();
verify(xaResource).getTransactionTimeout();
} |
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) {
GuardedByExpression expr = BINDER.visit(exp, context);
checkGuardedBy(expr != null, String.valueOf(exp));
checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp);
return expr;
} | @Test
public void inherited() {
assertThat(
bind(
"Test",
"slock",
forSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"class Super {",
" final Object slock =... |
public static long getPid() {
return ProcessHandle.current().pid();
} | @Test
public void testGetPid() {
long legacyPidResult = getPidLegacy();
assumeThat(legacyPidResult).isNotEqualTo(-1);
assertEquals(legacyPidResult, JVMUtil.getPid());
} |
@Override
public synchronized List<PrivilegedOperation> postComplete(
ContainerId containerId) throws ResourceHandlerException {
gpuAllocator.unassignGpus(containerId);
cGroupsHandler.deleteCGroup(CGroupsHandler.CGroupController.DEVICES,
containerId.toString());
return null;
} | @Test
public void testAllocationWhenDockerContainerEnabled() throws Exception {
// When docker container is enabled, no devices should be written to
// devices.deny.
initializeGpus();
startContainerWithGpuRequestsDocker(1, 3);
verifyDeniedDevices(getContainerId(1), Collections.emptyList());
... |
@GwtIncompatible("java.util.regex.Pattern")
public void doesNotContainMatch(@Nullable Pattern regex) {
checkNotNull(regex);
if (actual == null) {
failWithActual("expected a string that does not contain a match for", regex);
return;
}
Matcher matcher = regex.matcher(actual);
if (matcher... | @Test
@GwtIncompatible("Pattern")
public void stringDoesNotContainMatchPatternFailNull() {
expectFailureWhenTestingThat(null).doesNotContainMatch(Pattern.compile(".b."));
assertFailureValue("expected a string that does not contain a match for", ".b.");
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof InboundPacket) {
final DefaultInboundPacket other = (DefaultInboundPacket) obj;
return Objects.equals(this.receivedFrom, other.receivedFrom) &&
... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(packet1, sameAsPacket1)
.addEqualityGroup(packet2, sameAsPacket2)
.testEquals();
} |
public static NacosNamingServiceWrapper createNamingService(URL connectionURL) {
boolean check = connectionURL.getParameter(NACOS_CHECK_KEY, true);
int retryTimes = connectionURL.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = connectionURL.getPositiveParameter(NACOS_RETRY... | @Test
void testRetryCreate() throws NacosException {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
NamingService mock = new MockNamingService() {
@Override
... |
public ModelReproduction<T> reproduceFromModel() throws ClassNotFoundException, JsonProcessingException {
if(this.originalModel == null){
throw new IllegalStateException("No model to reproduce was provided");
}
Model<T> newModel = reproduceFromProvenance();
TreeSet<String> ... | @Test
public void testReproduceFromModel() throws IOException, URISyntaxException, ClassNotFoundException {
CSVDataSource<Label> csvSource = getCSVDataSource();
MutableDataset<Label> datasetFromCSV = new MutableDataset<>(csvSource);
LogisticRegressionTrainer trainer = new LogisticRegression... |
public int getAndAdvanceCurrentIndex() {
int idx = this.getCurrentIndex();
this.advanceIndex();
return idx;
} | @Test
public void testDefaultPattern() {
// Mux of size 1: 0 0 0 0 0, etc
mux = new WeightedRoundRobinMultiplexer(1, "", new Configuration());
for(int i = 0; i < 10; i++) {
assertThat(mux.getAndAdvanceCurrentIndex()).isZero();
}
// Mux of size 2: 0 0 1 0 0 1 0 0 1, etc
mux = new Weighte... |
public static Entry entry(String name) throws BlockException {
return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0);
} | @Test
public void testMethodEntryType() throws BlockException, NoSuchMethodException, SecurityException {
Method method = SphUTest.class.getMethod("testMethodEntryNormal");
Entry e = SphU.entry(method, EntryType.IN);
assertSame(e.resourceWrapper.getEntryType(), EntryType.IN);
e.exi... |
@Override
public boolean isControlBatch() {
return (attributes() & CONTROL_FLAG_MASK) > 0;
} | @Test
public void testReadAndWriteControlBatch() {
long producerId = 1L;
short producerEpoch = 0;
int coordinatorEpoch = 15;
ByteBuffer buffer = ByteBuffer.allocate(128);
MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE,
... |
@Benchmark
@Threads(16)
public void testLargeBundleHarnessStateSampler(HarnessStateTracker state, Blackhole bh)
throws Exception {
state.tracker.start("processBundleId");
for (int i = 0; i < 1000; ) {
state.state1.activate();
state.state2.activate();
state.state3.activate();
//... | @Test
public void testLargeBundleHarnessStateSampler() throws Exception {
HarnessStateSampler state = new HarnessStateSampler();
HarnessStateTracker threadState = new HarnessStateTracker();
threadState.setup(state);
new ExecutionStateSamplerBenchmark().testLargeBundleHarnessStateSampler(threadState, b... |
public static Object applyLogicalType(Schema.Field field, Object value) {
if (field == null || field.schema() == null) {
return value;
}
Schema fieldSchema = resolveUnionSchema(field.schema());
return applySchemaTypeLogic(fieldSchema, value);
} | @Test
public void testApplyLogicalTypeReturnsSameValueWhenNotConversionForLogicalTypeIsKnown() {
String value = "abc";
String schemaString =
new StringBuilder().append("{").append(" \"type\": \"record\",").append(" \"name\": \"test\",")
.append(" \"fields\": [{").append(" \"name\": \... |
@Override
public ProtobufSystemInfo.Section toProtobuf() {
ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder();
protobuf.setName("System");
setAttribute(protobuf, "Server ID", server.getId());
setAttribute(protobuf, "Version", getVersion());
setAttribute(protobuf... | @Test
public void toProtobuf_whenNoAllowsToSignUpEnabledIdentityProviders_shouldWriteNothing() {
when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(emptyList());
ProtobufSystemInfo.Section protobuf = underTest.toProtobuf();
assertThatAttributeDoesNotExist(protobuf, "Exte... |
public static Map<String, String> getExternalResourceConfigurationKeys(
Configuration config, String suffix) {
final Set<String> resourceSet = getExternalResourceSet(config);
final Map<String, String> configKeysToResourceNameMap = new HashMap<>();
LOG.info("Enabled external resources... | @Test
public void testGetExternalResourceConfigurationKeysWithConflictConfigKey() {
final Configuration config = new Configuration();
config.set(ExternalResourceOptions.EXTERNAL_RESOURCE_LIST, RESOURCE_LIST);
config.setString(
ExternalResourceOptions.getSystemConfigKeyConfig... |
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", expectedExceptions = IllegalArgumentException.class)
public void dynamicTypeCheckPutBoolean(MyStats stat) {
if (stat.getType() == StatMap.Type.BOOLEAN) {
throw new SkipException("Skipping BOOLEAN test");
}
StatMap<MyStats> statMap = new StatMap<>(MyStats.class);
... |
public static Instant garbageCollectionTime(
BoundedWindow window, WindowingStrategy windowingStrategy) {
return garbageCollectionTime(window, windowingStrategy.getAllowedLateness());
} | @Test
public void garbageCollectionTimeAfterEndOfGlobalWindow() {
FixedWindows windowFn = FixedWindows.of(Duration.standardMinutes(5));
WindowingStrategy<?, ?> strategy = WindowingStrategy.globalDefault().withWindowFn(windowFn);
IntervalWindow window = windowFn.assignWindow(BoundedWindow.TIMESTAMP_MAX_VA... |
public static boolean isPullRequest(Item item) {
// TODO probably want to be using SCMHeadCategory instances to categorize them instead of hard-coding for PRs
return SCMHead.HeadByItem.findHead(item) instanceof ChangeRequestSCMHead;
} | @Test
public void testIsPullRequest(){
BlueOrganization organization = mockOrganization();
OrganizationFolder organizationFolder = mockOrgFolder(organization);
PullRequestSCMHead changeRequestSCMHead = Mockito.mock(PullRequestSCMHead.class);
mockedStatic = Mockito.mockStatic(SCMHead.... |
public static String[] splitString( String string, String separator ) {
/*
* 0123456 Example a;b;c;d --> new String[] { a, b, c, d }
*/
// System.out.println("splitString ["+path+"] using ["+separator+"]");
List<String> list = new ArrayList<>();
if ( string == null || string.length() == 0 ) {... | @Test
public void testSplitStringWithNestedEscapedEnclosure() {
String[] result;
String enclosure = "\"";
String delimiter = ",";
// Actual data contains enclosure withing data with escaped enclosure like: "0","Test\"Data1","Test\"Data2","Test\"Data3"
String splitString = "\"0\",\"Test\\\"Data1\",... |
public static String getHeader(boolean qOption) {
return qOption ? ALL_HEADER : SUMMARY_HEADER;
} | @Test
public void testGetHeaderWithQuota() {
String header = " QUOTA REM_QUOTA SPACE_QUOTA "
+ "REM_SPACE_QUOTA DIR_COUNT FILE_COUNT CONTENT_SIZE ";
assertEquals(header, ContentSummary.getHeader(true));
} |
@Udf(description = "Subtracts a duration from a time")
public Time timeSub(
@UdfParameter(description = "A unit of time, for example SECOND or HOUR") final TimeUnit unit,
@UdfParameter(
description = "An integer number of intervals to subtract") final Integer interval,
@UdfParameter(descri... | @Test
public void handleNullTime() {
assertNull(udf.timeSub(TimeUnit.MILLISECONDS, -300, null));
} |
public <T> T convert(String property, Class<T> targetClass) {
final AbstractPropertyConverter<?> converter = converterRegistry.get(targetClass);
if (converter == null) {
throw new MissingFormatArgumentException("converter not found, can't convert from String to " + targetClass.getCanonicalNa... | @Test
void testConvertBooleanForEmptyProperty() {
assertNull(compositeConverter.convert(null, Boolean.class));
} |
@Override
public Set<Principal> getPrincipals() {
throw notAllowed("getPrincipals");
} | @Test(expected=UnsupportedOperationException.class)
public void testGetPrincipals() {
ctx.getPrincipals();
} |
public String getHost() {
if (host == null) {
try {
host = HostUtils.getLocalHostName();
} catch (UnknownHostException e) {
LOG.warn(e.getMessage(), e);
host = "unknown";
}
}
return host;
} | @Test
public void testHostDefaultIsNotNull() {
SplunkHECConfiguration config = new SplunkHECConfiguration();
assertNotNull(config.getHost());
} |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void convert_metric_to_lower_case() {
ProjectMeasuresQuery query = newProjectMeasuresQuery(asList(
Criterion.builder().setKey("NCLOC").setOperator(GT).setValue("10").build(),
Criterion.builder().setKey("coVERage").setOperator(LTE).setValue("80").build()),
emptySet());
assertTha... |
@VisibleForTesting
void validateDictTypeNameUnique(Long id, String name) {
DictTypeDO dictType = dictTypeMapper.selectByName(name);
if (dictType == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的字典类型
if (id == null) {
throw exception(DICT_TYPE_NAME_DUPL... | @Test
public void testValidateDictTypeNameUnique_nameDuplicateForUpdate() {
// 准备参数
Long id = randomLongId();
String name = randomString();
// mock 数据
dictTypeMapper.insert(randomDictTypeDO(o -> o.setName(name)));
// 调用,校验异常
assertServiceException(() -> dictT... |
public static List<Criterion> parse(String filter) {
return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false)
.map(FilterParser::parseCriterion)
.toList();
} | @Test
public void parse_filter_having_in_empty_list() {
List<Criterion> criterion = FilterParser.parse("languages IN ()");
assertThat(criterion)
.extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue)
.containsOnly(
tuple("languages", IN, Collecti... |
@Override
public void collect(MetricsEmitter metricsEmitter) {
for (Map.Entry<MetricKey, KafkaMetric> entry : ledger.getMetrics()) {
MetricKey metricKey = entry.getKey();
KafkaMetric metric = entry.getValue();
try {
collectMetric(metricsEmitter, metricKey... | @Test
public void testSecondDeltaCollectDouble() {
Sensor sensor = metrics.sensor("test");
sensor.add(metricName, new CumulativeSum());
sensor.record();
sensor.record();
time.sleep(60 * 1000L);
testEmitter.onlyDeltaMetrics(true);
collector.collect(testEmitte... |
public List<KinesisRecord> apply(List<KinesisRecord> records, ShardCheckpoint checkpoint) {
List<KinesisRecord> filteredRecords = newArrayList();
for (KinesisRecord record : records) {
if (checkpoint.isBeforeOrAt(record)) {
filteredRecords.add(record);
}
}
return filteredRecords;
} | @Test
public void shouldFilterOutRecordsBeforeOrAtCheckpoint() {
when(checkpoint.isBeforeOrAt(record1)).thenReturn(false);
when(checkpoint.isBeforeOrAt(record2)).thenReturn(true);
when(checkpoint.isBeforeOrAt(record3)).thenReturn(true);
when(checkpoint.isBeforeOrAt(record4)).thenReturn(false);
whe... |
@Override
public Local find(final Host bookmark) {
if(null != bookmark.getDownloadFolder()) {
if(bookmark.getDownloadFolder().exists()) {
return bookmark.getDownloadFolder();
}
}
final Local directory = LocalFactory.get(preferences.getProperty("queue.d... | @Test
public void testFind() throws Exception {
final Host host = new Host(new TestProtocol());
assertNull(host.getDownloadFolder());
final DownloadDirectoryFinder finder = new DownloadDirectoryFinder();
assertEquals(System.getProperty("user.dir"), finder.find(host).getAbsolute());
... |
@Override
public Map<String, String> getAddresses() {
AwsCredentials credentials = awsCredentialsProvider.credentials();
List<String> taskAddresses = emptyList();
if (!awsConfig.anyOfEc2PropertiesConfigured()) {
taskAddresses = awsEcsApi.listTaskPrivateAddresses(cluster, credenti... | @Test
public void getAddressesNoPublicAddresses() {
// given
List<String> privateIps = singletonList("123.12.1.0");
Map<String, String> privateToPublicIps = singletonMap("123.12.1.0", null);
given(awsEcsApi.listTaskPrivateAddresses(CLUSTER, CREDENTIALS)).willReturn(privateIps);
... |
private static Map<String, Set<Dependency>> checkOptionalFlags(
Map<String, Set<Dependency>> bundledDependenciesByModule,
Map<String, DependencyTree> dependenciesByModule) {
final Map<String, Set<Dependency>> allViolations = new HashMap<>();
for (String module : bundledDependen... | @Test
void testDirectBundledOptionalDependencyIsAccepted() {
final Dependency dependency = createOptionalDependency("a");
final Set<Dependency> bundled = Collections.singleton(dependency);
final DependencyTree dependencyTree = new DependencyTree().addDirectDependency(dependency);
fi... |
static void move(File src, File dest) throws IOException {
try {
Files.move(src.toPath(), dest.toPath());
} catch (IOException x) {
throw x;
} catch (RuntimeException x) {
throw new IOException(x);
}
} | @Test public void move() throws Exception {
File src = tmp.newFile();
File dest = new File(tmp.getRoot(), "dest");
RunIdMigrator.move(src, dest);
File dest2 = tmp.newFile();
assertThrows(IOException.class, () -> RunIdMigrator.move(dest, dest2));
} |
boolean hasMoreAvailableCapacityThan(final ClientState other) {
if (capacity <= 0) {
throw new IllegalStateException("Capacity of this ClientState must be greater than 0.");
}
if (other.capacity <= 0) {
throw new IllegalStateException("Capacity of other ClientState must ... | @Test
public void shouldThrowIllegalStateExceptionIfCapacityOfOtherClientStateIsZero() {
assertThrows(IllegalStateException.class, () -> client.hasMoreAvailableCapacityThan(zeroCapacityClient));
} |
@Override
public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewName(), "New name must not be null!");
byte[] ... | @Test
public void testRename() {
connection.stringCommands().set(originalKey, value).block();
if (hasTtl) {
connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block();
}
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyFor... |
public Optional<String> getType(Set<String> streamIds, String field) {
final Map<String, Set<String>> allFieldTypes = this.get(streamIds);
final Set<String> fieldTypes = allFieldTypes.get(field);
return typeFromFieldType(fieldTypes);
} | @Test
void returnsFieldTypeIfSingleTypeExistsForFieldInAllStreams() {
final Pair<IndexFieldTypesService, StreamService> services = mockServices(
IndexFieldTypesDTO.create("indexSet1", "stream1", ImmutableSet.of(
FieldTypeDTO.create("somefield", "long")
... |
public static StreamedRow toRowFromDelimited(final Buffer buff) {
try {
final QueryResponseMetadata metadata = deserialize(buff, QueryResponseMetadata.class);
return StreamedRow.header(new QueryId(Strings.nullToEmpty(metadata.queryId)),
createSchema(metadata));
} catch (KsqlRestClientExcepti... | @Test
public void shouldParseError() {
// When:
final StreamedRow row = KsqlTargetUtil.toRowFromDelimited(Buffer.buffer(
"{\"@type\":\"generic_error\",\"error_code\": 500,\"message\":\"Really bad problem\"}"));
// Then:
assertThat(row.getErrorMessage().isPresent(), is(true));
assertThat(r... |
@Udf
public <T> List<T> slice(
@UdfParameter(description = "the input array") final List<T> in,
@UdfParameter(description = "start index") final Integer from,
@UdfParameter(description = "end index") final Integer to) {
if (in == null) {
return null;
}
try {
// ... | @Test
public void shouldOneIndexSlice() {
// Given:
final List<String> list = Lists.newArrayList("a", "b", "c");
// When:
final List<String> slice = new Slice().slice(list, 1, 2);
// Then:
assertThat(slice, is(Lists.newArrayList("a", "b")));
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testSetPlatforms_emptyPlatformsSet() {
try {
ContainerBuildPlan.builder().setPlatforms(Collections.emptySet());
Assert.fail();
} catch (IllegalArgumentException ex) {
Assert.assertEquals("platforms set cannot be empty", ex.getMessage());
}
} |
public Path extract(Path targetPath) throws IOException, UserException {
try {
Path zipPath = downloadZip(targetPath);
return extractZip(zipPath, targetPath);
} finally {
// clean temp path;
for (Path p : cleanPathList) {
FileUtils.deleteQu... | @Test
public void testExtract() {
try {
Files.copy(PluginTestUtil.getTestPath("source/test.zip"), PluginTestUtil.getTestPath("source/test-a.zip"));
PluginZip util = new PluginZip(PluginTestUtil.getTestPathString("source/test-a.zip"), null);
Path actualPath = util.extrac... |
public static String substVars(String val, PropertyContainer pc1) throws ScanException {
return substVars(val, pc1, null);
} | @Test
public void trailingColon_LOGBACK_1140() throws ScanException {
String prefix = "c:";
String suffix = "/tmp";
context.putProperty("var", prefix);
String r = OptionHelper.substVars("${var}" + suffix, context);
assertEquals(prefix + suffix, r);
} |
public String getQueryCondition() {
StringBuilder sb = new StringBuilder();
if (!StringUtils.isEmpty(taskId)) {
sb.append("task_id = '").append(taskId).append("'").append(LINK);
}
if (!CollectionUtils.isEmpty(taskIds)) {
String taskIdsInQuery = taskIds.stream().m... | @Test
void test() {
SimpleTaskQuery simpleTaskQuery = new SimpleTaskQuery();
simpleTaskQuery.setInstanceId(10086L);
simpleTaskQuery.setTaskIds(Lists.newArrayList("taskId1", "taskId2", "taskId3"));
String queryCondition = simpleTaskQuery.getQueryCondition();
System.out.printl... |
@NotNull
public SocialUserDO authSocialUser(Integer socialType, Integer userType, String code, String state) {
// 优先从 DB 中获取,因为 code 有且可以使用一次。
// 在社交登录时,当未绑定 User 时,需要绑定登录,此时需要 code 使用两次
SocialUserDO socialUser = socialUserMapper.selectByTypeAndCodeAnState(socialType, code, state);
i... | @Test
public void testAuthSocialUser_insert() {
// 准备参数
Integer socialType = SocialTypeEnum.GITEE.getType();
Integer userType = randomEle(SocialTypeEnum.values()).getType();
String code = "tudou";
String state = "yuanma";
// mock 方法
AuthUser authUser = randomP... |
public User id(Long id) {
this.id = id;
return this;
} | @Test
public void idTest() {
// TODO: test id
} |
public List<IdentityProvider> getAllEnabledAndSorted() {
return providersByKey.values().stream()
.filter(IS_ENABLED_FILTER)
.sorted(Comparator.comparing(TO_NAME))
.toList();
} | @Test
public void return_sorted_enabled_providers() {
IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET));
List<IdentityProvider> providers = underTest.getAllEnabledAndSorted();
assertThat(providers).containsExactly(BITBUCKET, GITHUB);
} |
public static <InputT, OutputT> DoFnInvoker<InputT, OutputT> invokerFor(
DoFn<InputT, OutputT> fn) {
return ByteBuddyDoFnInvokerFactory.only().newByteBuddyInvoker(fn);
} | @Test
public void testOnWindowExpirationWithNoParam() throws Exception {
class MockFn extends DoFn<String, String> {
@ProcessElement
public void process(ProcessContext c) {}
@OnWindowExpiration
public void onWindowExpiration() {}
}
MockFn fn = mock(MockFn.class);
DoFnInvoker... |
@Deprecated
public static String getJwt(JwtClaims claims) throws JoseException {
String jwt;
RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName());
// A JWT is a JWS and/... | @Test
public void longlivedLightPortalConfigServer() throws Exception {
JwtClaims claims = ClaimsUtil.getTestClaims("stevehu@gmail.com", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e73", Arrays.asList("portal.r", "portal.w"), "user CfgPltAdmin CfgPltRead CfgPltWrite");
claims.setExpirationTimeMinu... |
public static String mobilePhone(String num) {
if (StrUtil.isBlank(num)) {
return StrUtil.EMPTY;
}
return StrUtil.hide(num, 3, num.length() - 4);
} | @Test
public void mobilePhoneTest() {
assertEquals("180****1999", DesensitizedUtil.mobilePhone("18049531999"));
} |
@VisibleForTesting
Map<ExecutionVertexID, Collection<ExecutionAttemptID>> findSlowTasks(
final ExecutionGraph executionGraph) {
final long currentTimeMillis = System.currentTimeMillis();
final Map<ExecutionVertexID, Collection<ExecutionAttemptID>> slowTasks = new HashMap<>();
f... | @Test
void testAllTasksInCreatedAndNoSlowTasks() throws Exception {
final int parallelism = 3;
final JobVertex jobVertex = createNoOpVertex(parallelism);
final JobGraph jobGraph = JobGraphTestUtils.streamingJobGraph(jobVertex);
// all tasks are in the CREATED state, which is not cla... |
public CellFormatter getFormatter(String columnId) {
checkId(columnId);
CellFormatter fmt = formatters.get(columnId);
return fmt == null ? DEF_FMT : fmt;
} | @Test
public void defaultFormatter() {
tm = new TableModel(FOO);
fmt = tm.getFormatter(FOO);
assertTrue("Wrong formatter", fmt instanceof DefaultCellFormatter);
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateCastToInteger() {
// Given:
final Expression cast1 = new Cast(
new LongLiteral(10L),
new Type(SqlPrimitiveType.of("INTEGER"))
);
final Expression cast2 = new Cast(
new StringLiteral("1234"),
new Type(SqlPrimitiveType.of("INTEGER"))
);... |
@Bean
@ConditionalOnMissingBean(TaskQueue.class)
@Qualifier("taskQueue")
@ConditionalOnProperty("shenyu.shared-pool.max-work-queue-memory")
public TaskQueue<Runnable> memoryLimitedTaskQueue(final ShenyuConfig shenyuConfig) {
final Instrumentation instrumentation = ByteBuddyAgent.install();
... | @Test
public void testMemoryLimitedTaskQueue() {
ShenyuConfig shenyuConfig = mock(ShenyuConfig.class);
ShenyuConfig.SharedPool sharedPool = mock(ShenyuConfig.SharedPool.class);
when(shenyuConfig.getSharedPool()).thenReturn(sharedPool);
when(sharedPool.getMaxWorkQueueMemory()).thenRet... |
@Override
public boolean matches(String name, Metric metric) {
return patterns.stream().anyMatch(pattern -> pattern.matcher(name).matches());
} | @Test
void test() {
final List<MapperConfig> mapperConfigs = ImmutableList.of(
new MapperConfig("foo.*.bar.*.baz", "test1", Collections.emptyMap()),
new MapperConfig("hello.world", "test2", Collections.emptyMap())
);
final PrometheusMetricFilter filter = new ... |
public ProcessCommands createAfterClean(int processNumber) {
return createForProcess(processNumber, true);
} | @Test
public void getProcessCommands_fails_if_processNumber_is_less_than_0() throws Exception {
try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) {
int processNumber = -2;
assertThatThrownBy(() -> commands.createAfterClean(processNumber))
.isInstanceOf(IllegalAr... |
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, ... | @Test
public void unorderedFlattenIndex_with_valueFunction_returns_SetMultimap() {
SetMultimap<Integer, String> multimap = LIST2.stream()
.collect(unorderedFlattenIndex(MyObj2::getId, MyObj2::getTexts));
assertThat(multimap.size()).isEqualTo(4);
Map<Integer, Collection<String>> map = multimap.asMap... |
public static double round(double value, int decimalPlaces) {
double factor = Math.pow(10, decimalPlaces);
return Math.round(value * factor) / factor;
} | @Test
public void testRound() {
assertEquals(100.94, Helper.round(100.94, 2), 1e-7);
assertEquals(100.9, Helper.round(100.94, 1), 1e-7);
assertEquals(101.0, Helper.round(100.95, 1), 1e-7);
// using negative values for decimalPlaces means we are rounding with precision > 1
ass... |
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
} | @Test
public void testWhenOptionIsDefinedOnMultipleInterfacesOnlyListedOnceWhenNotPresent() {
JoinedOptions options = PipelineOptionsFactory.as(JoinedOptions.class);
options.setFoo("Hello");
options.setRunner(CrashingRunner.class);
expectedException.expect(IllegalArgumentException.class);
expecte... |
@SuppressWarnings("unchecked")
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
if (metric == null) {
throw new NullPointerException("metric == null");
}
if (metric instanceof MetricRegistry) {
final MetricRegistry childR... | @Test
public void registeringAMeterTriggersANotification() {
assertThat(registry.register("thing", meter))
.isEqualTo(meter);
verify(listener).onMeterAdded("thing", meter);
} |
public static <T> T retryUntilTimeout(Callable<T> callable, Supplier<String> description, Duration timeoutDuration, long retryBackoffMs) throws Exception {
return retryUntilTimeout(callable, description, timeoutDuration, retryBackoffMs, Time.SYSTEM);
} | @Test
public void noRetryAndFailed() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
TimeoutException e = assertThrows(TimeoutException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(0), 10... |
public RegisteredClient() {
this.client = new ClientDetailsEntity();
} | @Test
public void testRegisteredClient() {
// make sure all the pass-through getters and setters work
RegisteredClient c = new RegisteredClient();
c.setClientId("s6BhdRkqt3");
c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk");
c.setClientSecretExpiresAt(new Date(1577858400L * 1000L));
c.s... |
@Override
public void setUnixPermission(final Path file, final TransferStatus status) throws BackgroundException {
final FileAttributes attr = new FileAttributes.Builder()
.withPermissions(Integer.parseInt(status.getPermission().getMode(), 8))
.build();
try {
... | @Test
public void testSetUnixPermission() throws Exception {
final Path home = new SFTPHomeDirectoryService(session).find();
{
final Path file = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
new SFTPTouchFeature(session).touch(file, new TransferSta... |
public RuleDescriptionSectionsGenerator getRuleDescriptionSectionsGenerator(RulesDefinition.Rule ruleDef) {
Set<RuleDescriptionSectionsGenerator> generatorsFound = ruleDescriptionSectionsGenerators.stream()
.filter(generator -> generator.isGeneratorForRule(ruleDef))
.collect(toSet());
checkState(gen... | @Test
public void getRuleDescriptionSectionsGenerator_whenNoGeneratorFound_throwsWithCorrectMessage() {
assertThatIllegalStateException()
.isThrownBy(() -> resolver.getRuleDescriptionSectionsGenerator(rule))
.withMessage("No rule description section generator found for rule with key RULE_KEY");
} |
@Override
public Mono<ExtensionStore> delete(String name, Long version) {
return repository.findById(name)
.flatMap(extensionStore -> {
// reset the version
extensionStore.setVersion(version);
return repository.delete(extensionStore).thenReturn(ext... | @Test
void shouldDoNotThrowExceptionWhenDeletingNonExistExt() {
when(repository.findById(anyString())).thenReturn(Mono.empty());
client.delete("/registry/posts/hello-halo", 1L).block();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.