focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public PackageRepository findPackageRepositoryWithPackageIdOrBomb(String packageId) {
PackageRepository packageRepository = findPackageRepositoryHaving(packageId);
if (packageRepository == null){
throw new RuntimeException(format("Could not find repository for given package id:[%s]", package... | @Test
void shouldThrowExceptionWhenRepositoryForGivenPackageNotFound() throws Exception {
PackageRepositories packageRepositories = new PackageRepositories();
try {
packageRepositories.findPackageRepositoryWithPackageIdOrBomb("invalid");
fail("should have thrown exception fo... |
public static long estimateSize(StructType tableSchema, long totalRecords) {
if (totalRecords == Long.MAX_VALUE) {
return totalRecords;
}
long result;
try {
result = LongMath.checkedMultiply(tableSchema.defaultSize(), totalRecords);
} catch (ArithmeticException e) {
result = Long.... | @Test
public void testEstimateSize() throws IOException {
long tableSize = SparkSchemaUtil.estimateSize(SparkSchemaUtil.convert(TEST_SCHEMA), 1);
Assert.assertEquals("estimateSize matches with expected approximation", 24, tableSize);
} |
@Override
public String getFileId(final Path file) throws BackgroundException {
try {
if(StringUtils.isNotBlank(file.attributes().getFileId())) {
return file.attributes().getFileId();
}
final String cached = super.getFileId(file);
if(cached != ... | @Test
public void getFileIdTrash() throws Exception {
assertEquals(EueResourceIdProvider.TRASH, new EueResourceIdProvider(session).getFileId(new Path("Gelöschte Dateien", EnumSet.of(directory))));
} |
public ExecutionContext generateExecutionContext(final QueryContext queryContext, final RuleMetaData globalRuleMetaData,
final ConfigurationProperties props, final ConnectionContext connectionContext) {
check(queryContext);
RouteContext routeContext =... | @Test
void assertGenerateExecutionContext() {
DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE");
SQLStatementContext sqlStatementContext = mock(CommonSQLStatementContext.class);
when(sqlStatementContext.getSqlStatement()).thenReturn(mock(SelectStatement.cla... |
public List<ParsedTerm> filterElementsContainingUsefulInformation(final Map<String, List<ParsedTerm>> parsedTermsGroupedByField) {
return parsedTermsGroupedByField.values()
.stream()
.map(this::filterElementsContainingUsefulInformation)
.flatMap(Collection::stream... | @Test
void limitsToOneTermOnlyIfMultipleTermsWithoutPosition() {
final Map<String, List<ParsedTerm>> fieldTerms = Map.of("field", List.of(
ParsedTerm.create("field", "oh!"),
ParsedTerm.create("field", "ah!"),
ParsedTerm.create("field", "eh!")
));
... |
@Override
protected void copy(List<AzfsResourceId> srcPaths, List<AzfsResourceId> destPaths)
throws IOException {
checkArgument(
srcPaths.size() == destPaths.size(),
"sizes of source paths and destination paths do not match");
Iterator<AzfsResourceId> sourcePathsIterator = srcPaths.iter... | @Test
@SuppressWarnings("CheckReturnValue")
public void testCopy() throws IOException {
List<AzfsResourceId> src =
new ArrayList<>(
Arrays.asList(AzfsResourceId.fromComponents("account", "container", "from")));
List<AzfsResourceId> dest =
new ArrayList<>(Arrays.asList(AzfsResourc... |
public void verifyAndValidate(final String jwt) {
try {
Jws<Claims> claimsJws = Jwts.parser()
.verifyWith(tokenConfigurationParameter.getPublicKey())
.build()
.parseSignedClaims(jwt);
// Log the claims for debugging purposes
C... | @Test
void givenTokens_whenVerifyAndValidate_thenValidateEachToken() {
// Given
Set<String> tokens = Set.of(
Jwts.builder().claim("user_id", "12345").issuedAt(new Date()).expiration(new Date(System.currentTimeMillis() + 86400000L)).signWith(keyPair.getPrivate()).compact(),
... |
public UniVocityFixedDataFormat setFieldLengths(int[] fieldLengths) {
this.fieldLengths = fieldLengths;
return this;
} | @Test
public void shouldConfigureHeaderExtractionEnabled() {
UniVocityFixedDataFormat dataFormat = new UniVocityFixedDataFormat()
.setFieldLengths(new int[] { 1, 2, 3 })
.setHeaderExtractionEnabled(true);
assertTrue(dataFormat.getHeaderExtractionEnabled());
a... |
public H3IndexResolution getResolution() {
return _resolution;
} | @Test
public void withDisabledNull()
throws JsonProcessingException {
String confStr = "{\"disabled\": null}";
H3IndexConfig config = JsonUtils.stringToObject(confStr, H3IndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
assertNull(config.getResolution(), "Unexpected r... |
public ConcurrentHashMap<String, DefaultExecutor> getExecutorMap() {
return executorMap;
} | @Test
void testInvalidCommand() throws InterpreterException {
if (System.getProperty("os.name").startsWith("Windows")) {
result = shell.interpret("invalid_command\ndir", context);
} else {
result = shell.interpret("invalid_command\nls", context);
}
assertEquals(Code.SUCCESS, result.code())... |
@Override
public byte[] getValueFromText(String text) {
throw new UnsupportedOperationException(format("Type of input not handled: %s", JMSPublisherGui.USE_TEXT_RSC));
} | @Test
public void getValueFromText() {
Assertions.assertThrows(UnsupportedOperationException.class, () -> render.getValueFromText(""));
} |
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
this.config = TbNodeUtils.convert(configuration, TbCheckRelationNodeConfiguration.class);
if (config.isCheckForSingleEntity()) {
if (StringUtils.isEmpty(config.getEntityType()) || String... | @Test
void givenDefaultConfig_whenInit_then_throwException() {
// GIVEN
var config = new TbCheckRelationNodeConfiguration().defaultConfiguration();
// WHEN
var exception = assertThrows(TbNodeException.class, () -> node.init(ctx, new TbNodeConfiguration(JacksonUtil.valueToTree(config... |
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithMethods(bean.getClass(), recurringJobFinderMethodCallback);
return bean;
} | @Test
void beansWithMethodsUsingJobContextAnnotatedWithRecurringCronAnnotationWillAutomaticallyBeRegistered() {
// GIVEN
final RecurringJobPostProcessor recurringJobPostProcessor = getRecurringJobPostProcessor();
// WHEN
recurringJobPostProcessor.postProcessAfterInitialization(new M... |
public CompletableFuture<Integer> read(ByteBuffer buf, long offset, long len, FileId fileId,
String ufsPath, UfsReadOptions options) {
Objects.requireNonNull(buf);
if (offset < 0 || len < 0 || len > buf.remaining()) {
throw new OutOfRangeRuntimeException(String.format(
"offset is negative,... | @Test
public void readOverlap() throws Exception {
mUfsIOManager.read(TEST_BUF, 2, TEST_BLOCK_SIZE - 2, FIRST_BLOCK_ID, mTestFilePath,
UfsReadOptions.getDefaultInstance()).get();
assertTrue(checkBuf(2, (int) TEST_BLOCK_SIZE - 2, TEST_BUF));
TEST_BUF.clear();
mUfsIOManager.read(TEST_BUF, TEST_B... |
public boolean shouldDropFrame(final InetSocketAddress address, final UnsafeBuffer buffer, final int length)
{
return false;
} | @Test
void multiSmallGap()
{
final MultiGapLossGenerator generator = new MultiGapLossGenerator(0, 16, 8, 4);
assertFalse(generator.shouldDropFrame(null, null, 123, 456, 0, 0, 8));
assertFalse(generator.shouldDropFrame(null, null, 123, 456, 0, 8, 8));
assertTrue(generator.shouldDr... |
public static ConfigurableResource parseResourceConfigValue(String value)
throws AllocationConfigurationException {
return parseResourceConfigValue(value, Long.MAX_VALUE);
} | @Test
public void testAbsoluteMemoryNegativeFractional() throws Exception {
expectNegativeValueOfResource("memory");
parseResourceConfigValue(" -5120.3 mb, 2.35 vcores ");
} |
public boolean matchStage(StageConfigIdentifier stageIdentifier, StageEvent event) {
return this.event.include(event) && appliesTo(stageIdentifier.getPipelineName(), stageIdentifier.getStageName());
} | @Test
void allEventShouldMatchAnyEvents() {
NotificationFilter filter = new NotificationFilter("cruise", "dev", StageEvent.All, false);
assertThat(filter.matchStage(new StageConfigIdentifier("cruise", "dev"), StageEvent.Breaks)).isTrue();
} |
public static QueryableRequestSpecification query(RequestSpecification specification) {
if (specification instanceof QueryableRequestSpecification) {
return (QueryableRequestSpecification) specification;
}
throw new IllegalArgumentException("Cannot convert " + specification + " to a ... | @Test public void
specification_querier_allows_querying_request_specifications() {
// Given
RequestSpecification spec = new RequestSpecBuilder().addHeader("header", "value").addCookie("cookie", "cookieValue").addParam("someparam", "somevalue").build();
// When
QueryableRequestSpecif... |
public static Optional<Boolean> parseBooleanExact(final String value) {
if (booleanStringMatches(value, true)) {
return Optional.of(true);
}
if (booleanStringMatches(value, false)) {
return Optional.of(false);
}
return Optional.empty();
} | @Test
public void shouldParseExactEverythingElseAsEmpty() {
assertThat(SqlBooleans.parseBooleanExact("No "), is(Optional.empty()));
assertThat(SqlBooleans.parseBooleanExact(" true"), is(Optional.empty()));
assertThat(SqlBooleans.parseBooleanExact(" f "), is(Optional.empty()));
assertThat(SqlBooleans.p... |
public RatingValue increment(Rating rating) {
if (value.compareTo(rating) > 0) {
value = rating;
}
this.set = true;
return this;
} | @Test
public void increment_has_no_effect_if_arg_is_null() {
verifyUnsetValue(new RatingValue().increment((RatingValue) null));
} |
public static URI getCanonicalUri(URI uri, int defaultPort) {
// skip if there is no authority, ie. "file" scheme or relative uri
String host = uri.getHost();
if (host == null) {
return uri;
}
String fqHost = canonicalizeHost(host);
int port = uri.getPort();
// short out if already can... | @Test
public void testCanonicalUriWithNoAuthority() {
URI uri;
uri = NetUtils.getCanonicalUri(URI.create("scheme:/"), 2);
assertEquals("scheme:/", uri.toString());
uri = NetUtils.getCanonicalUri(URI.create("scheme:/path"), 2);
assertEquals("scheme:/path", uri.toString());
uri = NetUtils.get... |
public static int toInt(final String str, final int defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
} | @Test
public void testToInReturnDefaultValueWithNull() {
Assertions.assertEquals(10, NumberUtils.toInt(null, 10));
} |
void start(Iterable<ShardCheckpoint> checkpoints) {
LOG.info(
"Pool {} - starting for stream {} consumer {}. Checkpoints = {}",
poolId,
read.getStreamName(),
consumerArn,
checkpoints);
for (ShardCheckpoint shardCheckpoint : checkpoints) {
checkState(
!stat... | @Test
public void poolReSubscribesAndSkipsAllRecordsWithAtTimestampGreaterThanRecords()
throws Exception {
kinesis = new EFOStubbedKinesisAsyncClient(10);
kinesis.stubSubscribeToShard("shard-000", eventWithRecords(3));
kinesis.stubSubscribeToShard("shard-001", eventWithRecords(11, 3));
Instant ... |
private boolean authenticate(final ChannelHandlerContext context, final ByteBuf message) {
try {
AuthenticationResult authResult = databaseProtocolFrontendEngine.getAuthenticationEngine().authenticate(context,
databaseProtocolFrontendEngine.getCodecEngine().createPacketPayload(me... | @Test
void assertChannelReadNotAuthenticated() throws Exception {
channel.register();
AuthenticationResult authenticationResult = AuthenticationResultBuilder.finished("username", "hostname", "database");
when(authenticationEngine.authenticate(any(ChannelHandlerContext.class), any(PacketPaylo... |
public synchronized void transfer(int accountA, int accountB, int amount) {
if (accounts[accountA] >= amount && accountA != accountB) {
accounts[accountB] += amount;
accounts[accountA] -= amount;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Transferred from account: {} to acco... | @Test
void TransferMethodHaveToTransferAmountFromAnAccountToOtherAccount() {
bank.transfer(0, 1, 1000);
int[] accounts = bank.getAccounts();
assertEquals(0, accounts[0]);
assertEquals(2000, accounts[1]);
} |
@Scheduled(initialDelay = 60, fixedRate = 60, timeUnit = TimeUnit.SECONDS)
public void refreshLocalCache() {
// 情况一:如果缓存里没有数据,则直接刷新缓存
if (CollUtil.isEmpty(sensitiveWordCache)) {
initLocalCache();
return;
}
// 情况二,如果缓存里数据,则通过 updateTime 判断是否有数据变更,有变更则刷新缓存
... | @Test
public void testRefreshLocalCache() {
// mock 数据
SensitiveWordDO wordDO1 = randomPojo(SensitiveWordDO.class, o -> o.setName("傻瓜")
.setTags(singletonList("论坛")).setStatus(CommonStatusEnum.ENABLE.getStatus()));
wordDO1.setUpdateTime(LocalDateTime.now());
sensitive... |
@Override
public ExpressionEvaluatorResult evaluateUnaryExpression(String rawExpression, Object resultValue, Class<?> resultClass) {
Map<String, Object> params = new HashMap<>();
params.put(ACTUAL_VALUE_IDENTIFIER, resultValue);
Object expressionResult = compileAndExecute(rawExpression, par... | @Test
public void evaluateUnaryExpression() {
assertThat(evaluator.evaluateUnaryExpression(mvelExpression("java.util.Objects.equals(" + ACTUAL_VALUE_IDENTIFIER + ", \"Test\")"), "Test", String.class)).is(successful);
assertThat(evaluator.evaluateUnaryExpression(mvelExpression("java.util.Objects.equa... |
@Override
public boolean hasPrivileges(final String database) {
return true;
} | @Test
void assertHasPrivileges() {
assertTrue(new AllPermittedPrivileges().hasPrivileges("foo_db"));
} |
String toLogMessage(TbMsg msg) {
return "\n" +
"Incoming message:\n" + msg.getData() + "\n" +
"Incoming metadata:\n" + JacksonUtil.toString(msg.getMetaData().getData());
} | @Test
void givenEmptyDataMsg_whenToLog_thenReturnString() {
TbLogNode node = new TbLogNode();
TbMsgMetaData metaData = new TbMsgMetaData(Collections.emptyMap());
TbMsg msg = TbMsg.newMsg(TbMsgType.POST_TELEMETRY_REQUEST, TenantId.SYS_TENANT_ID, metaData, "");
String logMessage = nod... |
public static DecimalType findMultiplicationDecimalType(
int precision1, int scale1, int precision2, int scale2) {
int scale = scale1 + scale2;
int precision = precision1 + precision2 + 1;
return adjustPrecisionScale(precision, scale);
} | @Test
void testFindMultiplicationDecimalType() {
assertThat(LogicalTypeMerging.findMultiplicationDecimalType(30, 10, 30, 10))
.hasPrecisionAndScale(38, 6);
assertThat(LogicalTypeMerging.findMultiplicationDecimalType(30, 20, 30, 20))
.hasPrecisionAndScale(38, 17);
... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
try {
Alarm alarm = JacksonUtil.fromString(msg.getData(), Alarm.class);
Objects.requireNonNull(alarm, "alarm is null");
ListenableFuture<Alarm> latest = ctx.getAlarmService().findAlarmByIdAsync... | @Test
void givenActiveAlarm_whenOnMsg_then_True() throws TbNodeException {
// GIVEN
var alarm = new Alarm();
alarm.setId(ALARM_ID);
alarm.setOriginator(DEVICE_ID);
alarm.setType("General Alarm");
String msgData = JacksonUtil.toString(alarm);
TbMsg msg = getTb... |
public float getProtectThreshold() {
return protectThreshold;
} | @Test
void testGetProtectThreshold() {
assertEquals(0.0F, serviceMetadata.getProtectThreshold(), 0);
} |
public static void ensureMarkFileLink(final File serviceDir, final File actualFile, final String linkFilename)
{
final String serviceDirPath;
final String markFileParentPath;
try
{
serviceDirPath = serviceDir.getCanonicalPath();
}
catch (final IOException... | @Test
void shouldRemoveLinkFileIfMarkFileIsInServiceDirectory() throws IOException
{
final String linkFilename = "markfile.lnk";
final File markFileLocation = new File(serviceDirectory, "markfile.dat");
final File linkFileLocation = new File(serviceDirectory, linkFilename);
asse... |
public static void format(Mode mode, AlluxioConfiguration alluxioConf) throws IOException {
NoopUfsManager noopUfsManager = new NoopUfsManager();
switch (mode) {
case MASTER:
URI journalLocation = JournalUtils.getJournalLocation();
LOG.info("Formatting master journal: {}", journalLocation)... | @Test
public void formatWorkerDeleteFileSameName() throws Exception {
final int storageLevels = 1;
String workerDataFolder;
final File[] dirs = new File[] {
mTemporaryFolder.newFolder("level0")
};
// Have files of same name as the target worker data dir in each tier
for (File dir : dir... |
@Override
public WebhookDelivery call(Webhook webhook, WebhookPayload payload) {
WebhookDelivery.Builder builder = new WebhookDelivery.Builder();
long startedAt = system.now();
builder
.setAt(startedAt)
.setPayload(payload)
.setWebhook(webhook);
try {
HttpUrl url = HttpUrl.par... | @Test
public void silently_catch_error_when_external_server_does_not_answer() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null);
server.shutdown();
WebhookDelivery delivery = newSend... |
public static boolean isPortable(SamzaPipelineOptions options) {
Map<String, String> override = options.getConfigOverride();
if (override == null) {
return false;
}
return Boolean.parseBoolean(override.getOrDefault(BEAM_PORTABLE_MODE, "false"));
} | @Test
public void testNonPortableModeNullConfig() {
SamzaPipelineOptions mockOptions = mock(SamzaPipelineOptions.class);
doReturn(null).when(mockOptions).getConfigOverride();
Assert.assertFalse(
"Expected false for portable mode ", PortableConfigUtils.isPortable(mockOptions));
} |
@Override
public synchronized void subscribe(final Subscriber<Collection<StreamedRow>> subscriber) {
final PullQuerySubscription subscription = new PullQuerySubscription(
exec, subscriber, result);
result.start();
final WebSocketSubscriber<StreamedRow> webSocketSubscriber =
(WebSocketSub... | @Test
public void shouldSubscribe() {
// When:
publisher.subscribe(subscriber);
// Then:
verify(subscriber).onSubscribe(any(), any(), anyLong());
} |
public boolean denied(String name, MediaType mediaType) {
String suffix = (name.contains(".") ? name.substring(name.lastIndexOf(".") + 1) : "").toLowerCase(Locale.ROOT);
boolean defaultDeny = false;
if (CollectionUtils.isNotEmpty(denyFiles)) {
if (denyFiles.contains(suffix)) {
... | @Test
public void testDenyWithDeny(){
FileUploadProperties uploadProperties=new FileUploadProperties();
uploadProperties.setDenyFiles(new HashSet<>(Arrays.asList("exe")));
assertFalse(uploadProperties.denied("test.xls", MediaType.ALL));
assertTrue(uploadProperties.denied("test.exe"... |
@Override
public Local create(final Path file) {
return this.create(String.format("%s-%s", new AlphanumericRandomStringService().random(), file.getName()));
} | @Test
public void testPathNotTooLong() {
final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator);
final String testPathDirectory = "/Lorem/ipsum/dolor/sit/amet/consetetur/sadipscing/elitr/sed/diam/nonumy/eirmod/tempor";
final String testPathFile = "tak... |
public ConfigData get(String path) {
if (allowedPaths == null) {
throw new IllegalStateException("The provider has not been configured yet.");
}
Map<String, String> data = new HashMap<>();
if (path == null || path.isEmpty()) {
return new ConfigData(data);
... | @Test
public void testGetOneKeyAtPath() {
ConfigData configData = configProvider.get("dummy", Collections.singleton("testKey"));
Map<String, String> result = new HashMap<>();
result.put("testKey", "testResult");
assertEquals(result, configData.data());
assertNull(configData.t... |
@Override
@SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "unchecked"})
public E poll() {
final E[] buffer = consumerBuffer;
final long index = consumerIndex;
final long mask = consumerMask;
final long offset = modifiedCalcElementOffset(index, mask);
Object e = lvElement(buffer, off... | @Test(dataProvider = "populated")
public void poll_whenPopulated(MpscGrowableArrayQueue<Integer> queue) {
assertThat(queue.poll()).isNotNull();
assertThat(queue).hasSize(POPULATED_SIZE - 1);
} |
public BlockLease flatten(Block block)
{
requireNonNull(block, "block is null");
if (block instanceof DictionaryBlock) {
return flattenDictionaryBlock((DictionaryBlock) block);
}
if (block instanceof RunLengthEncodedBlock) {
return flattenRunLengthEncodedBlock... | @Test
public void testNestedRLEs()
{
Block block = createTestRleBlock(createTestRleBlock(createTestRleBlock(createLongArrayBlock(5), 1), 1), 4);
assertEquals(block.getPositionCount(), 4);
try (BlockLease blockLease = flattener.flatten(block)) {
Block flattenedBlock = blockLea... |
public long getBacklogBytes(String streamName, Instant countSince)
throws TransientKinesisException {
return getBacklogBytes(streamName, countSince, new Instant());
} | @Test
public void shouldNotCallCloudWatchWhenSpecifiedPeriodTooShort() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T10:00:02.000Z");
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(ba... |
public static boolean writeFile(File file, byte[] content, boolean append) {
try (FileOutputStream fos = new FileOutputStream(file, append);
FileChannel fileChannel = fos.getChannel()) {
ByteBuffer buffer = ByteBuffer.wrap(content);
fileChannel.write(buffer);
... | @Test
void writeFile() {
assertTrue(DiskUtils.writeFile(testFile, "unit test".getBytes(StandardCharsets.UTF_8), false));
assertEquals("unit test", DiskUtils.readFile(testFile));
} |
public Statement buildStatement(final ParserRuleContext parseTree) {
return build(Optional.of(getSources(parseTree)), parseTree);
} | @Test
public void shouldHandleQualifiedSelectStarOnLeftJoinSource() {
// Given:
final SingleStatementContext stmt =
givenQuery("SELECT TEST1.* FROM TEST1 JOIN TEST2 WITHIN 1 SECOND ON TEST1.ID = TEST2.ID;");
// When:
final Query result = (Query) builder.buildStatement(stmt);
// Then:
... |
@Override
public Iterable<SingleTableInventoryCalculatedResult> calculate(final SingleTableInventoryCalculateParameter param) {
PipelineDataConsistencyCalculateSQLBuilder pipelineSQLBuilder = new PipelineDataConsistencyCalculateSQLBuilder(param.getDatabaseType());
List<CalculatedItem> calculatedItem... | @Test
void assertCalculateFailed() throws SQLException {
when(connection.prepareStatement(anyString())).thenThrow(new SQLException(""));
assertThrows(PipelineTableDataConsistencyCheckLoadingFailedException.class, () -> new CRC32SingleTableInventoryCalculator().calculate(parameter));
} |
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) {
List<String> diagramLines = filterOutComments(rawDiagramLines);
Set<PlantUmlComponent> components = parseComponents(diagramLines);
PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components);
List<Parse... | @Test
public void rejects_a_component_with_an_illegal_alias() {
File file = TestDiagram.in(temporaryFolder)
.component("irrelevant").withAlias("ill[]egal").withStereoTypes("..irrelevant..")
.write();
assertThatThrownBy(() -> createDiagram(file))
.isIn... |
public Object toIdObject(String baseId) throws AmqpProtocolException {
if (baseId == null) {
return null;
}
try {
if (hasAmqpUuidPrefix(baseId)) {
String uuidString = strip(baseId, AMQP_UUID_PREFIX_LENGTH);
return UUID.fromString(uuidStrin... | @Test
public void testToIdObjectWithEncodedUuid() throws Exception {
UUID uuid = UUID.randomUUID();
String provided = AMQPMessageIdHelper.AMQP_UUID_PREFIX + uuid.toString();
Object idObject = messageIdHelper.toIdObject(provided);
assertNotNull("null object should not have been retur... |
@Override
public void handleGlobalFailure(Throwable cause) {
final FailureEnricher.Context ctx =
DefaultFailureEnricherContext.forGlobalFailure(
jobInfo, jobManagerJobMetricGroup, ioExecutor, userCodeClassLoader);
final CompletableFuture<Map<String, String>> f... | @Test
void testExceptionHistoryWithGlobalFailureLabels() throws Exception {
final Exception expectedException = new Exception("Global Exception to label");
BiConsumer<AdaptiveScheduler, List<ExecutionAttemptID>> testLogic =
(scheduler, attemptIds) -> scheduler.handleGlobalFailure(exp... |
public void updateAcl( UIRepositoryObjectAcl aclToUpdate ) {
List<ObjectAce> aces = obj.getAces();
for ( ObjectAce ace : aces ) {
if ( ace.getRecipient().getName().equals( aclToUpdate.getRecipientName() ) ) {
ace.setPermissions( aclToUpdate.getPermissionSet() );
}
}
UIRepositoryObjec... | @Test
public void testUpdateAcl() {
List<UIRepositoryObjectAcl> originalUIAcls = Arrays.asList( new UIRepositoryObjectAcl[] { objectAcl1, objectAcl2 } );
repositoryObjectAcls.addAcls( originalUIAcls );
objectAcl2.addPermission( RepositoryFilePermission.DELETE );
repositoryObjectAcls.updateAcl( obje... |
public static URI parse(String gluePath) {
requireNonNull(gluePath, "gluePath may not be null");
if (gluePath.isEmpty()) {
return rootPackageUri();
}
// Legacy from the Cucumber Eclipse plugin
// Older versions of Cucumber allowed it.
if (CLASSPATH_SCHEME_PRE... | @Test
void can_parse_root_package() {
URI uri = GluePath.parse("classpath:/");
assertAll(
() -> assertThat(uri.getScheme(), is("classpath")),
() -> assertThat(uri.getSchemeSpecificPart(), is("/")));
} |
@Override
public String getMediaType() {
return firstNonNull(
mediaTypeFromUrl(source.getRequestURI()),
firstNonNull(
acceptedContentTypeInResponse(),
MediaTypes.DEFAULT));
} | @Test
public void default_media_type_is_octet_stream() {
when(source.getRequestURI()).thenReturn("/path/to/resource/search");
assertThat(underTest.getMediaType()).isEqualTo(MediaTypes.DEFAULT);
} |
public double getHeight() {
return this.bottom - this.top;
} | @Test
public void getHeightTest() {
Rectangle rectangle = create(1, 2, 3, 4);
Assert.assertEquals(2, rectangle.getHeight(), 0);
} |
@Override
protected URIRegisterDTO buildURIRegisterDTO(final ApplicationContext context,
final Map<String, ServiceFactoryBean> beans) {
return URIRegisterDTO.builder()
.contextPath(this.getContextPath())
.appName(this.getAppNam... | @Test
public void testBuildURIRegisterDTO() {
URIRegisterDTO expectedURIRegisterDTO = URIRegisterDTO.builder()
.contextPath(CONTEXT_PATH)
.appName(APP_NAME)
.rpcType(RpcTypeEnum.SOFA.getName())
.eventType(EventType.REGISTER)
.ho... |
public static SMAppService mainAppService() {
return CLASS.mainAppService();
} | @Test
public void testMainAppService() {
assumeFalse(Factory.Platform.osversion.matches("(10|11|12)\\..*"));
assertNotNull(SMAppService.mainAppService());
} |
@SuppressWarnings("WeakerAccess")
public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) {
final Map<String, Object> consumerProps = getCommonConsumerConfigs();
// Get main consumer override configs
final Map<String, Object> mainC... | @SuppressWarnings("deprecation")
@Test
public void shouldNotSetInternalThrowOnFetchStableOffsetUnsupportedConfigToFalseInConsumerForEosAlpha() {
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, EXACTLY_ONCE);
final StreamsConfig streamsConfig = new StreamsConfig(props);
final Map<Str... |
public EnumSet<RepositoryFilePermission> processCheckboxes() {
return processCheckboxes( false );
} | @Test
public void testProcessCheckboxesReadCheckedEnableAppropriateTrue() {
when( readCheckbox.isChecked() ).thenReturn( true );
when( writeCheckbox.isChecked() ).thenReturn( false );
when( deleteCheckbox.isChecked() ).thenReturn( false );
when( manageCheckbox.isChecked() ).thenReturn( false );
as... |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldCoerceStringNumericWithDecimalPointToDecimals() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of(
new IntegerLiteral(10),
new StringLiteral("1.0")
);
// When:
final Result result = CoercionUtil.coerceUserList(expressions, typeManag... |
public String start(WorkflowInstance instance) {
return workflowExecutor.startWorkflow(
translator.translate(instance),
Collections.singletonMap(
Constants.WORKFLOW_SUMMARY_FIELD,
workflowHelper.createWorkflowSummaryFromInstance(instance)),
null,
null,
... | @Test
public void testStart() {
WorkflowInstance instance = new WorkflowInstance();
instance.setWorkflowId("test-workflow");
instance.setWorkflowVersionId(1);
instance.setRuntimeWorkflow(mock(Workflow.class));
instance.setRuntimeDag(Collections.singletonMap("step1", new StepTransition()));
Map... |
public static String simplyEnvNameIfOverLimit(String envName) {
if (StringUtils.isNotBlank(envName) && envName.length() > MAX_ENV_NAME_LENGTH) {
return envName.substring(0, MAX_ENV_NAME_LENGTH) + MD5Utils.md5Hex(envName, "UTF-8");
}
return envName;
} | @Test
void testSimplyEnvNameNotOverLimit() {
String expect = "test";
assertEquals(expect, ParamUtil.simplyEnvNameIfOverLimit(expect));
} |
@GuardedBy("lock")
private boolean isLeader(ResourceManager<?> resourceManager) {
return running && this.leaderResourceManager == resourceManager;
} | @Test
void revokeLeadership_stopExistLeader() throws Exception {
final UUID leaderSessionId = UUID.randomUUID();
final CompletableFuture<UUID> terminateRmFuture = new CompletableFuture<>();
rmFactoryBuilder.setTerminateConsumer(terminateRmFuture::complete);
createAndStartResourceMa... |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE);
} | @Test
void givenTypeCircle_whenOnMsg_thenTrue() throws TbNodeException {
// GIVEN
var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration();
config.setPerimeterType(PerimeterType.CIRCLE);
node.init(ctx, new TbNodeConfiguration(JacksonUtil.valueToTree(config)));... |
@Override
public String getConfigDirectory() {
final String configDir =
flinkConfig
.getOptional(DeploymentOptionsInternal.CONF_DIR)
.orElse(flinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR));
checkNotNull(configDir);
ret... | @Test
void getConfigDirectory() {
final String confDir = "/path/of/flink-conf";
flinkConfig.set(DeploymentOptionsInternal.CONF_DIR, confDir);
assertThat(testingKubernetesParameters.getConfigDirectory()).isEqualTo(confDir);
} |
public void setOwnerBits(Bits bits) {
mOwnerBits = bits;
} | @Test
public void setOwnerBits() {
Mode mode = new Mode((short) 0000);
mode.setOwnerBits(Mode.Bits.READ_EXECUTE);
assertEquals(Mode.Bits.READ_EXECUTE, mode.getOwnerBits());
mode.setOwnerBits(Mode.Bits.WRITE);
assertEquals(Mode.Bits.WRITE, mode.getOwnerBits());
mode.setOwnerBits(Mode.Bits.ALL);... |
@Override
public BigDecimal getDecimal(final int columnIndex) {
return values.getDecimal(columnIndex - 1);
} | @Test
public void shouldGetDecimal() {
assertThat(row.getDecimal("f_decimal"), is(new BigDecimal("12.21")));
} |
public Optional<Object> evaluate(final Map<String, Object> columnPairsMap, final String outputColumn,
final String regexField) {
boolean matching = true;
boolean isRegex =
regexField != null && columnValues.containsKey(regexField) && (boolean) columnV... | @Test
void evaluateKeyFoundMatchingNoOutputColumnFound() {
KiePMMLRow kiePMMLRow = new KiePMMLRow(COLUMN_VALUES);
Optional<Object> retrieved = kiePMMLRow.evaluate(Collections.singletonMap("KEY-1", 1), "NOT-KEY", null);
assertThat(retrieved).isNotPresent();
} |
@Override
public boolean registerListener(Object listener) {
if (listener instanceof HazelcastInstanceAware aware) {
aware.setHazelcastInstance(node.hazelcastInstance);
}
if (listener instanceof ClusterVersionListener clusterVersionListener) {
clusterVersionListeners.... | @Test
public void test_clusterVersionListener_invokedOnRegistration() {
final CountDownLatch latch = new CountDownLatch(1);
ClusterVersionListener listener = newVersion -> latch.countDown();
assertTrue(nodeExtension.registerListener(listener));
assertOpenEventually(latch);
} |
protected static boolean isSingleQuoted(String input) {
if (input == null || input.isBlank()) {
return false;
}
return input.matches("(^" + QUOTE_CHAR + "{1}([^" + QUOTE_CHAR + "]+)" + QUOTE_CHAR + "{1})");
} | @Test
public void testSingleQuoted2() {
assertTrue(isSingleQuoted("\"with space\""));
} |
@Override
public V get(final K key) {
Objects.requireNonNull(key, "key cannot be null");
try {
return maybeMeasureLatency(() -> outerValue(wrapped().get(keyBytes(key))), time, getSensor);
} catch (final ProcessorStateException e) {
final String message = String.format... | @Test
public void shouldThrowNullPointerOnGetIfKeyIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> metered.get(null));
} |
@Override
public void createLoginLog(LoginLogCreateReqDTO reqDTO) {
LoginLogDO loginLog = BeanUtils.toBean(reqDTO, LoginLogDO.class);
loginLogMapper.insert(loginLog);
} | @Test
public void testCreateLoginLog() {
LoginLogCreateReqDTO reqDTO = randomPojo(LoginLogCreateReqDTO.class);
// 调用
loginLogService.createLoginLog(reqDTO);
// 断言
LoginLogDO loginLogDO = loginLogMapper.selectOne(null);
assertPojoEquals(reqDTO, loginLogDO);
} |
public Node chooseRandomWithStorageType(final String scope,
final Collection<Node> excludedNodes, StorageType type) {
netlock.readLock().lock();
try {
if (scope.startsWith("~")) {
return chooseRandomWithStorageType(
NodeBase.ROOT, scope.substring(1), excludedNodes, type);
}... | @Test
public void testChooseRandomWithStorageType() throws Exception {
Node n;
DatanodeDescriptor dd;
// test the choose random can return desired storage type nodes without
// exclude
Set<String> diskUnderL1 =
new HashSet<>(Arrays.asList("host2", "host4", "host5", "host6"));
Set<Strin... |
static double estimatePixelCount(final Image image, final double widthOverHeight) {
if (image.getHeight() == HEIGHT_UNKNOWN) {
if (image.getWidth() == WIDTH_UNKNOWN) {
// images whose size is completely unknown will be in their own subgroups, so
// any one of them wil... | @Test
public void testEstimatePixelCountWidthUnknown() {
assertEquals( 10000.0, estimatePixelCount(img(100, WIDTH_UNKNOWN), 1.0 ), 0.0);
assertEquals( 20000.0, estimatePixelCount(img(200, WIDTH_UNKNOWN), 0.5 ), 0.0);
assertEquals( 12.0, estimatePixelCount(img( 1, WIDTH_UNKNOWN), ... |
@Override
public Optional<DispatchEvent> build(final DataChangedEvent event) {
if (event.getKey().startsWith(ComputeNode.getOnlineInstanceNodePath())) {
return createInstanceEvent(event);
}
return Optional.empty();
} | @Test
void assertComputeNodeOnline() {
Optional<DispatchEvent> actual = new ComputeNodeOnlineDispatchEventBuilder()
.build(new DataChangedEvent("/nodes/compute_nodes/online/proxy/foo_instance_id", "{attribute: 127.0.0.1@3307,version: 1}", Type.ADDED));
assertTrue(actual.isPresent());... |
public SmppConfiguration getConfiguration() {
return configuration;
} | @Test
public void constructorSmppConfigurationShouldSetTheSmppConfiguration() {
SmppConfiguration configuration = new SmppConfiguration();
binding = new SmppBinding(configuration);
assertSame(configuration, binding.getConfiguration());
} |
public static List<FieldInfo> buildSourceSchemaEntity(final LogicalSchema schema) {
final List<FieldInfo> allFields = schema.columns().stream()
.map(EntityUtil::toFieldInfo)
.collect(Collectors.toList());
if (allFields.isEmpty()) {
throw new IllegalArgumentException("Root schema should co... | @Test
public void shouldBuildMiltipleFieldsCorrectly() {
// Given:
final LogicalSchema schema = LogicalSchema.builder()
.valueColumn(ColumnName.of("field1"), SqlTypes.INTEGER)
.valueColumn(ColumnName.of("field2"), SqlTypes.BIGINT)
.build();
// When:
final List<FieldInfo> field... |
@Override
public String format(LogRecord logRecord) {
Object[] arguments = new Object[6];
arguments[0] = logRecord.getThreadID();
String fullClassName = logRecord.getSourceClassName();
int lastDot = fullClassName.lastIndexOf('.');
String className = fullClassName.substring(la... | @Test
public void format() {
BriefLogFormatter formatter = new BriefLogFormatter();
LogRecord record = new LogRecord(Level.INFO, "message");
record.setSourceClassName("org.example.Class");
record.setSourceMethodName("method");
record.setMillis(Instant.EPOCH.toEpochMilli());
... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)
|| monitoringDisabled || !instanceEnabled) {
// si ce n'est pas une requête h... | @Test
public void testDoFilter() throws ServletException, IOException {
// displayed-counters
setProperty(Parameter.DISPLAYED_COUNTERS, "sql");
try {
setUp();
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
doFilter(request);
setProperty(Parameter.DISPLAYED_COUNTERS, "");
se... |
public static int toUnix(String time, String pattern) {
LocalDateTime formatted = LocalDateTime.parse(time, DateTimeFormatter.ofPattern(pattern));
return (int) formatted.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
} | @Test
public void testToUnix() {
int unixTime = DateKit.toUnix(date);
Assert.assertEquals(1505892470, unixTime);
unixTime = DateKit.toUnix("2017-09-09 11:22:33");
Assert.assertEquals(1504927353, unixTime);
unixTime = DateKit.toUnix("2017-09-09 11:22", "yyyy-MM-dd HH:mm");
... |
@Override
public void validateDictDataList(String dictType, Collection<String> values) {
if (CollUtil.isEmpty(values)) {
return;
}
Map<String, DictDataDO> dictDataMap = CollectionUtils.convertMap(
dictDataMapper.selectByDictTypeAndValues(dictType, values), DictDat... | @Test
public void testValidateDictDataList_success() {
// mock 数据
DictDataDO dictDataDO = randomDictDataDO().setStatus(CommonStatusEnum.ENABLE.getStatus());
dictDataMapper.insert(dictDataDO);
// 准备参数
String dictType = dictDataDO.getDictType();
List<String> values = si... |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitSSSMultipleDelimCharsWithDefaultValue() {
// Multiple delimiters
assertThat(JOrphanUtils.split("a,b;c,,", ",;", "?"),
CoreMatchers.equalTo(new String[]{"a", "b", "c", "?", "?"}));
} |
@Override
public CompletableFuture<AckResult> ackMessage(ProxyContext ctx, ReceiptHandle handle, String messageId,
AckMessageRequestHeader requestHeader, long timeoutMillis) {
return this.mqClientAPIFactory.getClient().ackMessageAsync(
this.resolveBrokerAddrInReceiptHandle(ctx, handle),
... | @Test
public void testAckMessageByInvalidBrokerNameHandle() throws Exception {
when(topicRouteService.getBrokerAddr(any(), anyString())).thenThrow(new MQClientException(ResponseCode.TOPIC_NOT_EXIST, ""));
try {
this.clusterMessageService.ackMessage(
ProxyContext.create(),... |
@JsonProperty("type")
public FSTType getFstType() {
return _fstType;
} | @Test
public void withDisabledTrue()
throws JsonProcessingException {
String confStr = "{\"disabled\": true}";
FstIndexConfig config = JsonUtils.stringToObject(confStr, FstIndexConfig.class);
assertTrue(config.isDisabled(), "Unexpected disabled");
assertNull(config.getFstType(), "Unexpected typ... |
static String getSparkInternalAccumulatorKey(final String prestoKey)
{
if (prestoKey.contains(SPARK_INTERNAL_ACCUMULATOR_PREFIX)) {
int index = prestoKey.indexOf(PRESTO_NATIVE_OPERATOR_STATS_SEP);
return prestoKey.substring(index);
}
String[] prestoKeyParts = prestoKe... | @Test
public void getSparkInternalAccumulatorKeyInternalKeyTest()
{
String expected = "internal.metrics.appname.writerRejectedPackageRawBytes";
String prestoKey = "ShuffleWrite.root.internal.metrics.appname.writerRejectedPackageRawBytes";
String actual = getSparkInternalAccumulatorKey(pr... |
@Override
public void setSequence(long update) {
sequence.set(update);
} | @Test
public void testSetSequence() {
sequencer.setSequence(23);
assertEquals(23, sequencer.getSequence());
} |
@Override
@ManagedOperation(description = "Does the store contain the given key")
public boolean contains(String key) {
return cache.asMap().containsKey(key);
} | @Test
void testContains() {
assertFalse(repo.contains(key01));
// add key and check again
assertTrue(repo.add(key01));
assertTrue(repo.contains(key01));
} |
@Override
public V poll(long timeout, TimeUnit unit) throws InterruptedException {
return commandExecutor.getInterrupted(pollAsync(timeout, unit));
} | @Test
@Timeout(3)
public void testShortPoll() throws InterruptedException {
RBlockingQueue<Integer> queue = getQueue();
queue.poll(500, TimeUnit.MILLISECONDS);
queue.poll(10, TimeUnit.MICROSECONDS);
} |
@Override
public void startBundles(List<Bundle> bundles, boolean privileged) throws BundleException {
throw newException();
} | @Test
void require_that_startBundles_throws_exception() throws BundleException {
assertThrows(RuntimeException.class, () -> {
new DisableOsgiFramework().startBundles(null, true);
});
} |
public static int indexOf(CharSequence str, char searchChar) {
return indexOf(str, searchChar, 0);
} | @Test
public void indexOfTest2() {
int index = CharSequenceUtil.indexOf("abc123", '1', 0, 3);
assertEquals(-1, index);
index = CharSequenceUtil.indexOf("abc123", 'b', 0, 3);
assertEquals(1, index);
} |
@Override
public ScheduledFuture<?> scheduleAtFixedRate(
ProcessingTimeCallback callback, long initialDelay, long period) {
return scheduleRepeatedly(callback, initialDelay, period, false);
} | @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
@Test
void testScheduleAtFixedRate() throws Exception {
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final long period = 10L;
final int countDown = 3;
final SystemProcessingTimeService timer = createSy... |
@VisibleForTesting
static boolean isCompressed(String contentEncoding) {
return contentEncoding.contains(HttpHeaderValues.GZIP.toString())
|| contentEncoding.contains(HttpHeaderValues.DEFLATE.toString())
|| contentEncoding.contains(HttpHeaderValues.BR.toString())
... | @Test
void detectsGzipAmongOtherEncodings() {
assertTrue(HttpUtils.isCompressed("gzip, deflate"));
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
final FileAttributes stat;
if(file.isSymbolicLink()) {
stat = s... | @Test
public void testFindSymbolicLink() throws Exception {
final Path file = new SFTPTouchFeature(session).touch(new Path(new SFTPHomeDirectoryService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
final Path symlink = new Path(n... |
@Private
@VisibleForTesting
public static int parseMaximumHeapSizeMB(String javaOpts) {
// Find the last matching -Xmx following word boundaries
Matcher m = JAVA_OPTS_XMX_PATTERN.matcher(javaOpts);
if (m.matches()) {
long size = Long.parseLong(m.group(1));
if (size <= 0) {
return -1;... | @Test
public void testParseMaximumHeapSizeMB() {
// happy cases
Assert.assertEquals(4096, JobConf.parseMaximumHeapSizeMB("-Xmx4294967296"));
Assert.assertEquals(4096, JobConf.parseMaximumHeapSizeMB("-Xmx4194304k"));
Assert.assertEquals(4096, JobConf.parseMaximumHeapSizeMB("-Xmx4096m"));
Assert.ass... |
@SneakyThrows({NoSuchProviderException.class, NoSuchAlgorithmException.class})
public static KeyPair generateRSAKeyPair() {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
keyPairGenerator.initialize(4096, new SecureRandom());
retu... | @Test
void assertGenerateKeyPair() {
KeyPair actual = SSLUtils.generateRSAKeyPair();
assertThat(actual.getPrivate().getAlgorithm(), is("RSA"));
assertThat(actual.getPrivate().getFormat(), is("PKCS#8"));
assertThat(actual.getPublic().getAlgorithm(), is("RSA"));
assertThat(actu... |
public static String readFile(String path, String fileName) {
File file = openFile(path, fileName);
if (file.exists()) {
return readFile(file);
}
return null;
} | @Test
void testReadFile() {
assertNotNull(DiskUtils.readFile(testFile));
} |
public long parse(final String text) {
return parse(text, ZoneId.systemDefault());
} | @Test
public void shouldConvertToMillis() {
// Given
final String format = "yyyy-MM-dd HH";
final String timestamp = "1605-11-05 10";
// When
final long ts = new StringToTimestampParser(format).parse(timestamp);
// Then
assertThat(ts, is(
FIFTH_OF_NOVEMBER
.withHour(1... |
public RuntimeOptionsBuilder parse(Class<?> clazz) {
RuntimeOptionsBuilder args = new RuntimeOptionsBuilder();
for (Class<?> classWithOptions = clazz; hasSuperClass(
classWithOptions); classWithOptions = classWithOptions.getSuperclass()) {
CucumberOptions options = requireNonNul... | @Test
void cannot_create_with_glue_and_extra_glue() {
Executable testMethod = () -> parser().parse(ClassWithGlueAndExtraGlue.class).build();
CucumberException actualThrown = assertThrows(CucumberException.class, testMethod);
assertThat("Unexpected exception message", actualThrown.getMessage(... |
@Override
public FSDataOutputStream create(final Path f, final FsPermission permission,
final boolean overwrite, final int bufferSize, final short replication,
final long blockSize, final Progressable progress) throws IOException {
return super.create(fullPath(f), permission, overwrite, bufferSize,
... | @Test(timeout = 30000)
public void testGetAllStoragePolicy() throws Exception {
Configuration conf = new Configuration();
conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class);
URI chrootUri = URI.create("mockfs://foo/a/b");
ChRootedFileSystem chrootFs = new ChRootedFileSystem(chroo... |
@Override
public void serviceInit(Configuration conf) throws Exception {
initScheduler(conf);
super.serviceInit(conf);
// Initialize SchedulingMonitorManager
schedulingMonitorManager.initialize(rmContext, conf);
} | @Test(timeout = 30000)
public void testConfValidation() throws Exception {
FifoScheduler scheduler = new FifoScheduler();
Configuration conf = new YarnConfiguration();
conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 2048);
conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION... |
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName,
@Nullable Integer pageNumber, @Nullable Integer pageSize) {
String url = format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s",
gitlabUrl,
proj... | @Test
public void search_projects_fail_if_pagination_data_not_returned() {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[ ]");
server.enqueue(projects);
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "pat", "example", 1, 10))
.isInstanceOf(Ill... |
@Override
public int hashCode() {
return Objects.hashCode(data);
} | @Test
public void testEqualityWithMemberResponses() {
for (short version : ApiKeys.LEAVE_GROUP.allVersions()) {
List<MemberResponse> localResponses = version > 2 ? memberResponses : memberResponses.subList(0, 1);
LeaveGroupResponse primaryResponse = new LeaveGroupResponse(localRespon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.