focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public IndexRange get(String index) throws NotFoundException {
final DBQuery.Query query = DBQuery.and(
DBQuery.notExists("start"),
DBQuery.is(IndexRange.FIELD_INDEX_NAME, index));
final MongoIndexRange indexRange = collection.findOne(query);
if (ind... | @Test(expected = NotFoundException.class)
public void getThrowsNotFoundException() throws Exception {
indexRangeService.get("does-not-exist");
} |
@Override
public ObjectNode encode(Criterion criterion, CodecContext context) {
EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context);
return encoder.encode();
} | @Test
public void matchIcmpTypeTest() {
Criterion criterion = Criteria.matchIcmpType((byte) 250);
ObjectNode result = criterionCodec.encode(criterion, context);
assertThat(result, matchesCriterion(criterion));
} |
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{networkId}/devices")
public Response getVirtualDevices(@PathParam("networkId") long networkId) {
NetworkId nid = NetworkId.networkId(networkId);
Set<VirtualDevice> vdevs = vnetService.getVirtualDevices(nid);
return ok(encodeArray(Vir... | @Test
public void testGetVirtualDevicesArray() {
NetworkId networkId = networkId3;
vdevSet.add(vdev1);
vdevSet.add(vdev2);
expect(mockVnetService.getVirtualDevices(networkId)).andReturn(vdevSet).anyTimes();
replay(mockVnetService);
WebTarget wt = target();
St... |
public void commitPartitions() throws Exception {
commitPartitions((subtaskIndex, attemptNumber) -> true);
} | @Test
void testPartitionPathNotExist() throws Exception {
Files.delete(path);
LinkedHashMap<String, String> staticPartitions = new LinkedHashMap<String, String>();
FileSystemCommitter committer =
new FileSystemCommitter(
fileSystemFactory,
... |
@Override
public List<InputSplit> getSplits(JobContext context)
throws IOException, InterruptedException {
Configuration configuration = context.getConfiguration();
int numSplits = DistCpUtils.getInt(configuration,
JobContext.NUM_MAPS);
if (num... | @Test
public void testGetSplits() throws Exception {
testGetSplits(9);
for (int i=1; i<N_FILES; ++i)
testGetSplits(i);
} |
@Override
public BatchKVResponse<K, EntityResponse<V>> wrapResponse(DataMap dataMap, Map<String, String> headers, ProtocolVersion version)
throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException
{
if (dataMap == null)
{
return null;
... | @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "batchEntityResponseDataProvider")
public void testDecoding(List<String> keys, ProtocolVersion protocolVersion)
throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException
{
final String ... |
static Date parseDate(final String value) {
try {
return getUtilDateFormat().parse(value);
} catch (ParseException e) {
return throwRuntimeParseException(value, e, DATE_FORMAT);
}
} | @Test
public void testUtilDate() {
long now = System.currentTimeMillis();
Date date1 = new Date(now);
Date date2 = DateHelper.parseDate(new SimpleDateFormat(DateHelperTest.DATE_FORMAT, Locale.US).format(date1));
Calendar cal1 = Calendar.getInstance(Locale.US);
cal1.setTimeI... |
@Override
public boolean trySetCapacity(int capacity) {
return get(trySetCapacityAsync(capacity));
} | @Test
public void testExpire() throws InterruptedException {
RBoundedBlockingQueue<Integer> queue = redisson.getBoundedBlockingQueue("queue1");
queue.trySetCapacity(10);
queue.add(1);
queue.add(2);
queue.expire(Duration.ofMillis(100));
Thread.sleep(500);
as... |
public void extractTablesFromSelect(final SelectStatement selectStatement) {
if (selectStatement.getCombine().isPresent()) {
CombineSegment combineSegment = selectStatement.getCombine().get();
extractTablesFromSelect(combineSegment.getLeft().getSelect());
extractTablesFromSel... | @Test
void assertExtractTablesFromSelectProjectsWithFunctionWithSubQuery() {
FunctionSegment functionSegment = new FunctionSegment(0, 0, "", "");
SelectStatement subQuerySegment = mock(SelectStatement.class);
when(subQuerySegment.getFrom()).thenReturn(Optional.of(new SimpleTableSegment(new T... |
@InvokeOnHeader(Web3jConstants.ETH_GET_BLOCK_BY_NUMBER)
void ethGetBlockByNumber(Message message) throws IOException {
DefaultBlockParameter atBlock
= toDefaultBlockParameter(message.getHeader(Web3jConstants.AT_BLOCK, configuration::getAtBlock, String.class));
Boolean fullTransaction... | @Test
public void ethGetBlockByNumberTest() throws Exception {
EthBlock response = Mockito.mock(EthBlock.class);
Mockito.when(mockWeb3j.ethGetBlockByNumber(any(), anyBoolean())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getBlock()).... |
public static void initializeBootstrapProperties(
Properties properties,
Optional<String> bootstrapServer,
Optional<String> bootstrapControllers
) {
if (bootstrapServer.isPresent()) {
if (bootstrapControllers.isPresent()) {
throw new InitializeBootstrapExc... | @Test
public void testInitializeBootstrapPropertiesWithBrokerBootstrap() {
Properties props = createTestProps();
CommandLineUtils.initializeBootstrapProperties(props,
Optional.of("127.0.0.2:9094"), Optional.empty());
assertEquals("127.0.0.2:9094", props.getProperty("bootstrap.ser... |
public static KafkaRoutineLoadJob fromCreateStmt(CreateRoutineLoadStmt stmt) throws UserException {
// check db and table
Database db = GlobalStateMgr.getCurrentState().getDb(stmt.getDBName());
if (db == null) {
ErrorReport.reportDdlException(ErrorCode.ERR_BAD_DB_ERROR, stmt.getDBNam... | @Test
public void testSerializationJson(@Mocked GlobalStateMgr globalStateMgr,
@Injectable Database database,
@Injectable OlapTable table) throws UserException {
CreateRoutineLoadStmt createRoutineLoadStmt = initCreateRoutineLoadStm... |
@Override
public Map<String, String> getProperties() {
final List<String> properties = this.list(PROPERTIES_KEY);
if(properties.isEmpty()) {
return parent.getProperties();
}
return properties.stream().distinct().collect(Collectors.toMap(
property -> String... | @Test
public void testEmptyProperty() {
final Profile profile = new Profile(new TestProtocol(), new Deserializer<String>() {
@Override
public String stringForKey(final String key) {
return null;
}
@Override
public String objectForK... |
public static Number getExactlyNumber(final String value, final int radix) {
try {
return getBigInteger(value, radix);
} catch (final NumberFormatException ex) {
return new BigDecimal(value);
}
} | @Test
void assertGetExactlyNumberForInteger() {
assertThat(SQLUtils.getExactlyNumber("100000", 10), is(100000));
assertThat(SQLUtils.getExactlyNumber("100000", 16), is(1048576));
assertThat(SQLUtils.getExactlyNumber(String.valueOf(Integer.MIN_VALUE), 10), is(Integer.MIN_VALUE));
asse... |
public static Type[] getReturnTypes(Invocation invocation) {
try {
if (invocation != null
&& invocation.getInvoker() != null
&& invocation.getInvoker().getUrl() != null
&& invocation.getInvoker().getInterface() != GenericService.class
... | @Test
void testGetReturnTypesWithoutCache() throws Exception {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.su... |
public static String parsePath(String uri, Map<String, String> patterns) {
if (uri == null) {
return null;
} else if (StringUtils.isBlank(uri)) {
return String.valueOf(SLASH);
}
CharacterIterator ci = new StringCharacterIterator(uri);
StringBuilder pathBuf... | @Test(description = "parse path with param without regex")
public void parsePathWithoutRegex() {
final Map<String, String> regexMap = new HashMap<String, String>();
final String path = PathUtils.parsePath("/api/{name}", regexMap);
assertEquals(path, "/api/{name}");
assertEquals(regex... |
public static LookupResult multi(final CharSequence singleValue, final Map<Object, Object> multiValue) {
return withoutTTL().single(singleValue).multiValue(multiValue).build();
} | @Test
public void serializeMultiNumber() {
final LookupResult lookupResult = LookupResult.multi(42, MULTI_VALUE);
final JsonNode node = objectMapper.convertValue(lookupResult, JsonNode.class);
assertThat(node.isNull()).isFalse();
assertThat(node.path("single_value").asInt()).isEqual... |
@Override
public void preflight(final Path workdir, final String filename) throws BackgroundException {
if(workdir.isRoot() || new DeepboxPathContainerService(session).isDeepbox(workdir) || new DeepboxPathContainerService(session).isBox(workdir)) {
throw new AccessDeniedException(MessageFormat.f... | @Test
public void testNoAddChildrenInbox() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final Path folder = new Path("/ORG 1 - DeepBox Desktop App/ORG1:Box1/Inbox/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final PathAttributes attributes = n... |
@Override
public boolean supportsCatalogsInProcedureCalls() {
return false;
} | @Test
void assertSupportsCatalogsInProcedureCalls() {
assertFalse(metaData.supportsCatalogsInProcedureCalls());
} |
public static Collection<DataNode> buildDataNode(final DataNode dataNode, final Map<String, Collection<String>> dataSources) {
if (!dataSources.containsKey(dataNode.getDataSourceName())) {
return Collections.singletonList(dataNode);
}
Collection<DataNode> result = new LinkedList<>();... | @Test
void assertBuildDataNodeWithSameDataSource() {
DataNode dataNode = new DataNode("readwrite_ds.t_order");
Collection<DataNode> dataNodes = DataNodeUtils.buildDataNode(dataNode, Collections.singletonMap("readwrite_ds", Arrays.asList("ds_0", "shadow_ds_0")));
assertThat(dataNodes.size(), ... |
public static String getOwnerFromGrpcClient(AlluxioConfiguration conf) {
try {
User user = AuthenticatedClientUser.get(conf);
if (user == null) {
return "";
}
return user.getName();
} catch (IOException e) {
return "";
}
} | @Test
public void getOwnerFromGrpcClient() throws Exception {
// When security is not enabled, user and group are not set
mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL);
assertEquals("", SecurityUtils.getOwnerFromGrpcClient(mConfiguration));
mConfiguration.set(PropertyK... |
public void validate(AlmSettingDto almSettingDto) {
String bitbucketUrl = almSettingDto.getUrl();
String bitbucketToken = almSettingDto.getDecryptedPersonalAccessToken(encryption);
if (bitbucketUrl == null || bitbucketToken == null) {
throw new IllegalArgumentException("Your global Bitbucket Server co... | @Test
public void validate_failure_on_incomplete_configuration() {
AlmSettingDto almSettingDto = createNewBitbucketDto(null, "abc");
assertThatThrownBy(() -> underTest.validate(almSettingDto))
.isInstanceOf(IllegalArgumentException.class);
} |
static <RequestT, @Nullable ResponseT>
PTransform<PCollection<RequestT>, Result<KV<RequestT, @Nullable ResponseT>>> readUsingRedis(
RedisClient client,
Coder<RequestT> requestTCoder,
Coder<@Nullable ResponseT> responseTCoder)
throws NonDeterministicException {
return re... | @Test
public void givenNonDeterministicCoder_readUsingRedis_throwsError()
throws Coder.NonDeterministicException {
URI uri = URI.create("redis://localhost:6379");
assertThrows(
NonDeterministicException.class,
() ->
Cache.readUsingRedis(
new RedisClient(uri),
... |
@Override
@SuppressWarnings("DuplicatedCode")
public Integer cleanErrorLog(Integer exceedDay, Integer deleteLimit) {
int count = 0;
LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
// 循环删除,直到没有满足条件的数据
for (int i = 0; i < Short.MAX_VALUE; i++) {
int... | @Test
public void testCleanJobLog() {
// mock 数据
ApiErrorLogDO log01 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofDays(-3))));
apiErrorLogMapper.insert(log01);
ApiErrorLogDO log02 = randomPojo(ApiErrorLogDO.class, o -> o.setCreateTime(addTime(Duration.ofD... |
public ClassificationPoliciesConfig shareClassificationsPolicies() throws BackgroundException {
if(classificationPolicies.get() == null) {
final Matcher matcher = Pattern.compile(SDSSession.VERSION_REGEX).matcher(this.softwareVersion().getRestApiVersion());
if(matcher.matches()) {
... | @Test
public void testClassificationConfiguration() throws Exception {
final ClassificationPoliciesConfig policies = session.shareClassificationsPolicies();
assertNotNull(policies);
assertNotNull(policies.getShareClassificationPolicies());
assertNotNull(policies.getShareClassificatio... |
public static float parseBytesIntToFloat(List data) {
return parseBytesIntToFloat(data, 0);
} | @Test
public void parseBytesIntToFloat() {
byte[] intValByte = {0x00, 0x00, 0x00, 0x0A};
Float valueExpected = 10.0f;
Float valueActual = TbUtils.parseBytesIntToFloat(intValByte, 3, 1, true);
Assertions.assertEquals(valueExpected, valueActual);
valueActual = TbUtils.parseByte... |
@Override
public void forget(final Xid xid) throws XAException {
try {
delegate.forget(xid);
} catch (final XAException ex) {
throw mapXAException(ex);
}
} | @Test
void assertForget() throws XAException {
singleXAResource.forget(xid);
verify(xaResource).forget(xid);
} |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
@Category({ValidatesRunner.class})
public void testWindowedMapSideInputWithNonDeterministicKeyCoder() {
final PCollectionView<Map<String, Integer>> view =
pipeline
.apply(
"CreateSideInput",
Create.timestamped(
TimestampedValue.o... |
public static String normalizeURL(String url) {
if (url == null) {
return null;
}
ParsedUrl parsedUrl = ParsedUrl.parseUrl(url);
Canonicalizer.AGGRESSIVE.canonicalize(parsedUrl);
String normalized = parsedUrl.toString();
if (normalized == null) {
normalized = url;
}
// convert to lower case, the... | @Test
void testNormalization() {
String urla1 = "http://example.com/hello?a=1&b=2";
String urla2 = "http://www.example.com/hello?a=1&b=2";
String urla3 = "http://EXAmPLe.com/HELLo?a=1&b=2";
String urla4 = "http://example.com/hello?b=2&a=1";
String urla5 = "https://example.com/hello?a=1&b=2";
String urlb1 ... |
public void callEnableDataCollect() {
call("enableDataCollect", null);
} | @Test
public void callEnableDataCollect() {
} |
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void when_userDeclaresPrimitiveAdditionalField_then_throws(boolean key, String prefix) {
Map<String, String> options = Map.of(
(key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT,
... |
@Override
public String retrieveIPfilePath(String id, String dstDir,
Map<Path, List<String>> localizedResources) {
// Assume .aocx IP file is distributed by DS to local dir
String ipFilePath = null;
LOG.info("Got environment: " + id +
", search IP file in localized resources");
if (null... | @Test
public void testLocalizedIPfileNotFound() {
Map<Path, List<String>> resources = createResources();
String path = plugin.retrieveIPfilePath("dummy", "workDir", resources);
assertNull("Retrieved IP file path", path);
} |
public static <T> T waitWithLogging(
Logger log,
String prefix,
String action,
CompletableFuture<T> future,
Deadline deadline,
Time time
) throws Throwable {
log.info("{}Waiting for {}", prefix, action);
try {
T result = time.waitForFuture(... | @Test
public void testWaitWithLoggingError() throws Throwable {
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
CompletableFuture<Integer> future = new CompletableFuture<>();
executorService.schedule(() -> {
future.completeExceptionally(new IllegalA... |
public static SqlDecimal of(final int precision, final int scale) {
return new SqlDecimal(precision, scale);
} | @Test(expected = SchemaException.class)
public void shouldThrowOnInvalidPrecision() {
SqlDecimal.of(0, 2);
} |
public static QueryServiceResponse buildSuccessResponse(ServiceInfo serviceInfo) {
return new QueryServiceResponse(serviceInfo);
} | @Test
void testSerializeSuccessResponse() throws JsonProcessingException {
QueryServiceResponse response = QueryServiceResponse.buildSuccessResponse(new ServiceInfo());
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"serviceInfo\":{"));
assertTrue(json.... |
public static PointList simplify(ResponsePath responsePath, RamerDouglasPeucker ramerDouglasPeucker, boolean enableInstructions) {
final PointList pointList = responsePath.getPoints();
List<Partition> partitions = new ArrayList<>();
// make sure all waypoints are retained in the simplified poin... | @Test
public void testScenario() {
DecimalEncodedValue speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false);
EncodingManager carManager = EncodingManager.start().add(speedEnc)
.add(Roundabout.create()).add(RoadClass.create()).add(RoadClassLink.create()).add(MaxSpeed.create())... |
public static String getGenericScenarioExceptionMessage(String exceptionMessage) {
return String.format("Failure reason: %s", exceptionMessage);
} | @Test
public void getGenericScenarioExceptionMessage_simpleCase() {
assertThat(getGenericScenarioExceptionMessage("An exception message")).isEqualTo("Failure reason: An exception message");
} |
@Override
public Long createLevel(MemberLevelCreateReqVO createReqVO) {
// 校验配置是否有效
validateConfigValid(null, createReqVO.getName(), createReqVO.getLevel(), createReqVO.getExperience());
// 插入
MemberLevelDO level = MemberLevelConvert.INSTANCE.convert(createReqVO);
memberLeve... | @Test
public void testCreateLevel_success() {
// 准备参数
MemberLevelCreateReqVO reqVO = randomPojo(MemberLevelCreateReqVO.class, o -> {
o.setDiscountPercent(randomInt());
o.setIcon(randomURL());
o.setBackgroundUrl(randomURL());
o.setStatus(randomCommonSta... |
@Override
public List<Document> get() {
try (var input = markdownResource.getInputStream()) {
Node node = parser.parseReader(new InputStreamReader(input));
DocumentVisitor documentVisitor = new DocumentVisitor(config);
node.accept(documentVisitor);
return documentVisitor.getDocuments();
}
catch (IO... | @Test
void testOnlyHeadersWithParagraphs() {
MarkdownDocumentReader reader = new MarkdownDocumentReader("classpath:/only-headers.md");
List<Document> documents = reader.get();
assertThat(documents).hasSize(4)
.extracting(Document::getMetadata, Document::getContent)
.containsOnly(tuple(Map.of("category", ... |
static Long replicationThrottle(CruiseControlRequestContext requestContext, KafkaCruiseControlConfig config) {
Long value = getLongParam(requestContext, REPLICATION_THROTTLE_PARAM, config.getLong(ExecutorConfig.DEFAULT_REPLICATION_THROTTLE_CONFIG));
if (value != null && value < 0) {
throw new UserRequestE... | @Test
public void testParseReplicationThrottleWithNoDefault() {
CruiseControlRequestContext mockRequest = EasyMock.mock(CruiseControlRequestContext.class);
KafkaCruiseControlConfig controlConfig = EasyMock.mock(KafkaCruiseControlConfig.class);
Map<String, String[]> paramMap = Collections.singletonMap(
... |
public static <T> String join(Iterator<T> iterator, CharSequence conjunction) {
return StrJoiner.of(conjunction).append(iterator).toString();
} | @Test
public void joinWithNullTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", null, "3", "4");
final String join = IterUtil.join(list.iterator(), ":", String::valueOf);
assertEquals("1:null:3:4", join);
} |
@Udf
public String lpad(
@UdfParameter(description = "String to be padded") final String input,
@UdfParameter(description = "Target length") final Integer targetLen,
@UdfParameter(description = "Padding string") final String padding) {
if (input == null) {
return null;
}
if (paddi... | @Test
public void shouldReturnNullForNullLengthBytes() {
final ByteBuffer result = udf.lpad(BYTES_123, null, BYTES_45);
assertThat(result, is(nullValue()));
} |
public static <T> CollectionCoder<T> of(Coder<T> elemCoder) {
return new CollectionCoder<>(elemCoder);
} | @Test
public void testCoderIsSerializableWithWellKnownCoderType() throws Exception {
CoderProperties.coderSerializable(CollectionCoder.of(GlobalWindow.Coder.INSTANCE));
} |
public static org.apache.avro.Schema toAvroSchema(
Schema beamSchema, @Nullable String name, @Nullable String namespace) {
final String schemaName = Strings.isNullOrEmpty(name) ? "topLevelRecord" : name;
final String schemaNamespace = namespace == null ? "" : namespace;
String childNamespace =
... | @Test
public void testJdbcLogicalDateAndTimeRowDataToAvroSchema() {
String expectedAvroSchemaJson =
"{ "
+ " \"name\": \"topLevelRecord\", "
+ " \"type\": \"record\", "
+ " \"fields\": [{ "
+ " \"name\": \"my_date_field\", "
+ " \"type\": { \... |
@Override
public List<String> getKeys(final String id) {
return Arrays.asList((getKeyName() + ".{" + id) + "}.tokens", (getKeyName() + ".{" + id) + "}.timestamp");
} | @Test
public void getKeysTest() {
String prefix = abstractRateLimiterAlgorithm.getKeyName() + ".{" + ID;
String tokenKey = prefix + "}.tokens";
String timestampKey = prefix + "}.timestamp";
List<String> keys = abstractRateLimiterAlgorithm.getKeys(ID);
assertThat(tokenKey, is(... |
public void removeSCM(String id) {
SCM scmToBeDeleted = this.find(id);
if (scmToBeDeleted == null) {
throw new RuntimeException(String.format("Could not find SCM with id '%s'", id));
}
this.remove(scmToBeDeleted);
} | @Test
void shouldThrowRuntimeExceptionWhenTryingToRemoveSCMIdWhichIsNotPresent() {
SCMs scms = new SCMs();
try {
scms.removeSCM("id1");
fail("should not reach here");
} catch (Exception e) {
assertThat(e.getMessage()).isEqualTo(String.format("Could not fin... |
@Override
public void handle(RMContainerEvent event) {
LOG.debug("Processing {} of type {}", event.getContainerId(),
event.getType());
writeLock.lock();
try {
RMContainerState oldState = getState();
try {
stateMachine.doTransition(event.getType(), event);
} catch (Inval... | @Test(timeout = 30000)
public void testContainerAcquiredAtKilled() {
DrainDispatcher drainDispatcher = new DrainDispatcher();
EventHandler<RMAppAttemptEvent> appAttemptEventHandler = mock(
EventHandler.class);
EventHandler generic = mock(EventHandler.class);
drainDispatcher.register(RMAppAttem... |
@Udf(description = "Returns the tangent of an INT value")
public Double tan(
@UdfParameter(
value = "value",
description = "The value in radians to get the tangent of."
) final Integer value
) {
return tan(value == null ? null : value.doubleValue());
} | @Test
public void shouldHandleNegative() {
assertThat(udf.tan(-0.43), closeTo(-0.45862102348555517, 0.000000000000001));
assertThat(udf.tan(-Math.PI), closeTo(0, 0.000000000000001));
assertThat(udf.tan(-Math.PI * 2), closeTo(0, 0.000000000000001));
assertThat(udf.tan(-Math.PI * 2), closeTo(0, 0.000000... |
@Override
public <K1, V1> KGroupedTable<K1, V1> groupBy(final KeyValueMapper<? super K, ? super V, KeyValue<K1, V1>> selector) {
return groupBy(selector, Grouped.with(null, null));
} | @Test
public void shouldNotAllowNullSelectorOnGroupBy() {
assertThrows(NullPointerException.class, () -> table.groupBy(null));
} |
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
} | @Test
public void testDestroyItem() {
ViewGroup container = Mockito.mock(ViewGroup.class);
View child = Mockito.mock(View.class);
mUnderTest.destroyItem(container, 0, child);
Mockito.verify(container).removeView(child);
} |
public static <T> boolean contains(Collection<T> coll, T target) {
if (isEmpty(coll)) {
return false;
}
return coll.contains(target);
} | @Test
void testContains() {
assertTrue(CollectionUtils.contains(Collections.singletonList("target"), "target"));
assertFalse(CollectionUtils.contains(Collections.emptyList(), "target"));
} |
public static PTransform<PCollection<? extends Iterable<?>>, PCollection<String>> iterables() {
return iterables(",");
} | @Test
@Category(NeedsRunner.class)
public void testToStringIterableWithDelimiter() {
ArrayList<Iterable<String>> iterables = new ArrayList<>();
iterables.add(Arrays.asList(new String[] {"one", "two", "three"}));
iterables.add(Arrays.asList(new String[] {"four", "five", "six"}));
ArrayList<String> e... |
public void updateLockedJobTriggers() {
final DateTime now = clock.nowUTC();
final var filter = and(
eq(FIELD_LOCK_OWNER, nodeId),
eq(FIELD_STATUS, JobTriggerStatus.RUNNING)
);
collection.updateMany(filter, set(FIELD_LAST_LOCK_TIME, now));
} | @Test
@MongoDBFixtures("locked-job-triggers.json")
public void updateLockedJobTriggers() {
DateTime newLockTime = DateTime.parse("2019-01-01T02:00:00.000Z");
final JobSchedulerTestClock clock = new JobSchedulerTestClock(newLockTime);
final DBJobTriggerService service = serviceWithClock(c... |
public static <T> Partition<T> of(
int numPartitions,
PartitionWithSideInputsFn<? super T> partitionFn,
Requirements requirements) {
Contextful ctfFn =
Contextful.fn(
(T element, Contextful.Fn.Context c) ->
partitionFn.partitionFor(element, numPartitions, c),
... | @Test
@Category(NeedsRunner.class)
public void testEvenOddPartition() {
PCollectionList<Integer> outputs =
pipeline
.apply(Create.of(591, 11789, 1257, 24578, 24799, 307))
.apply(Partition.of(2, new ModFn()));
assertTrue(outputs.size() == 2);
PAssert.that(outputs.get(0)).... |
@BuildStep
AdditionalBeanBuildItem produce(Capabilities capabilities, JobRunrBuildTimeConfiguration jobRunrBuildTimeConfiguration) {
Set<Class<?>> additionalBeans = new HashSet<>();
additionalBeans.add(JobRunrProducer.class);
additionalBeans.add(JobRunrStarter.class);
additionalBeans... | @Test
void jobRunrProducerUsesJacksonIfCapabilityPresent() {
Mockito.reset(capabilities);
lenient().when(capabilities.isPresent(Capability.JACKSON)).thenReturn(true);
final AdditionalBeanBuildItem additionalBeanBuildItem = jobRunrExtensionProcessor.produce(capabilities, jobRunrBuildTimeConfi... |
@Override
public ConfigData get(String path) {
return get(path, Files::isRegularFile);
} | @Test
public void testEmptyPathWithKey() {
ConfigData configData = provider.get("", Collections.singleton("foo"));
assertTrue(configData.data().isEmpty());
assertNull(configData.ttl());
} |
@SuppressWarnings("unchecked")
@Udf
public <T> List<T> union(
@UdfParameter(description = "First array of values") final List<T> left,
@UdfParameter(description = "Second array of values") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> combined ... | @Test
public void shouldUnionArraysOfLikeType() {
final List<String> input1 = Arrays.asList("foo", " ", "bar");
final List<String> input2 = Arrays.asList("baz");
final List<String> result = udf.union(input1, input2);
assertThat(result, contains("foo", " ", "bar", "baz"));
} |
public static Pattern buildTopicRegex(Set<String> stringsToMatch) {
StringJoiner sj = new StringJoiner("|");
stringsToMatch.forEach(sj::add);
return Pattern.compile(sj.toString());
} | @Test
public void testBuildTopicRegex() {
Set<String> topicsToMatch = Set.of(TOPIC1, TOPIC2);
Pattern pattern = buildTopicRegex(topicsToMatch);
assertTrue(pattern.matcher(TOPIC1).matches());
assertTrue(pattern.matcher(TOPIC2).matches());
assertFalse(pattern.matcher(TOPIC3).m... |
@Override
public boolean addAggrConfigInfo(final String dataId, final String group, String tenant, final String datumId,
String appName, final String content) {
String appNameTmp = StringUtils.isBlank(appName) ? StringUtils.EMPTY : appName;
String tenantTmp = StringUtils.isBlank(tenant) ... | @Test
void testAddAggrConfigInfoOfUpdateNotEqualContent() {
String dataId = "dataId111";
String group = "group";
String tenant = "tenant";
String datumId = "datumId";
String appName = "appname1234";
String content = "content1234";
//mock query datumId... |
@Override
public List<String> listDatabases() throws CatalogException {
if (catalog instanceof SupportsNamespaces) {
List<String> databases =
((SupportsNamespaces) catalog)
.listNamespaces().stream()
.map(Namespa... | @Test
@Order(4)
void listDatabases() {
icebergCatalog.listDatabases().forEach(System.out::println);
Assertions.assertTrue(icebergCatalog.listDatabases().contains(databaseName));
} |
@Override
public UUID generateId() {
return UUID.randomUUID();
} | @Test
void generates_different_non_null_uuids() {
// Given
UuidGenerator generator = new RandomUuidGenerator();
UUID uuid1 = generator.generateId();
// When
UUID uuid2 = generator.generateId();
// Then
assertNotNull(uuid1);
assertNotNull(uuid2);
... |
public static <T> SerializedValue<T> fromBytes(byte[] serializedData) {
return new SerializedValue<>(serializedData);
} | @Test
void testFromEmptyBytes() {
assertThatThrownBy(() -> SerializedValue.fromBytes(new byte[0]))
.isInstanceOf(IllegalArgumentException.class);
} |
public static Type[] getReturnTypes(Method method) {
Class<?> returnType = method.getReturnType();
Type genericReturnType = method.getGenericReturnType();
if (Future.class.isAssignableFrom(returnType)) {
if (genericReturnType instanceof ParameterizedType) {
Type actua... | @Test
void testGetReturnTypes() throws Exception {
Class<TypeClass> clazz = TypeClass.class;
Type[] types = ReflectUtils.getReturnTypes(clazz.getMethod("getFuture"));
Assertions.assertEquals("java.lang.String", types[0].getTypeName());
Assertions.assertEquals("java.lang.String", typ... |
public int distanceOf(PartitionTableView partitionTableView) {
int distance = 0;
for (int i = 0; i < partitions.length; i++) {
distance += distanceOf(partitions[i], partitionTableView.partitions[i]);
}
return distance;
} | @Test
public void testDistance_whenReplicasExchanged() throws Exception {
// distanceOf([A, B, C], [B, A, C]) == 2
PartitionTableView table1 = createRandomPartitionTable();
InternalPartition[] partitions = extractPartitions(table1);
PartitionReplica[] replicas = partitions[0].getRep... |
@Config("metadata-uri")
public ExampleConfig setMetadata(URI metadata)
{
this.metadata = metadata;
return this;
} | @Test
public void testExplicitPropertyMappings()
{
Map<String, String> properties = new ImmutableMap.Builder<String, String>()
.put("metadata-uri", "file://test.json")
.build();
ExampleConfig expected = new ExampleConfig()
.setMetadata(URI.create(... |
public static boolean reserved(Uuid uuid) {
return uuid.getMostSignificantBits() == 0 &&
uuid.getLeastSignificantBits() < 100;
} | @Test
void testMigratingIsReserved() {
assertTrue(DirectoryId.reserved(DirectoryId.MIGRATING));
} |
@SuppressWarnings("unchecked")
public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) {
final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type());
if (handler == null) {
throw new UnsupportedOperationException("Unsupported schema type: " + schema.type()... | @Test
public void shouldVisitString() {
// Given:
final Schema schema = Schema.OPTIONAL_STRING_SCHEMA;
when(visitor.visitString(any())).thenReturn("Expected");
// When:
final String result = SchemaWalker.visit(schema, visitor);
// Then:
verify(visitor).visitString(same(schema));
asse... |
@Description("current time without time zone")
@ScalarFunction("localtime")
@SqlType(StandardTypes.TIME)
public static long localTime(SqlFunctionProperties properties)
{
if (properties.isLegacyTimestamp()) {
return UTC_CHRONOLOGY.millisOfDay().get(properties.getSessionStartTime());
... | @Test
public void testLocalTime()
{
Session localSession = Session.builder(session)
.setStartTime(new DateTime(2017, 3, 1, 14, 30, 0, 0, DATE_TIME_ZONE).getMillis())
.build();
try (FunctionAssertions localAssertion = new FunctionAssertions(localSession)) {
... |
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("pathState", pathStates)
.add("activePathIndex", activePathIndex)
.add("description", description)
.toString();
} | @Test
public void testToString() {
ProtectedTransportEndpointState state1 =
ProtectedTransportEndpointState
.builder()
.withActivePathIndex(0)
.withDescription(protectedDescription)
.withPathState... |
public static Metric metric(String name) {
return MetricsImpl.metric(name, Unit.COUNT);
} | @Test
public void metricInNotFusedStages() {
int inputSize = 100_000;
Integer[] inputs = new Integer[inputSize];
Arrays.setAll(inputs, i -> i);
pipeline.readFrom(TestSources.items(inputs))
.filter(l -> {
Metrics.metric("onlyInFilter").increment();... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testClassicGroupJoinWithEmptyConsumerGroup() throws Exception {
String consumerGroupId = "consumer-group-id";
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.withConsumerGroup(new ConsumerGroupBuilder(consumerGroupId, 10))
... |
@Override
public ConnectionProperties parse(final String url, final String username, final String catalog) {
Matcher matcher = URL_PATTERN.matcher(url);
ShardingSpherePreconditions.checkState(matcher.find(), () -> new UnrecognizedDatabaseURLException(url, URL_PATTERN.pattern()));
return new ... | @Test
void assertNewConstructorFailure() {
assertThrows(UnrecognizedDatabaseURLException.class, () -> parser.parse("jdbc:sqlserver:xxxxxxxx", null, null));
} |
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
// Close the running transformation
if ( getData().wasStarted ) {
if ( !getData().mappingTrans.isFinished() ) {
// Wait until the child transformation has finished.
getData().mappingTrans.waitUntilFinished();
}
... | @Test
public void testDispose() throws KettleException {
// Set Up TransMock to return the error
when( stepMockHelper.trans.getErrors() ).thenReturn( 0 );
// The step has been already finished
when( stepMockHelper.trans.isFinished() ).thenReturn( Boolean.FALSE );
// The step was started
simp... |
@Override
public Duration convert(String source) {
try {
if (ISO8601.matcher(source).matches()) {
return Duration.parse(source);
}
Matcher matcher = SIMPLE.matcher(source);
Assert.state(matcher.matches(), "'" + source + "' is not a valid durati... | @Test
public void convertWhenSimpleWithoutSuffixShouldReturnDuration() {
assertThat(convert("10")).isEqualTo(Duration.ofMillis(10));
assertThat(convert("+10")).isEqualTo(Duration.ofMillis(10));
assertThat(convert("-10")).isEqualTo(Duration.ofMillis(-10));
} |
public static ResourceId relativize(ResourceId base, ResourceId child) {
checkArgument(child.nodeKeys().size() >= base.nodeKeys().size(),
"%s path must be deeper than base prefix %s", child, base);
@SuppressWarnings("rawtypes")
Iterator<NodeKey> bIt = base.nodeKeys().iterat... | @Test
public void testRelativize() {
ResourceId relDevices = ResourceIds.relativize(ResourceIds.ROOT_ID, DEVICES);
assertEquals(DeviceResourceIds.DEVICES_NAME,
relDevices.nodeKeys().get(0).schemaId().name());
assertEquals(DCS_NAMESPACE,
relDevices.no... |
public static String clean(String charsetName) {
try {
return forName(charsetName).name();
} catch (IllegalArgumentException e) {
return null;
}
} | @Test
public void testFunkyNames() {
assertEquals(null, CharsetUtils.clean("none"));
assertEquals(null, CharsetUtils.clean("no"));
assertEquals("UTF-8", CharsetUtils.clean("utf-8>"));
assertEquals("ISO-8859-1", CharsetUtils.clean("iso-8851-1"));
assertEquals("ISO-8859-15", ... |
@Override
public void filter(Set<String> brokers, BundleData bundleToAssign,
LoadData loadData,
ServiceConfiguration conf) throws BrokerFilterException {
loadData.getBrokerData().forEach((key, value) -> {
// The load manager class name can be null if... | @Test
public void test() throws BrokerFilterException {
BrokerLoadManagerClassFilter filter = new BrokerLoadManagerClassFilter();
LoadData loadData = new LoadData();
LocalBrokerData localBrokerData = new LocalBrokerData();
localBrokerData.setLoadManagerClassName(ModularLoadManagerIm... |
@Override
public <KR> KGroupedStream<KR, V> groupBy(final KeyValueMapper<? super K, ? super V, KR> keySelector) {
return groupBy(keySelector, Grouped.with(null, valueSerde));
} | @Test
public void shouldNotAllowNullSelectorOnGroupByWithGrouped() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.groupBy(null, Grouped.as("name")));
assertThat(exception.getMessage(), equalTo("keySelector can't be null"));... |
public static UserConfigRepo build(Element producerSpec, ConfigDefinitionStore configDefinitionStore, DeployLogger deployLogger) {
Map<ConfigDefinitionKey, ConfigPayloadBuilder> builderMap = new LinkedHashMap<>();
log.log(Level.FINE, () -> "getUserConfigs for " + producerSpec);
for (Element conf... | @Test
void no_exception_when_config_class_does_not_exist() {
Element configRoot = getDocument("<config name=\"is.unknown\">" +
" <foo>1</foo>" +
"</config>");
UserConfigRepo repo = UserConfigBuilder.build(configRoot, configDefinitionStore, new BaseDeployLogger());
... |
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!BuiltInQPChangeNotification.TYPE.equals(notification.getType())) {
return null;
}
BuiltInQPChangeNotificationBuilder profilesNotification = parse(notification);
StringBuilder message = new StringBuilder("The ... | @Test
public void notification_supports_grammar_for_single_rule_added_removed_or_updated() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()... |
public static DegraderImpl.Config toDegraderConfig(Map<String, String> properties)
{
DegraderImpl.Config config = new DegraderImpl.Config();
if (properties == null || properties.isEmpty())
{
return config;
}
else
{
// we are not modifying config's callTracker, name, clock and overr... | @Test
public void testToDegraderConfig()
{
Map<String,String> properties = new HashMap<>();;
Boolean logEnabled = false;
DegraderImpl.LatencyToUse latencyToUse = DegraderImpl.LatencyToUse.PCT95;
Double maxDropRate = 0.33;
Long maxDropDuration = 23190l;
Double upStep = 0.3;
Double downste... |
@Override
public SingleRuleConfiguration swapToObject(final YamlSingleRuleConfiguration yamlConfig) {
SingleRuleConfiguration result = new SingleRuleConfiguration();
if (null != yamlConfig.getTables()) {
result.getTables().addAll(yamlConfig.getTables());
}
result.setDefau... | @Test
void assertSwapToObject() {
YamlSingleRuleConfiguration yamlConfig = new YamlSingleRuleConfiguration();
yamlConfig.setDefaultDataSource("ds_0");
SingleRuleConfiguration ruleConfig = new YamlSingleRuleConfigurationSwapper().swapToObject(yamlConfig);
assertTrue(ruleConfig.getDefa... |
@Cacheable(value = "metadata-response", key = "#samlMetadataRequest.cacheableKey()")
public SamlMetadataResponse resolveSamlMetadata(SamlMetadataRequest samlMetadataRequest) {
LOGGER.info("Cache not found for saml-metadata {}", samlMetadataRequest.hashCode());
Connection connection = connectionServ... | @Test
void organizationInactiveTest() {
Connection connection = newConnection(SAML_COMBICONNECT, true, false, true);
when(connectionServiceMock.getConnectionByEntityId(anyString())).thenReturn(connection);
SamlMetadataResponse response = metadataRetrieverServiceMock.resolveSamlMetadata(newMe... |
@Override
public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) {
if (!tokenQueue.isNextTokenValue(lToken)) {
return false;
}
int stack = 0;
while (tokenQueue.peek() != null) {
Token token = tokenQueue.poll();
if (lToken.equals(token.getValue())) {
st... | @Test
public void shouldNotMatchWhenNoLeft() {
Token t1 = new Token("a", 1, 1);
TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1)));
List<Token> output = mock(List.class);
BridgeTokenMatcher matcher = new BridgeTokenMatcher("(", ")");
assertThat(matcher.matchToken(tokenQueue, output), ... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof PortFragmentId)) {
return false;
}
PortFragmentId that = (PortFragmentId) obj;
return Objects.equals(this.deviceId, that.deviceId) &&
... | @Test
public final void testEquals() {
new EqualsTester()
.addEqualityGroup(new PortFragmentId(DID1, PID, PN1),
new PortFragmentId(DID1, PID, PN1))
.addEqualityGroup(new PortFragmentId(DID2, PID, PN1),
new PortFragmentId(DID2, PID, PN1))
... |
public static Map<String, Properties> subProperties(Properties prop, String regex) {
Map<String, Properties> subProperties = new HashMap<>();
Pattern pattern = Pattern.compile(regex);
for (Map.Entry<Object, Object> entry : prop.entrySet()) {
Matcher m = pattern.matcher(entry.getKey().toString());
... | @Test
public void subProperties() {
MetricsConfig config = new MetricsConfig(mMetricsProps);
Properties properties = config.getProperties();
Map<String, Properties> sinkProps =
MetricsConfig.subProperties(properties, MetricsSystem.SINK_REGEX);
assertEquals(2, sinkProps.size());
assertTru... |
public static Sensor getInvocationSensor(
final Metrics metrics,
final String sensorName,
final String groupName,
final String functionDescription
) {
final Sensor sensor = metrics.sensor(sensorName);
if (sensor.hasMetrics()) {
return sensor;
}
final BiFunction<String, S... | @Test
public void shouldReturnSensorOnSubsequentCalls() {
// Given:
when(sensor.hasMetrics()).thenReturn(true);
// When:
final Sensor result = FunctionMetrics
.getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME);
// Then:
assertThat(result, is(sensor));
} |
public static void error() {
err.println();
} | @Test
public void errorTest2(){
Console.error("a", "b", "c");
Console.error((Object) "a", "b", "c");
} |
public Map<MessageQueue, Long> parseOffsetTableFromBroker(Map<MessageQueue, Long> offsetTable, String namespace) {
HashMap<MessageQueue, Long> newOffsetTable = new HashMap<>(offsetTable.size(), 1);
if (StringUtils.isNotEmpty(namespace)) {
for (Entry<MessageQueue, Long> entry : offsetTable.en... | @Test
public void testParseOffsetTableFromBroker() {
Map<MessageQueue, Long> offsetTable = new HashMap<>();
offsetTable.put(new MessageQueue(), 0L);
Map<MessageQueue, Long> actual = mqClientInstance.parseOffsetTableFromBroker(offsetTable, "defaultNamespace");
assertNotNull(actual);
... |
public static AbstractPredictor getCustomPredictor(DJLEndpoint endpoint) {
String applicationPath = endpoint.getApplication();
// CV
if (applicationPath.equals(IMAGE_CLASSIFICATION.getPath())) {
return new CustomCvPredictor<Classifications>(endpoint);
} else if (applicationP... | @Test
void testGetCustomPredictor() {
var modelName = "MyModel";
var translatorName = "MyTranslator";
// CV
assertInstanceOf(CustomCvPredictor.class,
getCustomPredictor(customEndpoint("cv/image_classification", modelName, translatorName)));
assertInstanceOf(C... |
public Predicate convert(ScalarOperator operator) {
if (operator == null) {
return null;
}
return operator.accept(this, null);
} | @Test
public void testLessThan() {
ConstantOperator value = ConstantOperator.createInt(5);
ScalarOperator op = new BinaryPredicateOperator(BinaryType.LT, F0, value);
Predicate result = CONVERTER.convert(op);
Assert.assertTrue(result instanceof LeafPredicate);
LeafPredicate le... |
public static Optional<String> finishUpdateCheck(Future<Optional<String>> updateMessageFuture) {
if (updateMessageFuture.isDone()) {
try {
return updateMessageFuture.get();
} catch (InterruptedException | ExecutionException ex) {
// No need to restore the interrupted status. The intentio... | @Test
public void testFinishUpdateCheck_notDone() {
@SuppressWarnings("unchecked")
Future<Optional<String>> updateCheckFuture = Mockito.mock(Future.class);
Mockito.when(updateCheckFuture.isDone()).thenReturn(false);
Optional<String> result = UpdateChecker.finishUpdateCheck(updateCheckFuture);
ass... |
@AfterStartUp(order = AfterStartUp.BEFORE_TRANSPORT_SERVICE)
public void init() {
List<LwM2MModelConfig> models = modelStore.getAll();
log.debug("Fetched model configs: {}", models);
currentModelConfigs = models.stream()
.collect(Collectors.toConcurrentMap(LwM2MModelConfig::g... | @Test
void testInitWithDuplicatedModels() {
LwM2MModelConfig config = new LwM2MModelConfig("urn:imei:951358811362976");
List<LwM2MModelConfig> models = List.of(config, config);
willReturn(models).given(modelStore).getAll();
service.init();
assertThat(service.currentModelConfi... |
public static Map<Type, Type> get(Type type) {
return CACHE.computeIfAbsent(type, (key) -> createTypeMap(type));
} | @Test
public void getTypeArgumentTest(){
final Map<Type, Type> typeTypeMap = ActualTypeMapperPool.get(FinalClass.class);
typeTypeMap.forEach((key, value)->{
if("A".equals(key.getTypeName())){
assertEquals(Character.class, value);
} else if("B".equals(key.getTypeName())){
assertEquals(Boolean.class, v... |
public static ImmutableList<SbeField> generateFields(Ir ir, IrOptions irOptions) {
ImmutableList.Builder<SbeField> fields = ImmutableList.builder();
TokenIterator iterator = getIteratorForMessage(ir, irOptions);
while (iterator.hasNext()) {
Token token = iterator.next();
switch (token.signal())... | @Test
public void testGenerateFieldsWithMessageName() throws Exception {
Ir ir = getIr(OnlyPrimitivesMultiMessage.RESOURCE_PATH);
IrOptions msg1Opts = IrOptions.builder().setMessageName(Primitives1.NAME).build();
IrOptions msg2Opts = IrOptions.builder().setMessageName(Primitives2.NAME).build();
Immut... |
public static String getJwt(final String authorizationHeader) {
return authorizationHeader.replace(TOKEN_PREFIX, "");
} | @Test
void testGetJwt_WithEmptyHeader() {
// Given
String authorizationHeader = "";
// When
String jwt = Token.getJwt(authorizationHeader);
// Then
assertEquals("", jwt);
} |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final JsonNode event;
try {
event = objectMapper.readTree(payload);
if (event == null || event.isMissingNode()) {
throw new ... | @Test
public void decodeMessagesHandlesFilebeatMessages() throws Exception {
final Message message = codec.decode(messageFromJson("filebeat.json"));
assertThat(message).isNotNull();
assertThat(message.getMessage()).isEqualTo("TEST");
assertThat(message.getSource()).isEqualTo("example... |
@Override
public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements)
throws IOException {
return new FormattingJavaFileObject(
delegate.createSourceFile(name, originatingElements), formatter, messager);
} | @Test
public void formatsFile() throws IOException {
FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler());
JavaFileObject sourceFile = formattingFiler.createSourceFile("foo.Bar");
try (Writer writer = sourceFile.openWriter()) {
writer.write("package foo;class Bar{private String ... |
public String getType() {
return type;
} | @Test
void testDeserialize() throws IOException {
String testChecker = "{\"type\":\"TEST\",\"testValue\":\"\"}";
TestChecker actual = objectMapper.readValue(testChecker, TestChecker.class);
assertEquals("", actual.getTestValue());
assertEquals(TestChecker.TYPE, actual.getType());
... |
@NonNull
static LinkNavigation findPostNavigation(List<String> postNames, String target) {
Assert.notNull(target, "Target post name must not be null");
for (int i = 0; i < postNames.size(); i++) {
var item = postNames.get(i);
if (target.equals(item)) {
var pre... | @Test
void postPreviousNextPair() {
List<String> postNames = new ArrayList<>();
for (int i = 0; i < 10; i++) {
postNames.add("post-" + i);
}
// post-0, post-1, post-2
var previousNextPair = PostFinderImpl.findPostNavigation(postNames, "post-0");
assertTha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.