focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public boolean isEmpty() {
return true;
} | @Test
public void testIsEmpty() throws Exception {
assertTrue(NULL_QUERY_CACHE.isEmpty());
} |
Collection<OutputFile> compile() {
List<OutputFile> out = new ArrayList<>(queue.size() + 1);
for (Schema schema : queue) {
out.add(compile(schema));
}
if (protocol != null) {
out.add(compileInterface(protocol));
}
return out;
} | @Test
void maxParameterCounts() throws Exception {
Schema validSchema1 = createSampleRecordSchema(SpecificCompiler.MAX_FIELD_PARAMETER_UNIT_COUNT, 0);
assertTrue(new SpecificCompiler(validSchema1).compile().size() > 0);
Schema validSchema2 = createSampleRecordSchema(SpecificCompiler.MAX_FIELD_PARAMETER_U... |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefin... | @Test
public void testConvertUnsupported() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("aaa").dataType("aaa").build();
try {
DmdbTypeConverter.INSTANCE.convert(typeDefine);
Assertions.fail();
} catch (SeaTun... |
public static String removePrefixIgnoreCase(CharSequence str, CharSequence prefix) {
if (isEmpty(str) || isEmpty(prefix)) {
return str(str);
}
final String str2 = str.toString();
if (startWithIgnoreCase(str, prefix)) {
return subSuf(str2, prefix.length());// 截取后半段
}
return str2;
} | @Test
public void removePrefixIgnoreCaseTest(){
assertEquals("de", CharSequenceUtil.removePrefixIgnoreCase("ABCde", "abc"));
assertEquals("de", CharSequenceUtil.removePrefixIgnoreCase("ABCde", "ABC"));
assertEquals("de", CharSequenceUtil.removePrefixIgnoreCase("ABCde", "Abc"));
assertEquals("ABCde", CharSequen... |
@Override
public void processElement(final StreamRecord<T> element) throws Exception {
final T event = element.getValue();
final long previousTimestamp =
element.hasTimestamp() ? element.getTimestamp() : Long.MIN_VALUE;
final long newTimestamp = timestampAssigner.extractTimes... | @Test
void periodicWatermarksEmitOnPeriodicEmitStreamMode() throws Exception {
OneInputStreamOperatorTestHarness<Long, Long> testHarness =
createTestHarness(
WatermarkStrategy.forGenerator((ctx) -> new PeriodicWatermarkGenerator())
.wit... |
public CodegenTableDO buildTable(TableInfo tableInfo) {
CodegenTableDO table = CodegenConvert.INSTANCE.convert(tableInfo);
initTableDefault(table);
return table;
} | @Test
public void testBuildTable() {
// 准备参数
TableInfo tableInfo = mock(TableInfo.class);
// mock 方法
when(tableInfo.getName()).thenReturn("system_user");
when(tableInfo.getComment()).thenReturn("用户");
// 调用
CodegenTableDO table = codegenBuilder.buildTable(tab... |
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the fe... | @Test
void testApplyLigaturesFoglihtenNo07() throws IOException
{
CmapLookup cmapLookup;
GsubWorker gsubWorkerForLatin;
try (TrueTypeFont ttf = new OTFParser().parse(
new RandomAccessReadBufferedFile("src/test/resources/otf/FoglihtenNo07.otf")))
{
cmap... |
@Override
public void restartConnector(final String connName, final Callback<Void> callback) {
restartConnector(0, connName, callback);
} | @Test
public void testRestartConnector() throws Exception {
// get the initial assignment
when(member.memberId()).thenReturn("leader");
when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V0);
when(worker.isSinkConnector(CONN1)).thenReturn(Boolean.TRUE);
expect... |
public int read(final MessageHandler handler)
{
return read(handler, Integer.MAX_VALUE);
} | @Test
void shouldReadNothingFromEmptyBuffer()
{
final long head = 0L;
when(buffer.getLong(HEAD_COUNTER_INDEX)).thenReturn(head);
final MessageHandler handler = (msgTypeId, buffer, index, length) -> fail("should not be called");
final int messagesRead = ringBuffer.read(handler);... |
@JsonProperty(FIELD_ID)
public abstract String id(); | @Test
public void ignoreIdFieldWithUnderscore() throws Exception {
final URL eventString = Resources.getResource(getClass(), "filter-event-from-elasticsearch.json");
final ObjectMapper objectMapper = new ObjectMapperProvider().get();
final EventDto eventDto = objectMapper.readValue(eventStr... |
public static String fix(final String raw) {
if ( raw == null || "".equals( raw.trim() )) {
return raw;
}
MacroProcessor macroProcessor = new MacroProcessor();
macroProcessor.setMacros( macros );
return macroProcessor.parse( raw );
} | @Test
public void testLeaveAssertAlone() {
final String original = "drools.insert(foo)";
assertEqualsIgnoreWhitespace( original,
KnowledgeHelperFixerTest.fixer.fix( original ) );
} |
public static MetricName getMetricName(
String group,
String typeName,
String name
) {
return getMetricName(
group,
typeName,
name,
null
);
} | @Test
public void testTaggedMetricNameWithEmptyValue() {
LinkedHashMap<String, String> tags = new LinkedHashMap<>();
tags.put("foo", "bar");
tags.put("bar", "");
tags.put("baz", "raz.taz");
MetricName metricName = KafkaYammerMetrics.getMetricName(
"kafka.metrics"... |
@Override
protected void processOptions(LinkedList<String> args)
throws IOException {
CommandFormat cf = new CommandFormat(0, Integer.MAX_VALUE,
OPTION_PATHONLY, OPTION_DIRECTORY, OPTION_HUMAN,
OPTION_HIDENONPRINTABLE, OPTION_RECURSIVE, OPTION_REVERSE,
OPTION_MTIME, OPTION_SIZE, OPTION_A... | @Test(expected = UnsupportedOperationException.class)
public void processPathFileDisplayECPolicyWhenUnsupported()
throws IOException {
TestFile testFile = new TestFile("testDirectory", "testFile");
LinkedList<PathData> pathData = new LinkedList<PathData>();
pathData.add(testFile.getPathData());
... |
@Override
public CompletableFuture<RegistrationResponse> registerTaskExecutor(
final TaskExecutorRegistration taskExecutorRegistration, final Time timeout) {
CompletableFuture<TaskExecutorGateway> taskExecutorGatewayFuture =
getRpcService()
.connect(
... | @Test
void testTaskExecutorBecomesUnreachableTriggersDisconnect() throws Exception {
final ResourceID taskExecutorId = ResourceID.generate();
final CompletableFuture<Exception> disconnectFuture = new CompletableFuture<>();
final CompletableFuture<ResourceID> stopWorkerFuture = new Completabl... |
public synchronized void maybeAddPartition(TopicPartition topicPartition) {
maybeFailWithError();
throwIfPendingState("send");
if (isTransactional()) {
if (!hasProducerId()) {
throw new IllegalStateException("Cannot add partition " + topicPartition +
... | @Test
public void testFailIfNotReadyForSendNoProducerId() {
assertThrows(IllegalStateException.class, () -> transactionManager.maybeAddPartition(tp0));
} |
public static PredicateTreeAnalyzerResult analyzePredicateTree(Predicate predicate) {
AnalyzerContext context = new AnalyzerContext();
int treeSize = aggregatePredicateStatistics(predicate, false, context);
int minFeature = ((int)Math.ceil(findMinFeature(predicate, false, context))) + (context.h... | @Test
void require_that_multilevel_and_stores_size() {
Predicate p =
and(
and(
feature("foo").inSet("bar"),
feature("baz").inSet("qux"),
feature("quux").inSet("corge")),
... |
@Override
public ClusterHealth checkCluster() {
checkState(!nodeInformation.isStandalone(), "Clustering is not enabled");
checkState(sharedHealthState != null, "HealthState instance can't be null when clustering is enabled");
Set<NodeHealth> nodeHealths = sharedHealthState.readAll();
Health health = ... | @Test
public void checkCluster_returns_GREEN_status_if_only_GREEN_statuses_returned_by_ClusterHealthChecks() {
when(nodeInformation.isStandalone()).thenReturn(false);
List<Health.Status> statuses = IntStream.range(1, 1 + random.nextInt(20)).mapToObj(i -> GREEN).toList();
HealthCheckerImpl underTest = newC... |
@Override
public Collection<LocalDataQueryResultRow> getRows(final ShowGlobalClockRuleStatement sqlStatement, final ContextManager contextManager) {
GlobalClockRuleConfiguration ruleConfig = rule.getConfiguration();
return Collections.singleton(new LocalDataQueryResultRow(ruleConfig.getType(), ruleC... | @Test
void assertGlobalClockRule() throws SQLException {
engine.executeQuery();
Collection<LocalDataQueryResultRow> actual = engine.getRows();
assertThat(actual.size(), is(1));
Iterator<LocalDataQueryResultRow> iterator = actual.iterator();
LocalDataQueryResultRow row = itera... |
public static Coder<PublishResult> fullPublishResultWithoutHeaders() {
return new PublishResultCoder(
RESPONSE_METADATA_CODER, NullableCoder.of(AwsCoders.sdkHttpMetadataWithoutHeaders()));
} | @Test
public void testFullPublishResultWithoutHeadersDecodeEncodeEquals() throws Exception {
CoderProperties.coderDecodeEncodeEqual(
PublishResultCoders.fullPublishResultWithoutHeaders(),
new PublishResult().withMessageId(UUID.randomUUID().toString()));
PublishResult value = buildFullPublishR... |
public JunctionTree junctionTree(List<OpenBitSet> cliques, boolean init) {
return junctionTree(null, null, null, cliques, init);
} | @Test
public void testJunctionWithPruning2() {
Graph<BayesVariable> graph = new BayesNetwork();
GraphNode x0 = addNode(graph);
GraphNode x1 = addNode(graph);
GraphNode x2 = addNode(graph);
GraphNode x3 = addNode(graph);
GraphNode x4 = addNode(graph);
GraphNode... |
@Override
public String getName() {
return _name;
} | @Test
public void testStringRepeatTransformFunction() {
int timesToRepeat = 21;
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("repeat(%s, %d)", STRING_ALPHANUM_SV_COLUMN, timesToRepeat));
TransformFunction transformFunction = TransformFunctionFactory.get(expression... |
public PublicKey convertPublicKey(final String publicPemKey) {
final StringReader keyReader = new StringReader(publicPemKey);
try {
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
.getInstance(new PEMParser(keyReader).readObject());
return new JcaPE... | @Test
void givenEmptyPublicKey_whenConvertPublicKey_thenThrowRuntimeException() {
// Given
String emptyPublicPemKey = "";
// When & Then
assertThatThrownBy(() -> KeyConverter.convertPublicKey(emptyPublicPemKey))
.isInstanceOf(RuntimeException.class)
.... |
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteJob(Long id) throws SchedulerException {
// 校验存在
JobDO job = validateJobExists(id);
// 更新
jobMapper.deleteById(id);
// 删除 Job 到 Quartz 中
schedulerManager.deleteJob(job.getHandlerName());
... | @Test
public void testDeleteJob_success() throws SchedulerException {
// mock 数据
JobDO job = randomPojo(JobDO.class);
jobMapper.insert(job);
// 调用
jobService.deleteJob(job.getId());
// 校验不存在
assertNull(jobMapper.selectById(job.getId()));
// 校验调用
... |
@Override
public Headers add(Header header) throws IllegalStateException {
Objects.requireNonNull(header, "Header cannot be null.");
canWrite();
headers.add(header);
return this;
} | @Test
public void shouldThrowNpeWhenAddingNullHeader() {
final RecordHeaders recordHeaders = new RecordHeaders();
assertThrows(NullPointerException.class, () -> recordHeaders.add(null));
} |
@Override
public Mono<Long> delete(final long id) {
return Mono.zip(
dataSourceRepository.existsByNamespace(id),
collectorRepository.existsByNamespace(id),
termRepository.existsByNamespace(id),
dataEntityRepository.existsNonDeletedByNamespaceId... | @Test
@DisplayName("Deletes a namespace which isn't tied with any data sources, collector or term from the database")
public void testDelete() {
final long namespaceId = 1L;
final NamespacePojo namespace = new NamespacePojo()
.setId(namespaceId)
.setDeletedAt(LocalDateTi... |
public static Path getClusterHighAvailableStoragePath(Configuration configuration) {
final String storagePath = configuration.getValue(HighAvailabilityOptions.HA_STORAGE_PATH);
if (isNullOrWhitespaceOnly(storagePath)) {
throw new IllegalConfigurationException(
"Configura... | @Test
public void testGetClusterHighAvailableStoragePath() throws IOException {
final String haStorageRootDirectory = temporaryFolder.newFolder().getAbsolutePath();
final String clusterId = UUID.randomUUID().toString();
final Configuration configuration = new Configuration();
config... |
static SuggestedItem findClosestSuggestedItem(List<SuggestedItem> r, String query) {
for (SuggestedItem curItem : r) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(String.format("item's searchUrl:%s;query=%s", curItem.item.getSearchUrl(), query));
}
if (cu... | @Test
public void findClosestSuggestedItem() {
final String query = "foobar 123";
final String searchName = "sameDisplayName";
SearchItem searchItemHit = new SearchItem() {
@Override
public SearchIndex getSearchIndex() {
return null;
}... |
@Override
public InterpreterResult interpret(final String st, final InterpreterContext context)
throws InterpreterException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("st:\n{}", st);
}
final FormType form = getFormType();
RemoteInterpreterProcess interpreterProcess = null;
try {
... | @Test
public void testParallelScheduler() throws InterruptedException, InterpreterException {
interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED);
interpreterSetting.setProperty("zeppelin.SleepInterpreter.parallel", "true");
final Interpreter interpreter1 = interpreterSetting.getInterpret... |
public static String post(HttpURLConnection con,
Map<String, String> headers,
String requestBody,
Integer connectTimeoutMs,
Integer readTimeoutMs)
throws IOException, UnretryableException {
handleInput(con, headers, requestBody, connectTimeoutMs, readTimeoutMs);
r... | @Test
public void testErrorResponseRetryableCode() throws IOException {
HttpURLConnection mockedCon = createHttpURLConnection("dummy");
when(mockedCon.getInputStream()).thenThrow(new IOException("Can't read"));
when(mockedCon.getErrorStream()).thenReturn(new ByteArrayInputStream(
... |
@Override
protected SubtaskExecutionAttemptDetailsInfo handleRequest(
HandlerRequest<EmptyRequestBody> request, AccessExecutionVertex executionVertex)
throws RestHandlerException {
final AccessExecution execution = executionVertex.getCurrentExecutionAttempt();
final JobID j... | @Test
void testHandleRequest() throws Exception {
// Prepare the execution graph.
final JobID jobID = new JobID();
final JobVertexID jobVertexID = new JobVertexID();
// The testing subtask.
final long deployingTs = System.currentTimeMillis() - 1024;
final long finis... |
@Override
public URL getResource(final String name) {
try {
final Enumeration<URL> resources = getResources(name);
if (resources.hasMoreElements()) {
return resources.nextElement();
}
} catch (IOException ignored) {
// mimics the behavi... | @Test
void testComponentFirstResourceFoundIgnoresOwner() throws Exception {
String resourceToLoad = TempDirUtils.newFile(tempFolder).getName();
TestUrlClassLoader owner =
new TestUrlClassLoader(resourceToLoad, RESOURCE_RETURNED_BY_OWNER);
final ComponentClassLoader component... |
@Override
public AppResponse process(Flow flow, AppRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
var response = new WidPollResponse(attestEnabled && Arrays.asList(allowedActions).contains(appSession.getAction()));
setValid(false);
switch (appSessi... | @Test
void processAttestDisabled() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException {
setupWidPolling(false);
WidPollResponse appResponse = (WidPollResponse) widPolling.process(mockedFlow, mockedAbstractAppRequest);
assertFalse(appResponse.getAttestApp());
asse... |
public static List<String> join(Map<String, String> map, String separator) {
if (map == null) {
return null;
}
List<String> list = new ArrayList<>();
if (map.size() == 0) {
return list;
}
for (Map.Entry<String, String> entry : map.entrySet()) {
... | @Test
void testJoinList() {
List<String> list = emptyList();
assertEquals("", CollectionUtils.join(list, "/"));
list = Arrays.asList("x");
assertEquals("x", CollectionUtils.join(list, "-"));
list = Arrays.asList("a", "b");
assertEquals("a/b", CollectionUtils.join(li... |
public boolean isInputSelected(int inputId) {
return (inputMask & (1L << (inputId - 1))) != 0;
} | @Test
void testIsInputSelected() {
assertThat(new Builder().build().isInputSelected(1)).isFalse();
assertThat(new Builder().select(2).build().isInputSelected(1)).isFalse();
assertThat(new Builder().select(1).build().isInputSelected(1)).isTrue();
assertThat(new Builder().select(1).se... |
@Override
public void schedule(Object task) {
} | @Test
public void test() {
NopScheduler scheduler = new NopScheduler();
scheduler.schedule(new IOBuffer(64));
} |
@Override
public void uncaughtException(@NonNull Thread thread, Throwable ex) {
ex.printStackTrace();
Logger.e(TAG, "Caught an unhandled exception!!!", ex);
// https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/15
// https://github.com/AnySoftKeyboard/AnySoftKeyboard/issues/433
final Strin... | @Test
public void testCrashLogFileWasCreated() throws Exception {
Application app = ApplicationProvider.getApplicationContext();
NotificationDriver notificationDriver = Mockito.mock(NotificationDriver.class);
TestableChewbaccaUncaughtExceptionHandler underTest =
new TestableChewbaccaUncaughtExcept... |
public static Checksum newInstance(final String className)
{
Objects.requireNonNull(className, "className is required!");
if (Crc32.class.getName().equals(className))
{
return crc32();
}
else if (Crc32c.class.getName().equals(className))
{
ret... | @Test
void newInstanceThrowsIllegalArgumentExceptionIfClassIsNotFound()
{
final IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class, () -> Checksums.newInstance("a.b.c.MissingClass"));
assertEquals(ClassNotFoundException.class, exception.getCause().getCl... |
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) {
in.markReaderIndex();
MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c... | @Test
void assertBinlogEventBodyIncomplete() {
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
byte[] completeData = StringUtil.decodeHexDump("002a80a862200100000038000000c569000000007400000000000100020004ff0801000000000000000100000007535543434553531c9580c5");
byteBuf.writeBytes(complet... |
static Catalog loadCatalog(IcebergSinkConfig config) {
return CatalogUtil.buildIcebergCatalog(
config.catalogName(), config.catalogProps(), loadHadoopConfig(config));
} | @Test
public void testLoadCatalogNoHadoopDir() {
Map<String, String> props =
ImmutableMap.of(
"topics",
"mytopic",
"iceberg.tables",
"mytable",
"iceberg.hadoop.conf-prop",
"conf-value",
"iceberg.catalog.catalog-impl",
... |
@Override
public HttpResponse send(HttpRequest httpRequest) throws IOException {
return send(httpRequest, null);
} | @Test
public void send_default_userAgent() throws IOException, InterruptedException {
String responseBody = "test response";
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(HttpStatus.OK.code())
.setHeader(CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString())
... |
public static Builder newChangesetBuilder() {
return new Builder();
} | @Test
public void test_to_string() {
Changeset underTest = Changeset.newChangesetBuilder()
.setAuthor("john")
.setDate(123456789L)
.setRevision("rev-1")
.build();
assertThat(underTest).hasToString("Changeset{revision='rev-1', author='john', date=123456789}");
} |
public URLNormalizer removeFragment() {
url = url.replaceFirst("(.*?)(#.*)", "$1");
return this;
} | @Test
public void testRemoveFragment() {
s = "http://www.example.com/bar.html#section1";
t = "http://www.example.com/bar.html";
assertEquals(t, n(s).removeFragment().toString());
s = "http://www.example.com/bar.html#";
t = "http://www.example.com/bar.html";
assertEqua... |
@Override
public ColumnStatisticsObj aggregate(List<ColStatsObjWithSourceInfo> colStatsWithSourceInfo,
List<String> partNames, boolean areAllPartsFound) throws MetaException {
checkStatisticsList(colStatsWithSourceInfo);
ColumnStatisticsObj statsObj = null;
String colType;
String colName ... | @Test
public void testAggregateSingleStat() throws MetaException {
List<String> partitions = Collections.singletonList("part1");
long[] values = { DATE_1.getDaysSinceEpoch(), DATE_4.getDaysSinceEpoch() };
ColumnStatisticsData data1 = new ColStatsBuilder<>(Date.class).numNulls(1).numDVs(2).low(DATE_1).hig... |
@Override
public int getScale(final int column) {
Preconditions.checkArgument(1 == column);
return 0;
} | @Test
void assertGetScale() throws SQLException {
assertThat(actualMetaData.getScale(1), is(0));
} |
@Override
public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) {
ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id);
if (errorLog == null) {
throw exception(API_ERROR_LOG_NOT_FOUND);
}
if (!ApiErrorLogProcessStatusEnum.INIT.getSt... | @Test
public void testUpdateApiErrorLogProcess_success() {
// 准备参数
ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class,
o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()));
apiErrorLogMapper.insert(apiErrorLogDO);
// 准备参数
Long id =... |
public BatchConfig(String tableNameWithType, Map<String, String> batchConfigsMap) {
_batchConfigMap = batchConfigsMap;
_tableNameWithType = tableNameWithType;
String inputFormat = batchConfigsMap.get(BatchConfigProperties.INPUT_FORMAT);
if (inputFormat != null) {
_inputFormat = FileFormat.valueOf... | @Test
public void testBatchConfig() {
Map<String, String> batchConfigMap = new HashMap<>();
String tableName = "foo_REALTIME";
String inputDir = "s3://foo/input";
String outputDir = "s3://foo/output";
String inputFsClass = "org.apache.S3FS";
String outputFsClass = "org.apache.GcsGS";
Strin... |
@Override
public AppResponse process(Flow flow, CheckAuthenticationStatusRequest request){
switch(appSession.getState()) {
case "AUTHENTICATION_REQUIRED", "AWAITING_QR_SCAN":
return new CheckAuthenticationStatusResponse("PENDING", false);
case "RETRIEVED", "AWAITING_C... | @Test
void processAuthenticated() {
appSession.setState("AUTHENTICATED");
AppResponse response = checkAuthenticationStatus.process(flow, request);
assertTrue(response instanceof OkResponse);
} |
public void verifyPassword(AttendeePassword other) {
if (!this.equals(other)) {
throw new MomoException(AttendeeErrorCode.PASSWORD_MISMATCHED);
}
} | @DisplayName("비밀번호가 서로 다르면 예외를 발생시킨다.")
@Test
void throwsExceptionForMismatchedPasswords() {
AttendeePassword password = new AttendeePassword("1234");
AttendeePassword other = new AttendeePassword("123456");
assertThatThrownBy(() -> password.verifyPassword(other))
.isIns... |
public static <T> Object create(Class<T> iface, T implementation,
RetryPolicy retryPolicy) {
return RetryProxy.create(iface,
new DefaultFailoverProxyProvider<T>(iface, implementation),
retryPolicy);
} | @Test
public void testRetryForever() throws UnreliableException {
UnreliableInterface unreliable = (UnreliableInterface)
RetryProxy.create(UnreliableInterface.class, unreliableImpl, RETRY_FOREVER);
unreliable.alwaysSucceeds();
unreliable.failsOnceThenSucceeds();
unreliable.failsTenTimesThenSucce... |
@VisibleForTesting
static void moveIfDoesNotExist(Path source, Path destination) throws IOException {
String errorMessage =
String.format(
"unable to move: %s to %s; such failures are often caused by interference from "
+ "antivirus (https://github.com/GoogleContainerTools/jib/... | @Test
public void testMoveIfDoesNotExist_exceptionAfterFailure() {
Exception exception =
assertThrows(
IOException.class,
() -> CacheStorageWriter.moveIfDoesNotExist(Paths.get("foo"), Paths.get("bar")));
assertThat(exception)
.hasMessageThat()
.contains(
... |
public void setPercentOfJvmHeap(int percentOfJvmHeap) {
if (percentOfJvmHeap > 0) {
setLimit(Math.round(Runtime.getRuntime().maxMemory() * percentOfJvmHeap / 100.0));
}
} | @Test
public void testPercentOfJvmHeap() throws Exception {
underTest.setPercentOfJvmHeap(50);
assertEquals("limit is half jvm limit", Math.round(Runtime.getRuntime().maxMemory() / 2.0), underTest.getLimit());
} |
@GET
@Path("{path:.*}")
@Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8})
public Response get(@PathParam("path") String path,
@Context UriInfo uriInfo,
@QueryParam(OperationParam.NAME) O... | @Test
@TestDir
@TestJetty
@TestHdfs
public void testGetServerDefaults() throws Exception {
createHttpFSServer(false, false);
String pathStr1 = "/";
Path path1 = new Path(pathStr1);
DistributedFileSystem dfs = (DistributedFileSystem) FileSystem
.get(path1.toUri(), TestHdfsHelper.getHdfsCo... |
public Printed<K, V> withLabel(final String label) {
Objects.requireNonNull(label, "label can't be null");
this.label = label;
return this;
} | @Test
public void shouldPrintWithLabel() throws UnsupportedEncodingException {
final Processor<String, Integer, Void, Void> processor = new PrintedInternal<>(sysOutPrinter.withLabel("label"))
.build("processor")
.get();
processor.process(new Record<>("hello", 3, 0L))... |
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
} | @Test
public void verify_myNewIssues_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = MyNewIssuesNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(MY_NEW_ISSUES_DISPATCHER_KEY);
} |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, final Callback<RestResponse> callback)
{
if (HttpMethod.POST != HttpMethod.valueOf(request.getMethod()))
{
_log.error("POST is expected, but " + request.getMethod() + " received");
callback.onError(RestExcept... | @Test(dataProvider = "multiplexerConfigurations")
public void testHandleError(MultiplexerRunMode multiplexerRunMode) throws Exception
{
SynchronousRequestHandler mockHandler = createMockHandler();
MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(mockHandler, multiplexerRunMode);
RequestCont... |
public <T extends Config> T getConfig(Class<T> clazz)
{
if (!Modifier.isPublic(clazz.getModifiers()))
{
throw new RuntimeException("Non-public configuration classes can't have default methods invoked");
}
T t = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]
{
clazz
}, handler);... | @Test
public void testGetConfig() throws IOException
{
manager.setConfiguration("test", "key", "moo");
TestConfig conf = manager.getConfig(TestConfig.class);
Assert.assertEquals("moo", conf.key());
} |
@Override
public ByteBuf writeBytes(byte[] src, int srcIndex, int length) {
ensureWritable(length);
setBytes(writerIndex, src, srcIndex, length);
writerIndex += length;
return this;
} | @Test
public void testWriteBytesAfterRelease8() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() throws IOException {
releasedBuffer().writeBytes(new TestScatteringByteChannel(), 1);
}
});
... |
@Override
protected Class<?> loadClass(final String name, final boolean resolve)
throws ClassNotFoundException {
if (blacklist.test(name)) {
throw new ClassNotFoundException("The requested class is not permitted to be used from a "
+ "udf. Class " + name);
}
Class<?> clazz = findLoad... | @Test
public void shouldLoadNonConfluentClassesFromChildFirst() throws ClassNotFoundException {
assertThat(parentLoader.findClass(IN_PARENT_AND_JAR), is(equalTo(InParentAndJar.class)));
assertThat(udfClassLoader.loadClass(IN_PARENT_AND_JAR, true), not(InParentAndJar.class));
} |
public static void removeMatching(Collection<String> values, String... patterns) {
removeMatching(values, Arrays.asList(patterns));
} | @Test
public void testRemoveMatchingWithMatchingPattern() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.removeMatching(values, "A");
assertTrue(values.isEmpty());
} |
@Override
public Iterator iterator() {
if (entries == null) {
return Collections.emptyIterator();
}
return new ResultIterator();
} | @Test
public void testIterator_whenEmpty() {
List<Map.Entry> emptyList = Collections.emptyList();
ResultSet resultSet = new ResultSet(emptyList, IterationType.KEY);
Iterator iterator = resultSet.iterator();
assertFalse(iterator.hasNext());
} |
@Override
public Flux<RawMetric> retrieve(KafkaCluster c, Node node) {
log.debug("Retrieving metrics from prometheus exporter: {}:{}", node.host(), c.getMetricsConfig().getPort());
MetricsConfig metricsConfig = c.getMetricsConfig();
var webClient = new WebClientConfigurator()
.configureBufferSize... | @Test
void callsSecureMetricsEndpointAndConvertsResponceToRawMetric() {
var url = mockWebServer.url("/metrics");
mockWebServer.enqueue(prepareResponse());
MetricsConfig metricsConfig = prepareMetricsConfig(url.port(), "username", "password");
StepVerifier.create(retriever.retrieve(WebClient.create(... |
public final void isAtMost(int other) {
asDouble.isAtMost(other);
} | @Test
public void isAtMost_int_withNoExactFloatRepresentation() {
expectFailureWhenTestingThat(0x1.0p30f).isAtMost((1 << 30) - 1);
} |
@PostMapping("create")
public String createProduct(NewProductPayload payload,
Model model,
HttpServletResponse response) {
try {
Product product = this.productsRestClient.createProduct(payload.title(), payload.details());
... | @Test
@DisplayName("createProduct вернёт страницу с ошибками, если запрос невалиден")
void createProduct_RequestIsInvalid_ReturnsProductFormWithErrors() {
// given
var payload = new NewProductPayload(" ", null);
var model = new ConcurrentModel();
var response = new MockHttpServl... |
@Override
public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) {
if (client.getId() != null) { // if it's not null, it's already been saved, this is an error
throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId());
}
if (client.getRegisteredRedi... | @Test(expected = IllegalArgumentException.class)
public void heartMode_implicit_invalidGrants() {
Mockito.when(config.isHeartMode()).thenReturn(true);
ClientDetailsEntity client = new ClientDetailsEntity();
Set<String> grantTypes = new LinkedHashSet<>();
grantTypes.add("implicit");
grantTypes.add("authoriza... |
public static Range<Comparable<?>> safeIntersection(final Range<Comparable<?>> range, final Range<Comparable<?>> connectedRange) {
try {
return range.intersection(connectedRange);
} catch (final ClassCastException ex) {
Class<?> clazz = getRangeTargetNumericType(range, connectedR... | @Test
void assertSafeIntersectionForBigInteger() {
Range<Comparable<?>> range = Range.upTo(new BigInteger("131323233123211"), BoundType.CLOSED);
Range<Comparable<?>> connectedRange = Range.downTo(35, BoundType.OPEN);
Range<Comparable<?>> newRange = SafeNumberOperationUtils.safeIntersection(r... |
public String getPassword() {
return password;
} | @Test
void hasAPassword() {
assertThat(credentials.getPassword()).isEqualTo("p");
} |
@Override
public String toString() {
try {
return new ObjectMapper().configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
.setSerializationInclusion(Include.NON_NULL).writeValueAsString(this... | @Test
public void testAlertaMessageJsonFormatWithoutNullValues() {
AlertaMessage alertaMessage = new AlertaMessage("resource", "event");
String expectedJson =
"{\"event\":\"event\","
+ "\"resource\":\"resource\"}";
assertEquals(expectedJson, alertaMessage.toString());
} |
public void readFrom(InputStream inStream, int offset, int length) throws IOException {
ensureCapacity(offset + length);
ByteStreams.readFully(inStream, buffer, offset, length);
size = offset + length;
} | @Test
public void testReadFrom() throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(TEST_DATA_A);
RandomAccessData stream = new RandomAccessData();
stream.readFrom(bais, 3, 2);
assertArrayEquals(
new byte[] {0x00, 0x00, 0x00, 0x01, 0x02}, Arrays.copyOf(stream.array(), stre... |
public static String analytical(String expression, String language) throws Exception {
return analytical(expression, new HashMap<>(), language);
} | @Test
public void testJson2(){
String js = ExpressionUtils.analytical("{\n" +
" \"msgtype\": \"markdown\",\n" +
" \"markdown\": {\n" +
" \"title\":\"消息类型:${messageType}\",\n" +
" \"text\": \" - 设备ID: `${deviceId}` 值:`${p... |
public void start() {
// Last minute init. Neither properties not annotations provided an
// injector source.
if (injector == null) {
injector = createDefaultScenarioModuleInjectorSource().getInjector();
}
scenarioScope = injector.getInstance(ScenarioScope.class);
... | @Test
void shouldStartWhenInjectorSourceIsNull() {
factory = new GuiceFactory();
factory.start();
} |
@Override
protected boolean notExist() {
return Stream.of(ConsulConstants.PLUGIN_DATA, ConsulConstants.AUTH_DATA, ConsulConstants.META_DATA).allMatch(this::dataKeyNotExist);
} | @Test
public void testNotExist() throws Exception {
ConsulDataChangedInit consulDataChangedInit = new ConsulDataChangedInit(consulClient);
assertNotNull(consulDataChangedInit);
Response<GetValue> pluginResponse = mock(Response.class);
when(consulClient.getKVValue(ConsulConstants.PLU... |
@Override
public GroupAssignment assign(
GroupSpec groupSpec,
SubscribedTopicDescriber subscribedTopicDescriber
) throws PartitionAssignorException {
if (groupSpec.memberIds().isEmpty())
return new GroupAssignment(Collections.emptyMap());
if (groupSpec.subscriptionTy... | @Test
public void testAssignWithSubscribedToNonExistentTopic() {
SubscribedTopicDescriberImpl subscribedTopicMetadata = new SubscribedTopicDescriberImpl(
Collections.singletonMap(
TOPIC_1_UUID,
new TopicMetadata(
TOPIC_1_UUID,
... |
public static String randomUUID() {
return UUID.randomUUID().toString();
} | @Test
public void randomUUIDTest() {
String simpleUUID = IdUtil.simpleUUID();
assertEquals(32, simpleUUID.length());
String randomUUID = IdUtil.randomUUID();
assertEquals(36, randomUUID.length());
} |
public ConnectorType connectorType(Map<String, String> connConfig) {
if (connConfig == null) {
return ConnectorType.UNKNOWN;
}
String connClass = connConfig.get(ConnectorConfig.CONNECTOR_CLASS_CONFIG);
if (connClass == null) {
return ConnectorType.UNKNOWN;
... | @Test
public void testGetConnectorTypeWithMissingPlugin() {
String connName = "AnotherPlugin";
AbstractHerder herder = testHerder();
when(worker.getPlugins()).thenReturn(plugins);
when(plugins.newConnector(anyString())).thenThrow(new ConnectException("No class found"));
asser... |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatOptionalMap() {
// Given:
final Schema schema = SchemaBuilder
.map(Schema.OPTIONAL_STRING_SCHEMA, Schema.OPTIONAL_FLOAT64_SCHEMA)
.optional()
.build();
// Then:
assertThat(DEFAULT.format(schema), is("MAP<VARCHAR, DOUBLE>"));
assertThat(STRICT.... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testNewClusterWithOldProtocolVersion(VertxTestContext context) {
VersionChangeCreator vcc = mockVersionChangeCreator(
mockKafka(VERSIONS.defaultVersion().version(), "2.8", "2.7"),
mockNewCluster(null, null, List.of())
);
Checkpoint async = c... |
public Item and(Item item) {
Item result = and(getRoot(), item);
setRoot(result);
return result;
} | @Test
void testAddQueryItemWithRoot() {
assertEquals("AND a b",
new QueryTree(new WordItem("a")).and(new WordItem("b")).toString());
NotItem not = new NotItem();
not.addNegativeItem(new WordItem("b"));
assertEquals("+a -b",
new QueryTree(new WordItem(... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
if(0L == status.getLength()) {
return new NullInputStream(0L);
}
final Storage.Objects.Get request = sessi... | @Test
public void testReadPreviousVersion() throws Exception {
final int length = 8;
final byte[] content = RandomUtils.nextBytes(length);
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
assertTrue(new GoogleStorageVersioningFe... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
// {"code":400,"message":"Bad Request","debugInfo":"Node ID must be positive.","errorCode":-80001}
final PathAttributes attributes = new PathAtt... | @Test
public void testChangedNodeId() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Ty... |
public long onStatusMessage(
final StatusMessageFlyweight flyweight,
final InetSocketAddress receiverAddress,
final long senderLimit,
final int initialTermId,
final int positionBitsToShift,
final long timeNs)
{
return processStatusMessage(
flyweigh... | @Test
void shouldNotIncludeReceiverMoreThanWindowSizeBehindMinPosition()
{
final UdpChannel udpChannel = UdpChannel.parse(
"aeron:udp?endpoint=224.20.30.39:24326|interface=localhost|fc=min,g:123/2");
flowControl.initialize(
newContext(), countersManager, udpChannel, 0, 0... |
public static int MurmurHash3_x86_32(byte[] data, int offset, int len) {
final long endIndex = (long) offset + len - 1;
assert endIndex >= Integer.MIN_VALUE && endIndex <= Integer.MAX_VALUE
: String.format("offset %,d len %,d would cause int overflow", offset, len);
return Murmur... | @Test(expected = AssertionError.class)
@RequireAssertEnabled
public void testMurmurHash3_x86_32_withIntOverflow() {
MurmurHash3_x86_32(null, Integer.MAX_VALUE, Integer.MAX_VALUE);
} |
@Override
public boolean contains(CharSequence name) {
return get(name) != null;
} | @Test
public void testContainsNameAndValue() {
Http2Headers headers = newClientHeaders();
assertTrue(headers.contains("Name1", "value1"));
assertFalse(headers.contains("Name1", "Value1"));
assertTrue(headers.contains("name2", "Value2", true));
assertFalse(headers.contains("na... |
public void createQprofileChangesForRuleUpdates(DbSession dbSession, Set<PluginRuleUpdate> pluginRuleUpdates) {
List<QProfileChangeDto> changesToPersist = pluginRuleUpdates.stream()
.flatMap(pluginRuleUpdate -> {
RuleChangeDto ruleChangeDto = createNewRuleChange(pluginRuleUpdate);
insertRuleCh... | @Test
public void updateWithoutCommit_whenTwoRulesChangedTheirImpactsAndAttributes_thenInsertRuleChangeAndImpactChange() {
PluginRuleUpdate pluginRuleUpdate = new PluginRuleUpdate();
pluginRuleUpdate.setNewCleanCodeAttribute(CleanCodeAttribute.CLEAR);
pluginRuleUpdate.setOldCleanCodeAttribute(CleanCodeAtt... |
@Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declare(output.fields());
} | @Test
public void fieldsAreDeclaredThroughProvidedOutput() {
Fields fields = new Fields(UUID.randomUUID().toString());
when(output.fields()).thenReturn(fields);
OutputFieldsDeclarer declarer = mock(OutputFieldsDeclarer.class);
bolt.declareOutputFields(declarer);
ArgumentCapt... |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testCorruptMessageError() {
buildFetcher();
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 0);
assertEquals(1, sendFetches());
assertFalse(fetcher.hasCompletedFetches());
// Prepare a response with the CORRUPT_MESSAGE error.
client... |
protected Map<String, Object> fetchActionRequestContext(Method method, Object[] arguments) {
Map<String, Object> context = new HashMap<>(8);
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
for (int j = 0... | @Test
public void testBusinessActionContext() throws NoSuchMethodException {
Method prepareMethod = TestAction.class.getDeclaredMethod("prepare",
BusinessActionContext.class, int.class, List.class, TestParam.class);
List<Object> list = new ArrayList<>();
list.add("b");
... |
public String getBaseUrl() {
String url = config.get(SERVER_BASE_URL).orElse("");
if (isEmpty(url)) {
url = computeBaseUrl();
}
// Remove trailing slashes
return StringUtils.removeEnd(url, "/");
} | @Test
public void base_url_is_http_localhost_9000_when_port_is_negative() {
settings.setProperty(PORT_PORPERTY, -23);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
} |
@Override
public T setDouble(K name, double value) {
throw new UnsupportedOperationException("read only");
} | @Test
public void testSetDouble() {
assertThrows(UnsupportedOperationException.class, new Executable() {
@Override
public void execute() {
HEADERS.setDouble("name", 0);
}
});
} |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
if(workdir.isRoot()) {
if(StringUtils.isEmpty(RequestEntityRestStorageService.findBucketInHostname(session.getHost()))) {
f... | @Test
public void testSearchInBucket() throws Exception {
final String name = new AlphanumericRandomStringService().random();
final Path root = new Path("/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path bucket = new Path(root, "test-eu-central-1-cyberduck", EnumSet.of(Path.... |
static Serde<List<?>> createSerde(final PersistenceSchema schema) {
final List<SimpleColumn> columns = schema.columns();
if (columns.isEmpty()) {
// No columns:
return new KsqlVoidSerde<>();
}
if (columns.size() != 1) {
throw new KsqlException("The '" + FormatFactory.KAFKA.name()
... | @Test
public void shouldHandleEmptyKey() {
// Given:
final LogicalSchema logical = LogicalSchema.builder()
.valueColumn(ColumnName.of("f0"), SqlTypes.INTEGER)
.build();
final PersistenceSchema schema = PhysicalSchema
.from(logical, SerdeFeatures.of(), SerdeFeatures.of())
.... |
@Override
public void close() {
store.close();
} | @Test
public void shouldCloseVersionedStore() {
givenWrapperWithVersionedStore();
wrapper.close();
verify(versionedStore).close();
} |
@Override
public UserAccount writeToDb(final UserAccount userAccount) {
db.getCollection(USER_ACCOUNT).insertOne(
new Document(USER_ID, userAccount.getUserId())
.append(USER_NAME, userAccount.getUserName())
.append(ADD_INFO, userAccount.getAdditionalInfo())
... | @Test
void writeToDb() {
MongoCollection<Document> mongoCollection = mock(MongoCollection.class);
when(db.getCollection(CachingConstants.USER_ACCOUNT)).thenReturn(mongoCollection);
assertDoesNotThrow(()-> {mongoDb.writeToDb(userAccount);});
} |
public String process(final Expression expression) {
return formatExpression(expression);
} | @Test
public void shouldGenerateCastExpressionsWhichAreComparable() {
// Given:
final Expression cast = new Cast(new StringLiteral("2020-01-01"), new io.confluent.ksql.execution.expression.tree.Type(SqlTypes.DATE));
final ComparisonExpression exp = new ComparisonExpression(Type.GREATER_THAN_... |
@Override
public Long sendSingleMailToMember(String mail, Long userId,
String templateCode, Map<String, Object> templateParams) {
// 如果 mail 为空,则加载用户编号对应的邮箱
if (StrUtil.isEmpty(mail)) {
mail = memberService.getMemberUserEmail(userId);
}
... | @Test
public void testSendSingleMailToMember() {
// 准备参数
Long userId = randomLongId();
String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// ... |
public Type getGELFType() {
if (payload.length < Type.HEADER_SIZE) {
throw new IllegalStateException("GELF message is too short. Not even the type header would fit.");
}
return Type.determineType(payload[0], payload[1]);
} | @Test
public void testGetGELFTypeDetectsUncompressedMessage() throws Exception {
byte[] fakeData = new byte[20];
fakeData[0] = (byte) '{';
fakeData[1] = (byte) '\n';
GELFMessage msg = new GELFMessage(fakeData);
assertEquals(GELFMessage.Type.UNCOMPRESSED, msg.getGELFType());
... |
@Override
public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter)
throws IOException {
EthCall ethCall =
web3j.ethCall(
Transaction.createEthCallTransaction(getFromAddress(), to, data),
... | @Test
void sendCallErrorRevertByDataNull() throws IOException {
EthCall lookupDataHex = new EthCall();
Response.Error error = new Response.Error();
error.setCode(3);
error.setData(null);
lookupDataHex.setError(error);
Request request = mock(Request.class);
wh... |
public Direction getNearestDirection()
{
int round = angle >>> 9;
int up = angle & 256;
if (up != 0)
{
// round up
++round;
}
switch (round & 3)
{
case 0:
return SOUTH;
case 1:
return WEST;
case 2:
return NORTH;
case 3:
return EAST;
default:
throw new IllegalState... | @Test
public void getNearestDirection()
{
Angle angle = new Angle(512 + 10);
assertEquals(WEST, angle.getNearestDirection());
angle = new Angle(512 + 256 + 1);
assertEquals(NORTH, angle.getNearestDirection());
} |
@Override
public void close() throws UnavailableException {
// JournalContext is closed before block deletion context so that file system master changes
// are written before block master changes. If a failure occurs between deleting an inode and
// remove its blocks, it's better to have an orphaned block... | @Test
public void throwTwoUnavailableExceptions() throws Throwable {
Exception bdcException = new UnavailableException("block deletion context exception");
Exception jcException = new UnavailableException("journal context exception");
doThrow(bdcException).when(mMockBDC).close();
doThrow(jcException).... |
@Override
public DnsServerAddressStream nameServerAddressStream(String hostname) {
for (;;) {
int i = hostname.indexOf('.', 1);
if (i < 0 || i == hostname.length() - 1) {
return defaultNameServerAddresses.stream();
}
DnsServerAddresses address... | @Test
public void emptyEtcResolverDirectoryDoesNotThrow(@TempDir Path tempDir) throws IOException {
File f = buildFile(tempDir, "domain linecorp.local\n" +
"nameserver 127.0.0.2\n" +
"nameserver 127.0.0.3\n");
UnixResolverDnsServerAddressStreamPr... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void fabricWarnings() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/fabric_warnings.txt")),
CrashReportAnalyzer.Rule.FABRIC_WARNINGS);
assertEquals((" - Conflicting versions found for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.