focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static Result<Boolean> ok() {
return new Result<>(true, null, null);
} | @Test
public void testOk() {
// Test the ok method
Result<Boolean> result = Result.ok();
// Verify that the result is true
assertTrue(result.getResult());
assertNull(result.getErrMsg());
assertNull(result.getErrMsgParams());
} |
public static boolean isClusterController(ServiceCluster cluster) {
return ServiceType.CLUSTER_CONTROLLER.equals(cluster.serviceType());
} | @Test
public void verifyNonControllerClusterIsNotRecognized() {
ServiceCluster cluster = createServiceCluster(new ServiceType("foo"));
assertFalse(VespaModelUtil.isClusterController(cluster));
} |
@SuppressWarnings("unchecked")
public <T> T convert(DocString docString, Type targetType) {
if (DocString.class.equals(targetType)) {
return (T) docString;
}
List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType);
if (d... | @Test
void different_docstring_content_types_convert_to_matching_doc_string_types() {
registry.defineDocStringType(stringForJson);
registry.defineDocStringType(stringForXml);
registry.defineDocStringType(stringForYaml);
DocString docStringJson = DocString.create("{\"content\":\"hello... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseIntegerAsInt32() {
Integer value = Integer.MAX_VALUE;
SchemaAndValue schemaAndValue = Values.parseString(
String.valueOf(value)
);
assertEquals(Schema.INT32_SCHEMA, schemaAndValue.schema());
assertInstanceOf(Integer.class, schemaAndVal... |
void format(NamespaceInfo nsInfo, boolean force) throws IOException {
Preconditions.checkState(nsInfo.getNamespaceID() != 0,
"can't format with uninitialized namespace info: %s",
nsInfo);
LOG.info("Formatting journal id : " + journalId + " with namespace info: " +
nsInfo + " and force: "... | @Test
public void testFormatNonEmptyStorageDirectories() throws Exception {
try {
// Format again here and to format the non-empty directories in
// journal node.
journal.format(FAKE_NSINFO, false);
fail("Did not fail to format non-empty directories in journal node.");
} catch (IOExcep... |
public void sendResponse(Response response) {
Payload convert = GrpcUtils.convert(response);
payloadStreamObserver.onNext(convert);
} | @Test
void testSendResponse() {
connection.sendResponse(new HealthCheckResponse());
verify(payloadStreamObserver).onNext(any(Payload.class));
} |
@JsonIgnore
public Object getField(String key) {
return message.getField(key);
} | @Test
public void testGetField() throws Exception {
assertNull(messageSummary.getField("foo"));
message.addField("foo", "bar");
assertEquals("bar", messageSummary.getField("foo"));
} |
public static <T> T decodeFromByteArray(Coder<T> coder, byte[] encodedValue)
throws CoderException {
return decodeFromByteArray(coder, encodedValue, Coder.Context.OUTER);
} | @Test
public void testClosingCoderFailsWhenDecodingByteArrayInContext() throws Exception {
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Caller does not own the underlying");
CoderUtils.decodeFromByteArray(new ClosingCoder(), new byte[0], Context.NESTED);
... |
@Override
public StorageObject upload(final Path file, Local local, final BandwidthThrottle throttle, final StreamListener listener,
final TransferStatus status, final ConnectionCallback prompt) throws BackgroundException {
if(this.threshold(status)) {
try {
... | @Test
public void testUploadZeroLength() throws Exception {
final S3ThresholdUploadService service = new S3ThresholdUploadService(session, new S3AccessControlListFeature(session), 5 * 1024L);
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.vol... |
@Override
public Map<String, Metric> getMetrics() {
return metricRegistry.getMetrics();
} | @Test
public void shouldReturnTotalNumberOfRequestsAs3ForFail() {
HelloWorldService helloWorldService = mock(HelloWorldService.class);
Retry retry = Retry.of("metrics", RetryConfig.<String>custom()
.retryExceptions(Exception.class)
.maxAttempts(5)
.build());
... |
public SchemaMapping fromParquet(MessageType parquetSchema) {
List<Type> fields = parquetSchema.getFields();
List<TypeMapping> mappings = fromParquet(fields);
List<Field> arrowFields = fields(mappings);
return new SchemaMapping(new Schema(arrowFields), parquetSchema, mappings);
} | @Test
public void testParquetInt32TimeMillisToArrow() {
MessageType parquet = Types.buildMessage()
.addField(Types.optional(INT32)
.as(LogicalTypeAnnotation.timeType(false, MILLIS))
.named("a"))
.named("root");
Schema expected = new Schema(asList(field("a", new ArrowTyp... |
@Override
public void onStreamRequest(StreamRequest req,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
disruptRequest(req, requestContext, wireAttrs, nextFilter);
} | @Test
public void testExecutorRejectExecution() throws Exception
{
final AtomicBoolean success = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
ExecutorService rejectedExecutor = EasyMock.createStrictMock(ExecutorService.class);
rejectedExecutor.execute(EasyMock.anyOb... |
@Override
public boolean tableExists(String dbName, String tblName) {
ConnectorMetadata metadata = metadataOfDb(dbName);
return metadata.tableExists(dbName, tblName);
} | @Test
void testTableExists() {
MockedJDBCMetadata mockedJDBCMetadata = new MockedJDBCMetadata(new HashMap<>());
assertTrue(mockedJDBCMetadata.tableExists("db1", "tbl1"));
} |
@Override
public Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Optional<ResourceNameAndAction> resourceMapping =
requestResourceMapper.getResourceNameAndAction(request);
log.log(Level.FINE, () -> String.format("Resource mapping for '%s': %s", r... | @Test
void accepts_request_with_access_token() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
DiscFilterRequest request = createRequest(null, ACCESS_TOKEN, USER_IDENTITY_CERTIFICATE);
... |
@SuppressWarnings("MethodMayBeStatic")
@Udf(description = "The 2 input points should be specified as (lat, lon) pairs, measured"
+ " in decimal degrees. An optional fifth parameter allows to specify either \"MI\" (miles)"
+ " or \"KM\" (kilometers) as the desired unit for the output measurement. Default i... | @Test
public void shouldFailInvalidUnitOfMeasure() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> distanceUdf.geoDistance(37.4439, -122.1663, 51.5257, -0.1122, "Parsecs")
);
// Then:
assertThat(e.getMessage(), containsString(
"GeoDistance f... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
try {
try {
final HttpHead request = new HttpHead(new DAVPathEncoder().encode(... | @Test
public void testFind() throws Exception {
assertTrue(new DAVFindFeature(session).find(new DefaultHomeFinderService(session).find()));
} |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
for (final Thread.State state : Thread.State.values()) {
gauges.put(name(state.toString().toLowerCase(), "count"),
(Gauge<Object>) () -> getThreadCount(state));
... | @Test
public void hasAGaugeForTotalStartedThreadsCount() {
assertThat(((Gauge<?>) gauges.getMetrics().get("total_started.count")).getValue())
.isEqualTo(42L);
} |
@Override
public void notifyCheckpointComplete(long checkpointId) throws Exception {
super.notifyCheckpointComplete(checkpointId);
sourceReader.notifyCheckpointComplete(checkpointId);
} | @Test
void testNotifyCheckpointComplete() throws Exception {
StateInitializationContext stateContext = context.createStateContext();
operator.initializeState(stateContext);
operator.open();
operator.snapshotState(new StateSnapshotContextSynchronousImpl(100L, 100L));
operator.... |
@Override
protected SSHClient connect(final ProxyFinder proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
final DefaultConfig configuration = new DefaultConfig();
if("zlib".equals(preferences.getProperty("ssh.compression"))) {
... | @Test(expected = LoginCanceledException.class)
public void testConnectNoValidCredentials() throws Exception {
final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch", new Credentials("user", "p")) {
@Override
public String getProperty(final String key) {
if... |
@Override
public void fromPB(EncryptionKeyPB pb, KeyMgr mgr) {
super.fromPB(pb, mgr);
if (pb.algorithm == null) {
throw new IllegalArgumentException("no algorithm in EncryptionKeyPB for NormalKey id:" + id);
}
algorithm = pb.algorithm;
if (pb.plainKey != null) {
... | @Test
public void testFromPB() {
EncryptionKeyPB pb = new EncryptionKeyPB();
pb.id = 12345L;
pb.createTime = System.currentTimeMillis();
pb.algorithm = EncryptionAlgorithmPB.AES_128;
pb.encryptedKey = ((NormalKey) normalKey.generateKey()).getEncryptedKey();
NormalKey... |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = trees.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = b;
for (int i... | @Test
public void testKin8nmLAD() {
test(Loss.lad(), "kin8nm", Kin8nm.formula, Kin8nm.data, 0.1814);
} |
public synchronized File buildPackage(HeliumPackage pkg,
boolean rebuild,
boolean recopyLocalModule) throws IOException {
if (pkg == null) {
return null;
}
String[] moduleNameVersion = getNpmModuleNameAndVersion(pkg);
... | @Test
void switchVersion() throws IOException, TaskRunnerException {
URL res = Resources.getResource("helium/webpack.config.js");
String resDir = new File(res.getFile()).getParent();
HeliumPackage pkgV1 =
newHeliumPackage(
HeliumType.VISUALIZATION,
"zeppelin-bubblechart",
... |
@Override
public SchemaPath getSchemaPath(TopicPath topicPath) throws IOException {
Topic topic = pubsub.projects().topics().get(topicPath.getPath()).execute();
if (topic.getSchemaSettings() == null) {
return null;
}
String schemaPath = topic.getSchemaSettings().getSchema();
if (schemaPath.e... | @Test
public void testGetSchemaPath() throws IOException {
TopicPath topicDoesNotExist =
PubsubClient.topicPathFromPath("projects/testProject/topics/idontexist");
TopicPath topicExistsDeletedSchema =
PubsubClient.topicPathFromPath("projects/testProject/topics/deletedSchema");
TopicPath top... |
@Override
public void subscribe(Collection<String> topics) {
subscribeInternal(topics, Optional.empty());
} | @Test
public void testSubscriptionOnEmptyTopic() {
consumer = newConsumer();
String emptyTopic = " ";
assertThrows(IllegalArgumentException.class, () -> consumer.subscribe(singletonList(emptyTopic)));
} |
@Override
public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) {
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().clear();
response.getHeaders().addAll(cachedResponse.headers());
} | @Test
void headersFromResponseAreDropped() {
SetResponseHeadersAfterCacheExchangeMutator toTest = new SetResponseHeadersAfterCacheExchangeMutator();
inputExchange.getResponse().getHeaders().set("X-Header-1", "Value-original");
CachedResponse cachedResponse = new CachedResponse.Builder(HttpStatus.OK).build();
... |
public static void register(Observer observer) {
register(SubjectType.SPRING_CONTENT_REFRESHED.name(), observer);
} | @Test
public void testSubjectTypeEnumRegister() {
AbstractSubjectCenter.register(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH, subjectNotifyListener);
List<Observer> list = OBSERVERS_MAP.get(AbstractSubjectCenter.SubjectType.THREAD_POOL_DYNAMIC_REFRESH.name());
Assert.assert... |
public static List<String> getPossibleMountPoints(String path) throws InvalidPathException {
String basePath = cleanPath(path);
List<String> paths = new ArrayList<>();
if ((basePath != null) && !basePath.equals(AlluxioURI.SEPARATOR)) {
paths.add(basePath);
String parent = getParent(path);
... | @Test
public void getPossibleMountPointsException() throws InvalidPathException {
mException.expect(InvalidPathException.class);
PathUtils.getPossibleMountPoints("");
} |
public int getNumLocks() {
return mNumLocks;
} | @Test
public void testConstruct() {
create(1023, 128);
assertEquals(128, mLocks.getNumLocks());
create(1023, 127);
assertEquals(128, mLocks.getNumLocks());
create(513, 65);
assertEquals(128, mLocks.getNumLocks());
} |
public VersionMatchResult matches(DeploymentInfo info) {
// Skip if no manifest configuration
if(info.getManifest() == null || info.getManifest().size() == 0) {
return VersionMatchResult.SKIPPED;
}
for (ManifestInfo manifest: info.getManifest()) {
Versio... | @Test
public void testFailedEmptyArtifactInfo() throws IOException {
Set<MavenInfo> maven = new HashSet<MavenInfo>();
ManifestInfo manifest = new ManifestInfo(null);
DeploymentInfo info = new DeploymentInfo(maven, Collections.singleton(manifest));
System.err.println(info);
Pl... |
static COSName mapPNGRenderIntent(int renderIntent)
{
COSName value;
switch (renderIntent)
{
case 0:
value = COSName.PERCEPTUAL;
break;
case 1:
value = COSName.RELATIVE_COLORIMETRIC;
break;
case 2:
value = CO... | @Test
void testMapPNGRenderIntent()
{
assertEquals(COSName.PERCEPTUAL, PNGConverter.mapPNGRenderIntent(0));
assertEquals(COSName.RELATIVE_COLORIMETRIC, PNGConverter.mapPNGRenderIntent(1));
assertEquals(COSName.SATURATION, PNGConverter.mapPNGRenderIntent(2));
assertEquals(COSName.... |
@SuppressWarnings("unused") // Part of required API.
public void execute(
final ConfiguredStatement<InsertValues> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
final InsertValues insertValues = s... | @Test
public void shouldThrowIfNotEnoughValuesSuppliedWithNoSchema() {
// Given:
final ConfiguredStatement<InsertValues> statement = givenInsertValues(
ImmutableList.of(),
ImmutableList.of(
new LongLiteral(1L))
);
// When:
final Exception e = assertThrows(
Ksql... |
@Override
public String toString() {
return toStringHelper(getClass())
.add("version", Byte.toString(version))
.add("headerLength", Byte.toString(headerLength))
.add("diffServ", Byte.toString(diffServ))
.add("totalLength", Short.toString(totalL... | @Test
public void testToStringIPv4() throws Exception {
IPv4 ipv4 = deserializer.deserialize(headerBytes, 0, headerBytes.length);
String str = ipv4.toString();
assertTrue(StringUtils.contains(str, "version=" + VERSION));
assertTrue(StringUtils.contains(str, "headerLength=" + HEADER_... |
@Override
public void contextDestroyed(ServletContextEvent event) {
if (!instanceEnabled) {
return;
}
// nettoyage avant le retrait de la webapp au cas où celui-ci ne suffise pas
SESSION_MAP_BY_ID.clear();
SESSION_COUNT.set(0);
// issue 665: in WildFly 10.1.0, the MonitoringFilter may never be initiali... | @Test
public void testContextDestroyed() {
final ServletContext servletContext = createNiceMock(ServletContext.class);
final ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
replay(servletContext);
sessionListener.sessionCreated(createSessionEvent());
sessionListener.context... |
@Override
public PageResult<DiyPageDO> getDiyPagePage(DiyPagePageReqVO pageReqVO) {
return diyPageMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetDiyPagePage() {
// mock 数据
DiyPageDO dbDiyPage = randomPojo(DiyPageDO.class, o -> { // 等会查询到
o.setName(null);
o.setCreateTime(null);
});
diyPageMapper.insert(dbDiyPage);
/... |
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> edit(Map<K, V> map, Editor<Entry<K, V>> editor) {
if (null == map || null == editor) {
return map;
}
Map<K, V> map2 = ReflectUtil.newInstanceIfPossible(map.getClass());
if (null == map2) {
map2 = new HashMap<>(map.size(), 1f);
}
if (isEmp... | @Test
public void editTest() {
final Map<String, String> map = MapUtil.newHashMap();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
map.put("d", "4");
final Map<String, String> map2 = MapUtil.edit(map, t -> {
// 修改每个值使之*10
t.setValue(t.getValue() + "0");
return t;
});
assertEquals(... |
@Override
public void customize(WebServerFactory server) {
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(server);
} | @Test
void shouldCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
assertThat(container.getMimeMappings().get("abs"))... |
@Override
public boolean equals(Object o) {
if (!(o instanceof OriginName)) {
return false;
}
OriginName that = (OriginName) o;
return Objects.equals(niwsClientName, that.niwsClientName)
&& Objects.equals(target, that.target)
&& Objects.equ... | @Test
void equals() {
OriginName name1 = OriginName.fromVipAndApp("woodly-doodly", "westerndigital");
OriginName name2 = OriginName.fromVipAndApp("woodly-doodly", "westerndigital", "woodly-doodly");
assertEquals(name1, name2);
assertEquals(name1.hashCode(), name2.hashCode());
} |
public synchronized boolean createCollection(String collectionName)
throws MongoDBResourceManagerException {
LOG.info("Creating collection using collectionName '{}'.", collectionName);
try {
// Check to see if the Collection exists
if (collectionExists(collectionName)) {
return false;... | @Test
public void testCreateCollectionShouldThrowErrorWhenCollectionNameIsInvalid() {
assertThrows(
MongoDBResourceManagerException.class, () -> testManager.createCollection("invalid$name"));
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
ctx.tellNext(msg, config.getMessageTypes().contains(msg.getType()) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE);
} | @Test
void givenAttributesUpdated_whenOnMsg_then_False() {
// GIVEN
TbMsg msg = getTbMsg(deviceId, ATTRIBUTES_UPDATED);
// WHEN
node.onMsg(ctx, msg);
// THEN
ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
verify(ctx, times(1)).tel... |
public static void register(final Runnable task)
{
register("INT", task);
} | @Test
void throwsNullPointerExceptionIfRunnableIsNull()
{
assertThrowsExactly(NullPointerException.class, () -> SigInt.register(null));
} |
static BlockStmt getDerivedFieldVariableDeclaration(final String variableName, final DerivedField derivedField) {
final MethodDeclaration methodDeclaration =
DERIVED_FIELD_TEMPLATE.getMethodsByName(GETKIEPMMLDERIVEDFIELD).get(0).clone();
final BlockStmt derivedFieldBody =
... | @Test
void getDerivedFieldVariableDeclarationWithApply() throws IOException {
final String variableName = "variableName";
Constant constant = new Constant();
constant.setValue(value1);
FieldRef fieldRef = new FieldRef();
fieldRef.setField("FIELD_REF");
Apply apply = n... |
@Override
public DeleteAclsResult deleteAcls(Collection<AclBindingFilter> filters, DeleteAclsOptions options) {
final long now = time.milliseconds();
final Map<AclBindingFilter, KafkaFutureImpl<FilterResults>> futures = new HashMap<>();
final List<AclBindingFilter> aclBindingFiltersSent = ne... | @Test
public void testDeleteAcls() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
// Test a call where one filter has an error.
env.kafkaClient().prepareResponse(new DeleteAclsRespon... |
public Flowable<V> takeElements() {
return ElementsStream.takeElements(queue::takeAsync);
} | @Test
public void testTakeElements() throws InterruptedException {
RBlockingQueueRx<Integer> queue = redisson.getBlockingQueue("test");
List<Integer> elements = new ArrayList<>();
queue.takeElements().subscribe(new Subscriber<Integer>() {
@Override
public void onSubs... |
@Override
public void deleteUser(String username) {
String sql = "DELETE FROM users WHERE username=?";
try {
jt.update(sql, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
throw e;
... | @Test
void testDeleteUser() {
externalUserPersistService.deleteUser("username");
String sql = "DELETE FROM users WHERE username=?";
Mockito.verify(jdbcTemplate).update(sql, "username");
} |
public static HttpResponseStatus parseLine(CharSequence line) {
return (line instanceof AsciiString) ? parseLine((AsciiString) line) : parseLine(line.toString());
} | @Test
public void parseLineStringJustCode() {
assertSame(HttpResponseStatus.OK, parseLine("200"));
} |
@Override
protected List<SegmentConversionResult> convert(PinotTaskConfig pinotTaskConfig, List<File> segmentDirs,
File workingDir)
throws Exception {
int numInputSegments = segmentDirs.size();
_eventObserver.notifyProgress(pinotTaskConfig, "Converting segments: " + numInputSegments);
String t... | @Test
public void testTimeFormatSDF()
throws Exception {
FileUtils.deleteQuietly(WORKING_DIR);
RealtimeToOfflineSegmentsTaskExecutor realtimeToOfflineSegmentsTaskExecutor =
new RealtimeToOfflineSegmentsTaskExecutor(null, null);
realtimeToOfflineSegmentsTaskExecutor.setMinionEventObserver(n... |
public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException {
UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream)));
return parser.parse();
} | @Test
public void testParseIssue104() throws IOException {
UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(
UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_parsing_issue104.diff"));
assertThat(diff.getFiles().size()).isEqualTo(6);
final UnifiedDiffFile f... |
public Entry getChild(int index) {
return childEntries.get(index);
} | @Test
public void getsChildrenWithNoIndices() {
Entry top = entryWithName("top");
assertThat(top.getChild(), equalTo(top));
} |
public static Row toBeamRow(GenericRecord record, Schema schema, ConversionOptions options) {
List<Object> valuesInOrder =
schema.getFields().stream()
.map(
field -> {
try {
org.apache.avro.Schema.Field avroField =
rec... | @Test
public void testToBeamRow_row() {
Row beamRow = BigQueryUtils.toBeamRow(ROW_TYPE, BQ_ROW_ROW);
assertEquals(ROW_ROW, beamRow);
} |
@Override
public Pixel[] getPixels() {
return pixels;
} | @Test
void testGetPixels() {
try {
var field = FrameBuffer.class.getDeclaredField("pixels");
var pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
Arrays.fill(pixels, Pixel.WHITE);
pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer();
field.setAccessible(true)... |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldThrowIfCanNotCoerceToInt() {
// Given:
final KsqlJsonDeserializer<Integer> deserializer =
givenDeserializerForSchema(Schema.OPTIONAL_INT32_SCHEMA, Integer.class);
final byte[] bytes = serializeJson(BooleanNode.valueOf(true));
// When:
final Exception e = assertTh... |
@SuppressWarnings("JdkObsolete")
void runNonGui(String testFile, String logFile, boolean remoteStart, String remoteHostsString, boolean generateReportDashboard)
throws ConfigurationException {
try {
File f = new File(testFile);
if (!f.exists() || !f.isFile()) {
... | @Test
void testFailureWhenJmxDoesNotExist() {
JMeter jmeter = new JMeter();
try {
jmeter.runNonGui("testPlan.jmx", null, false, null, false);
Assertions.fail("Expected ConfigurationException to be thrown");
} catch (ConfigurationException e) {
Assertions.a... |
@Override
public UfsFileStatus getFileStatus(String path, GetStatusOptions options) throws IOException {
String tpath = stripPath(path);
File file = new File(tpath);
try {
PosixFileAttributes attr =
Files.readAttributes(Paths.get(file.getPath()), PosixFileAttributes.class);
if (attr.... | @Test
public void getFileStatus() throws IOException {
String file = PathUtils.concatPath(mLocalUfsRoot, getUniqueFileName());
mLocalUfs.create(file).close();
UfsFileStatus s = mLocalUfs.getFileStatus(file);
assertFalse(s.isDirectory());
assertTrue(s.isFile());
} |
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testToArray_withArray() {
queue.toArray(new Integer[0]);
} |
protected static String toString( FilterType filterType ) {
return filterType == null ? null : filterType.toString();
} | @Test
public void testToString_FilterType() {
assertNull( SelectionAdapterOptions.toString( null ) );
assertEquals( "TXT", SelectionAdapterOptions.toString( FilterType.TXT ) );
} |
public static void populateRackInfoForReplicationFactorChange(Map<Short, Set<String>> topicsByReplicationFactor,
Cluster cluster,
boolean skipTopicRackAwarenessCheck,
... | @Test
public void testPopulateRackInfoForReplicationFactorChange() {
Map<String, List<Integer>> brokersByRack = new HashMap<>();
Map<Integer, String> rackByBroker = new HashMap<>();
// Expected: RuntimeException if replication factor (RF) is more than the number of brokers.
assertThrows(RuntimeExcepti... |
@Override
public void fetchAll(final DiscoveryHandlerDTO discoveryHandlerDTO, final ProxySelectorDTO proxySelectorDTO) {
List<DiscoveryUpstreamDO> discoveryUpstreamDOS = discoveryUpstreamMapper.selectByDiscoveryHandlerId(discoveryHandlerDTO.getId());
DiscoverySyncData discoverySyncData = new Discove... | @Test
public void testFetchAll() {
List<DiscoveryUpstreamDO> discoveryUpstreamDOS = new ArrayList<>();
DiscoveryHandlerDTO discoveryHandlerDTO = new DiscoveryHandlerDTO();
ProxySelectorDTO proxySelectorDTO = new ProxySelectorDTO();
when(discoveryUpstreamMapper.selectByDiscoveryHandle... |
@Override
public void write(int b) throws IOException {
dataOut.write(b);
} | @Test
public void testWriteB() throws Exception {
dataOutputStream.write(1);
verify(mockOutputStream).write(1);
} |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testFetchWithUnknownLeaderEpoch() {
buildDependencies();
assignAndSeek(topicAPartition0);
// Try to data and validate that we get an empty Fetch back.
CompletedFetch completedFetch = completedFetchBuilder
.error(Errors.UNKNOWN_LEADER_EPOCH)
... |
@Override
public RegisterApplicationMasterResponse registerApplicationMaster(
RegisterApplicationMasterRequest request) throws YarnException,
IOException {
this.metrics.incrRequestCount();
long startTime = clock.getTime();
try {
RequestInterceptorChainWrapper pipeline =
authori... | @Test
public void testRegisterMultipleApplicationMasters() throws Exception {
for (int testAppId = 0; testAppId < 3; testAppId++) {
RegisterApplicationMasterResponse response = registerApplicationMaster(testAppId);
Assert.assertNotNull(response);
Assert.assertEquals(Integer.toString(testAppId), ... |
@Override
protected TableRecords getUndoRows() {
return super.getUndoRows();
} | @Test
public void getUndoRows() {
Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage());
} |
public static SimpleTransform mul(double operand) {
return new SimpleTransform(Operation.mul,operand);
} | @Test
public void testMul() {
TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.mul(-2)),new HashMap<>());
testSimple(t,(double a) -> a * -2);
} |
public static <T> Optional<T> quietlyEval(String action,
String path,
CallableRaisingIOE<T> operation) {
try {
return Optional.of(once(action, path, operation));
} catch (Exception e) {
LOG.debug("Action {} failed", action, e);
return Optional.empty();
}
} | @Test
public void testQuietlyEvalReturnValueSuccess() {
assertOptionalEquals("quietly", 3,
quietlyEval("", "", () -> 3));
} |
public static <T> T copyProperties(Object source, Class<T> tClass, String... ignoreProperties) {
if (null == source) {
return null;
}
T target = ReflectUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
} | @Test
public void beanWithEnumSetTest() {
final Vto v1 = new Vto();
v1.setVersions(EnumSet.allOf(Version.class));
final Vto v2 = BeanUtil.copyProperties(v1, Vto.class);
assertNotNull(v2);
assertNotNull(v2.getVersions());
} |
@Override
public Object adapt(final HttpAction action, final WebContext context) {
if (action != null) {
var code = action.getCode();
val response = ((JEEContext) context).getNativeResponse();
if (code < 400) {
response.setStatus(code);
} else... | @Test
public void testError500() throws IOException {
JEEHttpActionAdapter.INSTANCE.adapt(new StatusAction(500), context);
verify(response).sendError(500);
} |
public void processOnce() throws IOException {
// set status of query to OK.
ctx.getState().reset();
executor = null;
// reset sequence id of MySQL protocol
final MysqlChannel channel = ctx.getMysqlChannel();
channel.setSequenceId(0);
// read packet from channel
... | @Test
public void testFieldList() throws Exception {
ConnectContext ctx = initMockContext(mockChannel(fieldListPacket), GlobalStateMgr.getCurrentState());
myContext.setDatabase("testDb1");
ConnectProcessor processor = new ConnectProcessor(ctx);
processor.processOnce();
Asser... |
@SuppressWarnings("WeakerAccess")
public Map<String, Object> getGlobalConsumerConfigs(final String clientId) {
final Map<String, Object> baseConsumerProps = getCommonConsumerConfigs();
// Get global consumer override configs
final Map<String, Object> globalConsumerProps = originalsWithPrefi... | @Test
public void testGetGlobalConsumerConfigs() {
final Map<String, Object> returnedProps = streamsConfig.getGlobalConsumerConfigs(clientId);
assertEquals(returnedProps.get(ConsumerConfig.CLIENT_ID_CONFIG), clientId + "-global-consumer");
assertNull(returnedProps.get(ConsumerConfig.GROUP_ID... |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void addNestedMapField() {
Schema nested = Schema.builder().addStringField("field1").build();
Schema schema =
Schema.builder()
.addMapField("map", Schema.FieldType.STRING, Schema.FieldType.row(nested))
.build();
Row subRow = Row.... |
@Override
public void emit(String emitKey, List<Metadata> metadataList, ParseContext parseContext)
throws IOException, TikaEmitterException {
if (metadataList == null || metadataList.size() < 1) {
return;
}
List<EmitData> emitDataList = new ArrayList<>();
emit... | @Test
public void testMultiValuedFields(@TempDir Path tmpDir) throws Exception {
Files.createDirectories(tmpDir.resolve("db"));
Path dbDir = tmpDir.resolve("db/h2");
Path config = tmpDir.resolve("tika-config.xml");
String connectionString = "jdbc:h2:file:" + dbDir.toAbsolutePath();
... |
public void setViaTable(String name, String path, List<Map<String, String>> list) {
name = StringUtils.trimToEmpty(name);
path = StringUtils.trimToNull(path);
if (path == null) {
StringUtils.Pair nameAndPath = parseVariableAndPath(name);
name = nameAndPath.left;
... | @Test
void testSetViaTable() {
Json json = Json.of("[{path: 'bar', value: \"'baz'\" }]");
engine.setViaTable("foo", null, json.asList());
matchEquals("foo", "{ bar: 'baz' }");
json = Json.of("[{path: 'bar', value: 'null' }]"); // has no effect
engine.setViaTable("foo", null, ... |
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) {
GuardedByExpression expr = BINDER.visit(exp, context);
checkGuardedBy(expr != null, String.valueOf(exp));
checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp);
return expr;
} | @Test
public void explicitThisSameClass() {
assertThat(
bind(
"Test",
"Test.this",
forSourceLines(
"threadsafety/Test.java", "package threadsafety;", "class Test {", "}")))
.isEqualTo("(THIS)");
} |
@Override
public DescribeConfigsResult describeConfigs(Collection<ConfigResource> configResources, final DescribeConfigsOptions options) {
// Partition the requested config resources based on which broker they must be sent to with the
// null broker being used for config resources which can be obtai... | @Test
public void testDescribeConsumerGroupConfigs() throws Exception {
ConfigResource resource1 = new ConfigResource(ConfigResource.Type.GROUP, "group1");
ConfigResource resource2 = new ConfigResource(ConfigResource.Type.GROUP, "group2");
try (AdminClientUnitTestEnv env = mockClientEnv()) {... |
@Override
public Page getNextPage()
{
if (closed) {
return null;
}
if (serverResponseIterator == null) {
serverResponseIterator = queryPinot(split);
}
ByteBuffer byteBuffer = null;
try {
// Pinot gRPC server response iterator r... | @Test
public void testPrunedColumns()
{
PinotSessionProperties pinotSessionProperties = new PinotSessionProperties(pinotConfig);
ConnectorSession session = new TestingConnectorSession(pinotSessionProperties.getSessionProperties());
List<DataTable> dataTables = IntStream.range(0, 3).mapTo... |
@Override
public COMMIT3Response commit(XDR xdr, RpcInfo info) {
SecurityHandler securityHandler = getSecurityHandler(info);
RpcCall rpcCall = (RpcCall) info.header();
int xid = rpcCall.getXid();
SocketAddress remoteAddress = info.remoteAddress();
return commit(xdr, info.channel(), xid, securityHa... | @Test(timeout = 60000)
public void testCommit() throws Exception {
HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
long dirId = status.getFileId();
int namenodeId = Nfs3Utils.getNamenodeId(config);
FileHandle handle = new FileHandle(dirId, namenodeId);
XDR xdr_req = new XDR();
... |
static void validateDependencies(Set<Artifact> dependencies, Set<String> allowedRules, boolean failOnUnmatched)
throws EnforcerRuleException {
SortedSet<Artifact> unmatchedArtifacts = new TreeSet<>();
Set<String> matchedRules = new HashSet<>();
for (Artifact dependency : dependencies... | @Test
void fails_on_unmatched_rule() {
Set<Artifact> dependencies = Set.of(
artifact("com.yahoo.vespa", "testutils", "8.0.0", "test"));
Set<String> rules = Set.of(
"com.yahoo.vespa:container-core:jar:*:provided",
"com.yahoo.vespa:*:jar:*:test");
... |
@Override
public ConfigOperateResult insertOrUpdateCas(String srcIp, String srcUser, ConfigInfo configInfo,
Map<String, Object> configAdvanceInfo) {
if (Objects.isNull(
findConfigInfoState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant()))) {
retu... | @Test
void testInsertOrUpdateCasOfInsertConfigSuccess() {
Map<String, Object> configAdvanceInfo = new HashMap<>();
String desc = "testdesc";
String use = "testuse";
String effect = "testeffect";
String type = "testtype";
String schema = "testschema";
... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MutableLong that = (MutableLong) o;
return value == that.value;
} | @Test
public void testEquals() {
assertEquals(MutableLong.valueOf(0), MutableLong.valueOf(0));
assertEquals(MutableLong.valueOf(10), MutableLong.valueOf(10));
assertNotEquals(MutableLong.valueOf(0), MutableLong.valueOf(10));
assertNotEquals(null, MutableLong.valueOf(0));
asse... |
public CreateTableCommand createTableCommand(
final KsqlStructuredDataOutputNode outputNode,
final Optional<RefinementInfo> emitStrategy
) {
Optional<WindowInfo> windowInfo =
outputNode.getKsqlTopic().getKeyFormat().getWindowInfo();
if (windowInfo.isPresent() && emitStrategy.isPresent()) ... | @Test
public void shouldCreateTableCommandWithSingleValueWrappingFromConfig() {
// Given:
ksqlConfig = new KsqlConfig(ImmutableMap.of(
KsqlConfig.KSQL_WRAP_SINGLE_VALUES, false
));
final CreateTable statement =
new CreateTable(SOME_NAME, TABLE_ELEMENTS_1_VALUE,
false, true... |
Session retrieve(String clientID) {
return pool.get(clientID);
} | @Test
public void connectWithCleanSessionUpdateClientSession() throws ExecutionException, InterruptedException {
LOG.info("connectWithCleanSessionUpdateClientSession");
// first connect with clean session true
MqttConnectMessage msg = connMsg.clientId(FAKE_CLIENT_ID).cleanSession(true).build... |
public abstract VoiceInstructionValue getConfigForDistance(
double distance,
String turnDescription,
String thenVoiceInstruction); | @Test
public void initialVICImperialTest() {
InitialVoiceInstructionConfig configImperial = new InitialVoiceInstructionConfig(FOR_HIGHER_DISTANCE_PLURAL.imperial, trMap,
locale, 4250, 250, DistanceUtils.Unit.IMPERIAL);
compareVoiceInstructionValues(
3219,
... |
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 shouldRegisterAvgMetric() {
// Given:
when(metrics.metricName(SENSOR_NAME + "-avg", GROUP_NAME, description(AVG_DESC)))
.thenReturn(specificMetricName);
// When:
FunctionMetrics
.getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME);
// Then:
veri... |
public static long size2Long(String size) {
if (null == size || size.length() <= 1) {
throw new IllegalArgumentException("could not convert '" + size + "' to byte length");
}
String size2Lower = size.toLowerCase();
char unit = size2Lower.charAt(size.length() - 1);
lo... | @Test
void size2Long() {
assertThatThrownBy(() -> SizeUtil.size2Long(null)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> SizeUtil.size2Long("")).isInstanceOf(IllegalArgumentException.class);
// wrong format
assertThatThrownBy(() -> SizeUtil.size2Long("2kk"))... |
public final void isPositiveInfinity() {
isEqualTo(Float.POSITIVE_INFINITY);
} | @Test
public void isPositiveInfinity() {
assertThat(Float.POSITIVE_INFINITY).isPositiveInfinity();
assertThatIsPositiveInfinityFails(1.23f);
assertThatIsPositiveInfinityFails(Float.NEGATIVE_INFINITY);
assertThatIsPositiveInfinityFails(Float.NaN);
assertThatIsPositiveInfinityFails(null);
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
try {
final EueApiClient client = new EueApiClient(session);
final UiFsModel response;
final String resourceId = fileid.getFileId(file);
swi... | @Test
public void testChangeETagPropagatingToRoot() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final EueAttributesFinderFeature feature = new EueAttributesFinderFeature(session, fileid);
final String rootEtag = feature.find(new Path("/", EnumS... |
public void goOnlineFromConsuming(SegmentZKMetadata segmentZKMetadata)
throws InterruptedException {
_serverMetrics.setValueOfTableGauge(_clientId, ServerGauge.LLC_PARTITION_CONSUMING, 0);
try {
// Remove the segment file before we do anything else.
removeSegmentFile();
_leaseExtender.re... | @Test
public void testOnlineTransitionAfterStop()
throws Exception {
SegmentZKMetadata metadata = new SegmentZKMetadata(SEGMENT_NAME_STR);
final long finalOffsetValue = START_OFFSET_VALUE + 600;
final LongMsgOffset finalOffset = new LongMsgOffset(finalOffsetValue);
metadata.setEndOffset(finalOff... |
static List<BigtableResourceManagerCluster> generateDefaultClusters(
String baseString, String zone, int numNodes, StorageType storageType) {
String clusterId =
generateResourceId(
baseString.toLowerCase(),
ILLEGAL_CLUSTER_CHARS,
REPLACE_CLUSTER_CHAR,
M... | @Test
public void testGenerateDefaultClustersShouldThrowErrorWhenTestIdIsEmpty() {
assertThrows(
IllegalArgumentException.class,
() -> generateDefaultClusters("", ZONE, NUM_NODES, STORAGE_TYPE));
} |
@LiteralParameters("x")
@ScalarOperator(LESS_THAN_OR_EQUAL)
@SqlType(StandardTypes.BOOLEAN)
public static boolean lessThanOrEqual(@SqlType("varchar(x)") Slice left, @SqlType("varchar(x)") Slice right)
{
return left.compareTo(right) <= 0;
} | @Test
public void testLessThanOrEqual()
{
assertFunction("'foo' <= 'foo'", BOOLEAN, true);
assertFunction("'foo' <= 'bar'", BOOLEAN, false);
assertFunction("'bar' <= 'foo'", BOOLEAN, true);
assertFunction("'bar' <= 'bar'", BOOLEAN, true);
} |
public ProtocolBuilder heartbeat(Integer heartbeat) {
this.heartbeat = heartbeat;
return getThis();
} | @Test
void heartbeat() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.heartbeat(1000);
Assertions.assertEquals(1000, builder.build().getHeartbeat());
} |
public int getClusterNodeAttributesFailedRetrieved() {
return numGetClusterNodeAttributesFailedRetrieved.value();
} | @Test
public void testGetClusterNodeAttributesRetrievedFailed() {
long totalBadBefore = metrics.getClusterNodeAttributesFailedRetrieved();
badSubCluster.getClusterNodeAttributesFailed();
Assert.assertEquals(totalBadBefore + 1,
metrics.getClusterNodeAttributesFailedRetrieved());
} |
static String trimFieldsAndRemoveEmptyFields(String str) {
char[] chars = str.toCharArray();
char[] res = new char[chars.length];
/*
* set when reading the first non trimmable char after a separator char (or the beginning of the string)
* unset when reading a separator
*/
boolean inField ... | @Test
@UseDataProvider("emptys")
public void trimFieldsAndRemoveEmptyFields_quotes_allow_to_preserve_fields(String empty) {
String quotedEmpty = '"' + empty + '"';
assertThat(trimFieldsAndRemoveEmptyFields(quotedEmpty)).isEqualTo(quotedEmpty);
assertThat(trimFieldsAndRemoveEmptyFields(',' + quotedEmpty... |
public T getOrDefault(final T defaultValue) {
return _delegate.getOrDefault(defaultValue);
} | @Test
public void testGetOrDefaultWithError() {
final Promise<String> delegate = Promises.error(new Exception());
final Promise<String> promise = new DelegatingPromise<String>(delegate);
assertEquals(delegate.getOrDefault("defaultValue"), promise.getOrDefault("defaultValue"));
} |
@Override
public byte[] echo(byte[] message) {
return read(null, ByteArrayCodec.INSTANCE, ECHO, message);
} | @Test
public void testEcho() {
assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes());
} |
protected void ensurePath() throws Exception {
ensureContainers.ensure();
} | @Test
public void testEnsurePath() throws Exception {
Timing timing = new Timing();
CuratorFramework client = CuratorFrameworkFactory.newClient(
server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
client.start();
try {
... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldChooseSpecificOverOnlyVarArgs() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING),
function(OTHER, 0, STRING_VARARGS)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(SqlArgument.of(SqlTypes.STRING)));
// Then:
... |
@VisibleForTesting
static Object convertAvroField(Object avroValue, Schema schema) {
if (avroValue == null) {
return null;
}
switch (schema.getType()) {
case NULL:
case INT:
case LONG:
case DOUBLE:
case FLOAT:
... | @Test
public void testConvertAvroLong() {
Object converted = BaseJdbcAutoSchemaSink.convertAvroField(Long.MIN_VALUE, createFieldAndGetSchema((builder) ->
builder.name("field").type().longType().noDefault()));
Assert.assertEquals(converted, Long.MIN_VALUE);
} |
@Override
public void writeMetrics(MetricQueryResults metricQueryResults) throws Exception {
URL url = new URL(urlString);
String metrics = serializeMetrics(metricQueryResults);
byte[] postData = metrics.getBytes(StandardCharsets.UTF_8);
HttpURLConnection connection = (HttpURLConnection) url.openConne... | @Test
public void testWriteMetricsWithCommittedUnSupported() throws Exception {
MetricQueryResults metricQueryResults = new CustomMetricQueryResults(false);
MetricsOptions pipelineOptions = PipelineOptionsFactory.create().as(MetricsOptions.class);
pipelineOptions.setMetricsHttpSinkUrl(String.format("http:... |
public String getNamespaceId() {
return namespaceId;
} | @Test
void testGetNamespaceId() {
String namespaceId = "aaa";
final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props);
NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, nacosClientProperties);
String actua... |
public void printKsqlEntityList(final List<KsqlEntity> entityList) {
switch (outputFormat) {
case JSON:
printAsJson(entityList);
break;
case TABULAR:
final boolean showStatements = entityList.size() > 1;
for (final KsqlEntity ksqlEntity : entityList) {
writer().... | @Test
public void testPrintPropertyList() {
// Given:
final List<Property> properties = new ArrayList<>();
properties.add(new Property("k1", "KSQL", "1"));
properties.add(new Property("k2", "KSQL", "v2"));
properties.add(new Property("k3", "KSQL", "true"));
final KsqlEntityList entityList = n... |
public static boolean isLimit(String accessKeyID) {
RateLimiter rateLimiter = null;
try {
rateLimiter = CACHE.get(accessKeyID, () -> RateLimiter.create(limit));
} catch (Exception e) {
LOGGER.error("create limit fail", e);
}
if (rateLimiter != null && !rat... | @Test
void testIsLimit() {
String keyId = "a";
//For initiating.
assertFalse(Limiter.isLimit(keyId));
long start = System.currentTimeMillis();
for (int j = 0; j < 5; j++) {
assertFalse(Limiter.isLimit(keyId));
}
long elapse = System.currentTimeMill... |
@Override
public double calcDist3D(double fromLat, double fromLon, double fromHeight,
double toLat, double toLon, double toHeight) {
double eleDelta = hasElevationDiff(fromHeight, toHeight) ? (toHeight - fromHeight) : 0;
double len = calcDist(fromLat, fromLon, toLat, toL... | @Test
public void testDistance3dEarth() {
DistanceCalc distCalc = new DistanceCalcEarth();
assertEquals(1, distCalc.calcDist3D(
0, 0, 0,
0, 0, 1
), 1e-6);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.