focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public long availablePermits() {
return get(availablePermitsAsync());
} | @Test
public void testAvailablePermits() throws InterruptedException {
RRateLimiter rt = redisson.getRateLimiter("rt2");
rt.trySetRate(RateType.OVERALL, 10, 5, RateIntervalUnit.SECONDS);
assertThat(rt.availablePermits()).isEqualTo(10);
rt.acquire(1);
Thread.sleep(6000);
... |
<K, V> List<ConsumerRecord<K, V>> fetchRecords(FetchConfig fetchConfig,
Deserializers<K, V> deserializers,
int maxRecords) {
// Error when fetching the next record before deserialization.
if (corruptLas... | @Test
public void testCommittedTransactionRecordsIncluded() {
int numRecords = 10;
Records rawRecords = newTranscactionalRecords(ControlRecordType.COMMIT, numRecords);
FetchResponseData.PartitionData partitionData = new FetchResponseData.PartitionData()
.setRecords(rawRecords... |
@Override
public URL getApiRoute(String apiRouteBase) throws MalformedURLException {
return new URL(apiRouteBase);
} | @Test
public void testGetApiRoute() throws MalformedURLException {
Assert.assertEquals(
new URL("http://someApiBase/"),
testAuthenticationMethodRetriever.getApiRoute("http://someApiBase/"));
} |
@Operation(summary = "queryDataSource", description = "QUERY_DATA_SOURCE_NOTES")
@Parameters({
@Parameter(name = "id", description = "DATA_SOURCE_ID", required = true, schema = @Schema(implementation = int.class, example = "100"))
})
@GetMapping(value = "/{id}")
@ResponseStatus(HttpStatus.O... | @Disabled("unknown you datasources id")
@Test
public void testQueryDataSource() throws Exception {
MvcResult mvcResult = mockMvc.perform(get("/datasources/2")
.header("sessionId", sessionId))
.andExpect(status().isOk())
.andExpect(content().contentType(Med... |
public static Optional<TableMetaData> load(final DataSource dataSource, final String tableNamePattern, final DatabaseType databaseType) throws SQLException {
DialectDatabaseMetaData dialectDatabaseMetaData = new DatabaseTypeRegistry(databaseType).getDialectDatabaseMetaData();
try (MetaDataLoaderConnecti... | @Test
void assertLoadWithExistedTable() throws SQLException {
Map<String, SchemaMetaData> actual = MetaDataLoader.load(Collections.singleton(new MetaDataLoaderMaterial(Collections.singleton(TEST_TABLE), dataSource, databaseType, "sharding_db")));
TableMetaData tableMetaData = actual.get("sharding_db... |
public MonetaryFormat decimalMark(char decimalMark) {
checkArgument(!Character.isDigit(decimalMark), () ->
"decimalMark can't be digit: " + decimalMark);
checkArgument(decimalMark > 0, () ->
"decimalMark must be positive: " + decimalMark);
if (decimalMark == this.... | @Test
public void testDecimalMark() {
assertEquals("1.00", NO_CODE.format(Coin.COIN).toString());
assertEquals("1,00", NO_CODE.decimalMark(',').format(Coin.COIN).toString());
} |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfStringNegativePrefixLengthIPv4() {
IpPrefix ipPrefix;
ipPrefix = IpPrefix.valueOf("1.2.3.4/-1");
} |
public void convert(FSConfigToCSConfigConverterParams params)
throws Exception {
validateParams(params);
this.clusterResource = getClusterResource(params);
this.convertPlacementRules = params.isConvertPlacementRules();
this.outputDirectory = params.getOutputDirectory();
this.rulesToFile = para... | @Test
public void testInvalidYarnSiteXml() throws Exception {
FSConfigToCSConfigConverterParams params =
createParamsBuilder(YARN_SITE_XML_INVALID)
.withClusterResource(CLUSTER_RESOURCE_STRING)
.build();
expectedException.expect(RuntimeException.class);
converter.convert(params);
... |
@Override
public List<WidgetType> findWidgetTypesByWidgetsBundleId(UUID tenantId, UUID widgetsBundleId) {
return DaoUtil.convertDataList(widgetTypeRepository.findWidgetTypesByWidgetsBundleId(widgetsBundleId));
} | @Test
public void testFindByWidgetsBundleId() {
List<WidgetType> widgetTypes = widgetTypeDao.findWidgetTypesByWidgetsBundleId(TenantId.SYS_TENANT_ID.getId(), widgetsBundle.getUuidId());
assertEquals(WIDGET_TYPE_COUNT, widgetTypes.size());
} |
public static boolean isEqualCollection(final Collection a, final Collection b) {
if (a.size() != b.size()) {
return false;
} else {
Map mapa = getCardinalityMap(a);
Map mapb = getCardinalityMap(b);
if (mapa.size() != mapb.size()) {
return ... | @Test
void testIsEqualCollection() {
List<String> list1 = Arrays.asList("2", "2", "3");
List<String> list2 = Arrays.asList("3", "2", "2");
List<String> list3 = Arrays.asList("3", "2", "3");
List<String> list4 = Arrays.asList("3", "2");
assertTrue(CollectionUtils.isEqualCollec... |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperCli... | @Test(expected = LoadBalancerServiceException.class)
public void require_that_conflict_is_returned_when_creating_load_balancer_fails() throws IOException {
var configserverConfig = new ConfigserverConfig.Builder().hostedVespa(true).build();
MockProvisioner provisioner = new MockProvisioner().transie... |
@Override
public Object merge(T mergingValue, T existingValue) {
if (existingValue == null) {
return null;
}
return existingValue.getRawValue();
} | @Test
public void merge_bothValuesNull() {
MapMergeTypes existing = mergingValueWithGivenValue(null);
MapMergeTypes merging = mergingValueWithGivenValue(null);
assertNull(mergePolicy.merge(merging, existing));
} |
public boolean setLocations(DefaultIssue issue, @Nullable Object locations) {
if (!locationsEqualsIgnoreHashes(locations, issue.getLocations())) {
issue.setLocations(locations);
issue.setChanged(true);
issue.setLocationsChanged(true);
return true;
}
return false;
} | @Test
void change_locations_if_secondary_text_rage_changed() {
DbCommons.TextRange range = DbCommons.TextRange.newBuilder().setStartLine(1).build();
DbIssues.Locations locations = DbIssues.Locations.newBuilder()
.addFlow(DbIssues.Flow.newBuilder()
.addLocation(DbIssues.Location.newBuilder().setT... |
public static Combine.BinaryCombineDoubleFn ofDoubles() {
return new Max.MaxDoubleFn();
} | @Test
public void testMaxDoubleFnInfinity() {
testCombineFn(
Max.ofDoubles(),
Lists.newArrayList(Double.NEGATIVE_INFINITY, 2.0, 3.0, Double.POSITIVE_INFINITY),
Double.POSITIVE_INFINITY);
} |
public static String implode(String[] array, String sepString) {
if (array==null) return null;
StringBuilder ret = new StringBuilder();
if (sepString==null) sepString="";
for (int i = 0 ; i<array.length ; i++) {
ret.append(array[i]);
if (!(i==array.length-1)) ret.... | @Test
public void testImplode() {
assertNull(StringUtilities.implode(null, null));
assertEquals(StringUtilities.implode(new String[0], null), "");
assertEquals(StringUtilities.implode(new String[] {"foo"}, null), "foo");
assertEquals(StringUtilities.implode(new String[] {"foo"}, "asd... |
@Override
public RetrievableStateHandle<T> getAndLock(String pathInZooKeeper) throws Exception {
return get(pathInZooKeeper, true);
} | @Test
void testGetNonExistingPath() {
final TestingLongStateHandleHelper stateHandleProvider = new TestingLongStateHandleHelper();
ZooKeeperStateHandleStore<TestingLongStateHandleHelper.LongStateHandle> store =
new ZooKeeperStateHandleStore<>(getZooKeeperClient(), stateHandleProvide... |
public static String[] getDistinctStrings( String[] strings ) {
if ( strings == null ) {
return null;
}
if ( strings.length == 0 ) {
return new String[] {};
}
String[] sorted = sortStrings( strings );
List<String> result = new ArrayList<>();
String previous = "";
for ( int i... | @Test
public void testGetDistinctStrings() {
assertNull( Const.getDistinctStrings( null ) );
assertTrue( Const.getDistinctStrings( new String[] {} ).length == 0 );
Assert.assertArrayEquals( new String[] { "bar", "foo" }, Const.getDistinctStrings( new String[] { "foo", "bar", "foo",
"bar" } ) );
} |
public Release findLatestActiveRelease(Namespace namespace) {
return findLatestActiveRelease(namespace.getAppId(),
namespace.getClusterName(), namespace.getNamespaceName());
} | @Test
public void testLoadConfigWithConfigNotFound() throws Exception {
String someAppId = "1";
String someClusterName = "someClusterName";
String someNamespaceName = "someNamespaceName";
when(releaseRepository.findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId,
... |
public static String getExactlyExpression(final String value) {
return Strings.isNullOrEmpty(value) ? value : CharMatcher.anyOf(" ").removeFrom(value);
} | @Test
void assertGetExactlyExpressionUsingAndReturningEmptyString() {
assertThat(SQLUtils.getExactlyExpression(""), is(""));
} |
public static String u2(int v) {
char[] result = new char[4];
for (int i = 0; i < 4; i++) {
result[3 - i] = Character.forDigit(v & 0x0f, 16);
v >>= 4;
}
return new String(result);
} | @Test
public void testU2() {
Assert.assertEquals("0000", Hex.u2(0));
Assert.assertEquals("04d2", Hex.u2(1234));
Assert.assertEquals("02d2", Hex.u2(1234567890));
} |
public static ResourceBundle getBundledResource(String basename) {
return ResourceBundle.getBundle(basename, new UTF8Control());
} | @Test
public void getBundleByClassAndName() {
title("getBundleByClassAndName");
res = LionUtils.getBundledResource(LionUtilsTest.class, "SomeResource");
assertNotNull("missing resource bundle", res);
String v1 = res.getString("key1");
String v2 = res.getString("key2");
... |
public int toInt() {
ByteBuffer bb = ByteBuffer.wrap(super.toOctets());
return bb.getInt();
} | @Test
public void testToInt() {
Ip4Address ipAddress;
ipAddress = Ip4Address.valueOf("1.2.3.4");
assertThat(ipAddress.toInt(), is(0x01020304));
ipAddress = Ip4Address.valueOf("0.0.0.0");
assertThat(ipAddress.toInt(), is(0));
ipAddress = Ip4Address.valueOf("255.255.... |
@Override
public <R> List<R> queryMany(String sql, Object[] args, RowMapper<R> mapper) {
return queryMany(jdbcTemplate, sql, args, mapper);
} | @Test
void testQueryMany3() {
String sql = "SELECT data_id FROM config_info WHERE id >= ? AND id <= ?";
Object[] args = new Object[] {1, 2};
String dataId1 = "test1";
String dataId2 = "test2";
List<String> resultList = new ArrayList<>();
resultList.add(dataId1);
... |
@Override
public long getMin() {
if (values.length == 0) {
return 0;
}
return values[0];
} | @Test
public void calculatesAMinOfZeroForAnEmptySnapshot() {
final Snapshot emptySnapshot = new WeightedSnapshot(
weightedArray(new long[]{}, new double[]{}));
assertThat(emptySnapshot.getMin())
.isZero();
} |
public static Builder builder() {
return new Builder();
} | @Test
void fail_when_search_query_length_is_less_than_3_characters() {
assertThatThrownBy(() -> {
PermissionQuery.builder()
.setSearchQuery("so")
.build();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Search query should contains at least 3 characters");
} |
@Override
public ByteBuf writeBytes(byte[] src, int srcIndex, int length) {
ensureWritable(length);
setBytes(writerIndex, src, srcIndex, length);
writerIndex += length;
return this;
} | @Test
public void testWriteBytesAfterRelease2() {
final ByteBuf buffer = copiedBuffer(new byte[8]);
try {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeByte... |
@VisibleForTesting
static boolean hasEnoughCurvature(final int[] xs, final int[] ys, final int middlePointIndex) {
// Calculate the radianValue formed between middlePointIndex, and one point in either
// direction
final int startPointIndex = middlePointIndex - CURVATURE_NEIGHBORHOOD;
final int startX ... | @Test
public void testHasEnoughCurvature15Degrees() {
final int[] Xs = new int[3];
final int[] Ys = new int[3];
// https://www.triangle-calculator.com/?what=&q=A%3D165%2C+b%3D100%2C+c%3D100&submit=Solve
// A[100; 0] B[0; 0] C[196.593; 25.882]
Xs[0] = 0;
Ys[0] = 0;
Xs[1] = 100;
Ys[1]... |
static Optional<File> getOptionalFileFromResource(URL retrieved) {
try {
File toReturn = getFileFromResource(retrieved);
logger.debug(TO_RETURN_TEMPLATE, toReturn);
return Optional.of(toReturn);
} catch (Exception e) {
throw new KieEfestoCommonException("F... | @Test
void getOptionalFileFromResource() {
URL resourceUrl = getResourceUrl();
Optional<File> retrieved = MemoryFileUtils.getOptionalFileFromResource(resourceUrl);
assertThat(retrieved).isNotNull();
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved).get().isIns... |
public String getId(String name) {
// Use the id directly if it is unique and the length is less than max
if (name.length() <= maxHashLength && usedIds.add(name)) {
return name;
}
// Pick the last bytes of hashcode and use hex format
final String hexString = Integer.toHexString(name.hashCode(... | @Test
public void testSameShortNames() {
final HashIdGenerator idGenerator = new HashIdGenerator();
String id = idGenerator.getId("abcd");
Assert.assertEquals("abcd", id);
String id2 = idGenerator.getId("abcd");
Assert.assertNotEquals("abcd", id2);
} |
@Override
public void appendOrOverwriteRegion(int subpartition, T newRegion) throws IOException {
// This method will only be called when we want to eliminate a region. We can't let the
// region be reloaded into the cache, otherwise it will lead to an infinite loop.
long oldRegionOffset = f... | @Test
void testWriteMoreThanOneRegionGroup() throws Exception {
List<TestingFileDataIndexRegion> regions = createTestRegions(0, 0L, 2, 2);
int regionGroupSize =
regions.stream().mapToInt(TestingFileDataIndexRegion::getSize).sum() + 1;
try (FileDataIndexSpilledRegionManager<Te... |
@Override
public int read() throws IOException {
if (mPosition == mLength) { // at end of file
return -1;
}
updateStreamIfNeeded();
int res = mUfsInStream.get().read();
if (res == -1) {
return -1;
}
mPosition++;
Metrics.BYTES_READ_FROM_UFS.inc(1);
return res;
} | @Test
public void readOverflowOffLen() throws IOException, AlluxioException {
// TODO(lu) enable for client cache in the future
Assume.assumeFalse(mConf.getBoolean(PropertyKey.USER_CLIENT_CACHE_ENABLED));
AlluxioURI ufsPath = getUfsPath();
createFile(ufsPath, CHUNK_SIZE);
try (FileInStream inStrea... |
public HttpResult getBinary(String url) throws IOException, NotModifiedException {
return getBinary(url, null, null);
} | @Test
void lastModifiedReturns304() {
this.mockServerClient.when(HttpRequest.request().withMethod("GET").withHeader(HttpHeaders.IF_MODIFIED_SINCE, "123456"))
.respond(HttpResponse.response().withStatusCode(HttpStatus.SC_NOT_MODIFIED));
Assertions.assertThrows(NotModifiedException.class, () -> getter.getBinary... |
@Override
public void prepareContainer(ContainerRuntimeContext ctx)
throws ContainerExecutionException {
@SuppressWarnings("unchecked")
List<String> localDirs =
ctx.getExecutionAttribute(CONTAINER_LOCAL_DIRS);
@SuppressWarnings("unchecked")
Map<org.apache.hadoop.fs.Path, List<String>> r... | @Test
public void testGroupPolicies()
throws IOException, ContainerExecutionException {
// Generate new policy files each containing one grant
File openSocketPolicyFile =
File.createTempFile("openSocket", "policy", baseTestDirectory);
File classLoaderPolicyFile =
File.createTempFile(... |
public CompactedPinotSegmentRecordReader(File indexDir, RoaringBitmap validDocIds) {
this(indexDir, validDocIds, null);
} | @Test
public void testCompactedPinotSegmentRecordReader()
throws Exception {
RoaringBitmap validDocIds = new RoaringBitmap();
for (int i = 0; i < NUM_ROWS; i += 2) {
validDocIds.add(i);
}
List<GenericRow> outputRows = new ArrayList<>();
List<GenericRow> rewoundOuputRows = new ArrayList... |
protected BaseNode parse(String input) {
return input.isEmpty() || input.isBlank() ? getNullNode() : parseNotEmptyInput(input);
} | @Test
void parse_NotEmptyString() {
String input = "";
assertThat(rangeFunction.parse(input))
.withFailMessage(String.format("Check `%s`", input))
.isInstanceOf(NullNode.class);
input = "null";
assertThat(rangeFunction.parse("null"))
.w... |
@Override
public boolean verify(String hostname, SSLSession session) {
if (LOCALHOST_HOSTNAME[0].equalsIgnoreCase(hostname) || LOCALHOST_HOSTNAME[1].equals(hostname)) {
return true;
}
if (isIP(hostname)) {
return true;
}
return hv.verify(hostname, sess... | @Test
void testVerify() {
assertTrue(selfHostnameVerifier.verify("localhost", sslSession));
assertTrue(selfHostnameVerifier.verify("127.0.0.1", sslSession));
assertTrue(selfHostnameVerifier.verify("10.10.10.10", sslSession));
// hit cache
assertTrue(selfHostnameVerifier.verif... |
@Deprecated
@Restricted(DoNotUse.class)
public static String resolve(ConfigurationContext context, String toInterpolate) {
return context.getSecretSourceResolver().resolve(toInterpolate);
} | @Test
public void resolve_mixedSingleEntryWithDefault() {
environment.set("FOO", "www.foo.io");
assertThat(resolve("${protocol:-https}://${FOO:-www.bar.io}"), equalTo("https://www.foo.io"));
} |
public void maybeFlush() {
// We check dirtyTopicId first to avoid having to take the lock unnecessarily in the frequently called log append path
if (dirtyTopicIdOpt.isPresent()) {
// We synchronize on the actual write to disk
synchronized (lock) {
dirtyTopicIdOpt... | @Test
public void testMaybeFlushWithNoTopicIdPresent() {
PartitionMetadataFile partitionMetadataFile = new PartitionMetadataFile(file, null);
partitionMetadataFile.maybeFlush();
assertEquals(0, file.length());
} |
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
IOException {
if ( isJettyMode() && !request.getContextPath().startsWith( CONTEXT_PATH ) ) {
return;
}
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "ExecuteTransServlet.Lo... | @Test
public void doGetMissingMandatoryParamTransTest() throws Exception {
HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class );
HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class );
KettleLogStore.init();
StringWriter out = new StringWriter();
P... |
public static MemberVersion of(int major, int minor, int patch) {
if (major == 0 && minor == 0 && patch == 0) {
return MemberVersion.UNKNOWN;
} else {
return new MemberVersion(major, minor, patch);
}
} | @Test
public void testVersionOf_whenVersionStringIsRC() {
MemberVersion expected = MemberVersion.of(3, 8, 1);
assertEquals(expected, MemberVersion.of(VERSION_3_8_1_RC1_STRING));
} |
File putIfAbsent(String userId, boolean saveToDisk) throws IOException {
String idKey = getIdStrategy().keyFor(userId);
String directoryName = idToDirectoryNameMap.get(idKey);
File directory = null;
if (directoryName == null) {
synchronized (this) {
directoryN... | @Test
public void testDirectoryFormatAllSuppressedCharacters() throws IOException {
UserIdMapper mapper = createUserIdMapper(IdStrategy.CASE_INSENSITIVE);
String user1 = "!@#$%^";
File directory1 = mapper.putIfAbsent(user1, true);
assertThat(directory1.getName(), startsWith("_"));
... |
public int doWork()
{
final long nowNs = nanoClock.nanoTime();
cachedNanoClock.update(nowNs);
dutyCycleTracker.measureAndUpdate(nowNs);
int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT);
final int bytesReceived = dataTransportPolle... | @Test
@InterruptAfter(10)
void shouldCreateRcvTermAndSendSmOnSetup() throws IOException
{
receiverProxy.registerReceiveChannelEndpoint(receiveChannelEndpoint);
receiverProxy.addSubscription(receiveChannelEndpoint, STREAM_ID);
receiver.doWork();
receiver.doWork();
fi... |
public static Path getJobAttemptPath(JobContext context, Path out) {
return getJobAttemptPath(getAppAttemptId(context), out);
} | @Test
public void testJobAbort() throws Exception {
Path jobAttemptPath = jobCommitter.getJobAttemptPath(job);
FileSystem fs = jobAttemptPath.getFileSystem(conf);
Set<String> uploads = runTasks(job, 4, 3);
assertPathExists(fs, "No job attempt path", jobAttemptPath);
jobCommitter.abortJob(job, Jo... |
@Override
public void setConfig(RedisClusterNode node, String param, String value) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_SET, param, value);
syncFuture(f);
} | @Test
public void testSetConfig() {
RedisClusterNode master = getFirstMaster();
connection.setConfig(master, "timeout", "10");
} |
@Override
@SuppressWarnings("unchecked")
public <K, V> List<Map<K, V>> toMaps(DataTable dataTable, Type keyType, Type valueType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(keyType, "keyType may not be null");
requireNonNull(valueType, "valueType may not be n... | @Test
void convert_to_maps_of_optional() {
DataTable table = parse("",
"| header1 | header2 |",
"| 311 | 12299 |");
Map<Optional<String>, Optional<BigInteger>> expectedMap = new HashMap<Optional<String>, Optional<BigInteger>>() {
{
p... |
@Override
public synchronized void execute() {
boolean debugMode = conf.isLoadBalancerDebugModeEnabled() || log.isDebugEnabled();
if (debugMode) {
log.info("Load balancer enabled: {}, Shedding enabled: {}.",
conf.isLoadBalancerEnabled(), conf.isLoadBalancerSheddingEna... | @Test(timeOut = 30 * 1000)
public void testNotChannelOwner() {
AtomicReference<List<Metrics>> reference = new AtomicReference<>();
UnloadCounter counter = new UnloadCounter();
LoadManagerContext context = setupContext();
context.brokerConfiguration().setLoadBalancerEnabled(false);
... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CachedQueryEntry<?, ?> that = (CachedQueryEntry<?, ?>) o;
return keyData.equals(that.keyData);
} | @Test
@SuppressWarnings("ConstantConditions")
public void testEquals_givenOtherIsNull_thenReturnFalse() {
CachedQueryEntry entry1 = createEntry("key");
CachedQueryEntry entry2 = null;
assertFalse(entry1.equals(entry2));
} |
public static synchronized String quantityToStackSize(long quantity)
{
if (quantity < 0)
{
// Long.MIN_VALUE = -1 * Long.MIN_VALUE so we need to correct for it.
return "-" + quantityToStackSize(quantity == Long.MIN_VALUE ? Long.MAX_VALUE : -quantity);
}
else if (quantity < 10_000)
{
return NUMBER_FO... | @Test
public void quantityToStackSize()
{
assertEquals("0", QuantityFormatter.quantityToStackSize(0));
assertEquals("999", QuantityFormatter.quantityToStackSize(999));
assertEquals("1,000", QuantityFormatter.quantityToStackSize(1000));
assertEquals("9,450", QuantityFormatter.quantityToStackSize(9450));
asse... |
public static Builder builder() {
return new Builder();
} | @Test
public void testEqualsAndHashCode() {
WebSocketUpstream upstream1 = WebSocketUpstream.builder().protocol("protocol").upstreamUrl("url")
.status(true).warmup(50).timestamp(1650549243L).build();
WebSocketUpstream upstream2 = WebSocketUpstream.builder().protocol("protocol").upstre... |
@Override
synchronized public void close() {
if (stream != null) {
IOUtils.cleanupWithLogger(LOG, stream);
stream = null;
}
} | @Test(timeout=120000)
public void testRefillReservoir() throws Exception {
OsSecureRandom random = getOsSecureRandom();
for (int i = 0; i < 8196; i++) {
random.nextLong();
}
random.close();
} |
public static long getLastModified(URL resourceURL) {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final... | @Test
void getLastModifiedReturnsZeroIfAnErrorOccurs() throws Exception {
final URL url = new URL("file:/some/path/that/doesnt/exist");
final long lastModified = ResourceURL.getLastModified(url);
assertThat(lastModified)
.isZero();
} |
public static String buildURIFromPattern(String pattern, List<Parameter> parameters) {
if (parameters != null) {
// Browse parameters and choose between template or query one.
for (Parameter parameter : parameters) {
String wadlTemplate = "{" + parameter.getName() + "}";
... | @Test
void testBuildURIFromPatternWithMapWithParamsArray() {
// Prepare a bunch of parameters.
Multimap<String, String> parameters = ArrayListMultimap.create();
parameters.put("year", "2018");
parameters.put("month", "05");
parameters.put("status", "published");
parameters.put("st... |
public XmlStreamInfo information() throws IOException {
if (information.problem != null) {
return information;
}
if (XMLStreamConstants.START_DOCUMENT != reader.getEventType()) {
information.problem = new IllegalStateException("Expected START_DOCUMENT");
retu... | @Test
public void simplestDocument() throws IOException {
String xml = "<root />";
XmlStreamDetector detector
= new XmlStreamDetector(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
XmlStreamInfo info = detector.information();
assertTrue(info.isValid(... |
@Override
public Consumer<Packet> get() {
return responseHandler;
} | @Test
public void get_whenZeroResponseThreads() {
supplier = newSupplier(0);
assertInstanceOf(InboundResponseHandler.class, supplier.get());
} |
@Override
@SuppressWarnings("unchecked")
public O process(I i) throws Exception {
LOG.debug("processing item [{}]...", i);
O result = (O) producerTemplate.requestBody(endpointUri, i);
LOG.debug("processed item");
return result;
} | @Test
public void shouldReturnDoubledMessage() throws Exception {
// When
String messageRead = camelItemProcessor.process(message);
// Then
assertEquals(message + message, messageRead);
} |
@Override
public ByteBuf writeMediumLE(int value) {
ensureWritable0(3);
_setMediumLE(writerIndex, value);
writerIndex += 3;
return this;
} | @Test
public void testWriteMediumLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().writeMediumLE(1);
}
});
} |
public static DumpedPrivateKey fromBase58(@Nullable Network network, String base58)
throws AddressFormatException, AddressFormatException.WrongNetwork {
byte[] versionAndDataBytes = Base58.decodeChecked(base58);
int version = versionAndDataBytes[0] & 0xFF;
byte[] bytes = Arrays.copyO... | @Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBase58_tooShort() {
String base58 = Base58.encodeChecked(NetworkParameters.of(MAINNET).getDumpedPrivateKeyHeader(), new byte[31]);
DumpedPrivateKey.fromBase58((Network) null, base58);
} |
public static StrictFieldProjectionFilter fromSemicolonDelimitedString(String columnsToKeepGlobs) {
return new StrictFieldProjectionFilter(parseSemicolonDelimitedString(columnsToKeepGlobs));
} | @Test
public void testFromSemicolonDelimitedString() {
List<String> globs = StrictFieldProjectionFilter.parseSemicolonDelimitedString(";x.y.z;*.a.b.c*;;foo;;;;bar;");
assertEquals(Arrays.asList("x.y.z", "*.a.b.c*", "foo", "bar"), globs);
try {
StrictFieldProjectionFilter.parseSemicolonDelimitedStri... |
@Transactional
public String login(OauthLoginRequest request) {
OauthInfoApiResponse oauthInfoApiResponse = oauthClient.requestOauthInfo(request);
User user = userRepository.findByEmail(oauthInfoApiResponse.kakao_account().email())
.orElseGet(() -> signUp(oauthInfoApiResponse));
... | @DisplayName("로그인 성공 : 존재하는 회원이면 데이터베이스에 새로운 유저를 추가하지않고 토큰을 바로 반환한다.")
@Test
void login() {
// given
userRepository.save(USER1);
Mockito.when(oauthClient.requestOauthInfo(any(OauthLoginRequest.class)))
.thenReturn(UserFixture.OAUTH_INFO_RESPONSE_USER1);
// when
... |
@Override
public CompletableFuture<Void> close(boolean closeWithoutWaitingClientDisconnect) {
return close(true, closeWithoutWaitingClientDisconnect);
} | @Test
public void testRemoveProducerOnNonPersistentTopic() throws Exception {
final String topicName = "non-persistent://prop/ns-abc/topic_" + UUID.randomUUID();
Producer<byte[]> producer = pulsarClient.newProducer()
.topic(topicName)
.create();
NonPersisten... |
@Override
public void removeInstancePort(String portId) {
checkArgument(!Strings.isNullOrEmpty(portId), ERR_NULL_INSTANCE_PORT_ID);
synchronized (this) {
if (isInstancePortInUse(portId)) {
final String error =
String.format(MSG_INSTANCE_PORT, ... | @Test(expected = IllegalArgumentException.class)
public void testRemoveInstancePortWithNull() {
target.removeInstancePort(null);
} |
@Override
public boolean isEnabled(CeWorker ceWorker) {
return ceWorker.getOrdinal() < ceConfiguration.getWorkerCount();
} | @Test
public void isEnabled_returns_true_if_ordinal_is_invalid() {
int ordinal = -1 - random.nextInt(3);
when(ceWorker.getOrdinal()).thenReturn(ordinal);
assertThat(underTest.isEnabled(ceWorker))
.as("For invalid ordinal " + ordinal + " and workerCount " + randomWorkerCount)
.isTrue();
} |
@VisibleForTesting
int log2Floor(long n) {
checkArgument(n >= 0);
return n == 0 ? -1 : LongMath.log2(n, RoundingMode.FLOOR);
} | @Test
public void testLog2Floor_Positive() {
OrderedCode orderedCode = new OrderedCode();
assertEquals(0, orderedCode.log2Floor(1));
assertEquals(1, orderedCode.log2Floor(2));
assertEquals(1, orderedCode.log2Floor(3));
assertEquals(2, orderedCode.log2Floor(4));
assertEquals(5, orderedCode.log2... |
static String removeWhiteSpaceFromJson(String json) {
//reparse the JSON to ensure that all whitespace formatting is uniform
String flattend = FLAT_GSON.toJson(JsonParser.parseString(json));
return flattend;
} | @Test
public void removeWhiteSpaceFromJson_removesNewLinesAndLeadingSpaceAndMiddleSpace() {
String input = "{\n \"a\": 123,\n \"b\": 456\n}";
String output = "{\"a\":123,\"b\":456}";
assertThat(
removeWhiteSpaceFromJson(input),
is(output)
);
} |
public static void disablePullConsumption(DefaultLitePullConsumerWrapper wrapper, Set<String> topics) {
Set<String> subscribedTopic = wrapper.getSubscribedTopics();
if (subscribedTopic.stream().anyMatch(topics::contains)) {
suspendPullConsumer(wrapper);
return;
}
... | @Test
public void testDisablePullConsumptionWithNoSubTractTopics() {
subscribedTopics = new HashSet<>();
subscribedTopics.add("test-topic-2");
subscribedTopics.add("test-topic-3");
pullConsumerWrapper.setSubscribedTopics(subscribedTopics);
pullConsumerWrapper.setProhibition(t... |
@Override
public long getCreationTime() {
return creationTime;
} | @Test
public void testGetCreationTime() {
assertTrue(queryCacheEventData.getCreationTime() > 0);
} |
@Override
public Alarm save(Alarm alarm, User user) throws ThingsboardException {
ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = alarm.getTenantId();
try {
AlarmApiCallResult result;
if (alarm.getId() == null... | @Test
public void testSave() throws ThingsboardException {
var alarm = new AlarmInfo();
when(alarmSubscriptionService.createAlarm(any())).thenReturn(AlarmApiCallResult.builder()
.successful(true)
.modified(true)
.alarm(alarm)
.build());... |
@Tolerate
public void setChatId(@NonNull Long chatId) {
this.chatId = chatId.toString();
} | @Test
public void chatIdCantBeEmpty() {
SendInvoice sendInvoice = createSendInvoiceObject();
sendInvoice.setChatId("");
Throwable thrown = assertThrows(TelegramApiValidationException.class, sendInvoice::validate);
assertEquals("ChatId parameter can't be empty", thrown.getMessage());
... |
@VisibleForTesting
SmsTemplateDO validateSmsTemplate(String templateCode) {
// 获得短信模板。考虑到效率,从缓存中获取
SmsTemplateDO template = smsTemplateService.getSmsTemplateByCodeFromCache(templateCode);
// 短信模板不存在
if (template == null) {
throw exception(SMS_SEND_TEMPLATE_NOT_EXISTS);
... | @Test
public void testCheckSmsTemplateValid_notExists() {
// 准备参数
String templateCode = randomString();
// mock 方法
// 调用,并断言异常
assertServiceException(() -> smsSendService.validateSmsTemplate(templateCode),
SMS_SEND_TEMPLATE_NOT_EXISTS);
} |
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 shouldParseStringListWithNullFirstAsString() {
String str = "[null, 1]";
SchemaAndValue result = Values.parseString(str);
assertEquals(Type.STRING, result.schema().type());
assertEquals(str, result.value());
} |
public static SetAclPOptions setAclDefaults(AlluxioConfiguration conf) {
return SetAclPOptions.newBuilder()
.setCommonOptions(commonDefaults(conf))
.setRecursive(false)
.build();
} | @Test
public void setAclOptionsDefaults() {
SetAclPOptions options = FileSystemOptionsUtils.setAclDefaults(mConf);
assertNotNull(options);
assertFalse(options.getRecursive());
} |
public static VerificationMode once() {
return times(1);
} | @Test
public void should_verify_form_data() throws Exception {
final HttpServer server = httpServer(port(), hit);
server.post(eq(form("name"), "dreamhead")).response("foobar");
running(server, () -> {
Request request = Request.post(root()).bodyForm(new BasicNameValuePair("name",... |
public boolean equalPathsTo(NodeRelativePath nodeRelativePath2) {
return Arrays.equals(beginPath, nodeRelativePath2.beginPath) && Arrays.equals(endPath, nodeRelativePath2.endPath);
} | @Test
public void equalPaths(){
final NodeModel parent = root();
final NodeModel node1 = new NodeModel("node1", map);
parent.insert(node1);
final NodeModel node2 = new NodeModel("node2", map);
parent.insert(node2);
final NodeRelativePath nodeRelativePath1 = new NodeRelativePath(node1, node2);
final NodeR... |
@Override
public boolean contains(double lat1, double lon1) {
return normDist(lat1, lon1) <= normedDist;
} | @Test
public void testContains() {
Circle c = new Circle(10, 10, 120000);
assertTrue(c.contains(new BBox(9, 11, 10, 10.1)));
assertFalse(c.contains(new BBox(9, 11, 8, 9)));
assertFalse(c.contains(new BBox(9, 12, 10, 10.1)));
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendLocation() {
float lat = 21.999998f, lng = 105.2f, horizontalAccuracy = 1.9f;
int livePeriod = 60, heading = 120, proximityAlertRadius = 50000;
Location location = bot.execute(new SendLocation(chatId, lat, lng)
.horizontalAccuracy(horizontalAccuracy)
... |
@NotNull @Override
public INode enrich(@NotNull INode node) {
if (node instanceof SHA2 sha2) {
return enrich(sha2);
}
return node;
} | @Test
void oid1() {
DetectionLocation testDetectionLocation =
new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "Jca");
final SHA2 sha256 = new SHA2(256, testDetectionLocation);
this.logBefore(sha256);
final SHA2Enricher sha2Enricher = new SHA2Enricher()... |
@GetMapping("/authorize")
@Operation(summary = "获得授权信息", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@Parameter(name = "clientId", required = true, description = "客户端编号", example = "tudou")
public CommonResult<OAuth2OpenAuthorizeInfoRespVO> authorize(@RequestParam("clientId") Str... | @Test
public void testAuthorize() {
// 准备参数
String clientId = randomString();
// mock 方法(client)
OAuth2ClientDO client = randomPojo(OAuth2ClientDO.class).setClientId("demo_client_id").setScopes(ListUtil.toList("read", "write", "all"));
when(oauth2ClientService.validOAuthClien... |
@Override
public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity)
throws Exception {
while (interceptors.hasNext()) {
HttpClientRequestInterceptor nextInterceptor = interceptors.next();
if (nextInterceptor.isIntercept(uri, httpMe... | @Test
void testExecuteIntercepted() throws Exception {
when(interceptor.isIntercept(any(), any(), any())).thenReturn(true);
HttpClientResponse response = clientRequest.execute(URI.create("http://example.com"), "GET",
new RequestHttpEntity(Header.EMPTY, Query.EMPTY));
assertEq... |
@Nullable
public static ValueReference of(Object value) {
if (value instanceof Boolean) {
return of((Boolean) value);
} else if (value instanceof Double) {
return of((Double) value);
} else if (value instanceof Float) {
return of((Float) value);
} ... | @Test
public void deserializeString() throws IOException {
assertThat(objectMapper.readValue("{\"@type\":\"string\",\"@value\":\"\"}", ValueReference.class)).isEqualTo(ValueReference.of(""));
assertThat(objectMapper.readValue("{\"@type\":\"string\",\"@value\":\"Test\"}", ValueReference.class)).isEqu... |
public static EvictionConfig newEvictionConfig(Integer maxSize, MaxSizePolicy maxSizePolicy, EvictionPolicy evictionPolicy,
boolean isNearCache, boolean isIMap, String comparatorClassName,
EvictionPolicyComparator<?, ?... | @Test
public void should_use_default_cache_max_size_for_null_size() {
EvictionConfig evictionConfig = newEvictionConfig(null, false);
assertThat(evictionConfig.getSize()).isEqualTo(EvictionConfig.DEFAULT_MAX_ENTRY_COUNT);
} |
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
return fromVersion == 0 ?
upgradeRuleNodesWithOldPropertyToUseFetchTo(
oldConfiguration,
"fetchToMetadata",
... | @Test
void givenOldConfig_whenUpgrade_thenShouldReturnTrueResultWithNewConfig() throws Exception {
String oldConfig = "{\"fetchToMetadata\":true}";
JsonNode configJson = JacksonUtil.toJsonNode(oldConfig);
TbPair<Boolean, JsonNode> upgrade = node.upgrade(0, configJson);
assertTrue(upg... |
@Override
protected CompletableFuture<JobSubmitResponseBody> handleRequest(
@Nonnull HandlerRequest<JobSubmitRequestBody> request,
@Nonnull DispatcherGateway gateway)
throws RestHandlerException {
final Collection<File> uploadedFiles = request.getUploadedFiles();
... | @TestTemplate
void testFileHandling() throws Exception {
final String dcEntryName = "entry";
CompletableFuture<JobGraph> submittedJobGraphFuture = new CompletableFuture<>();
DispatcherGateway dispatcherGateway =
TestingDispatcherGateway.newBuilder()
.... |
@Nonnull
public static <K, V> BatchSource<Entry<K, V>> map(@Nonnull String mapName) {
return batchFromProcessor("mapSource(" + mapName + ')', readMapP(mapName));
} | @Test
public void mapWithFilterAndProjection_byRef() {
// Given
List<Integer> input = sequence(itemCount);
putToBatchSrcMap(input);
// When
BatchSource<Integer> source = Sources.map(srcMap, truePredicate(), Projections.singleAttribute("value"));
// Then
p.re... |
public static RawPrivateTransaction decode(final String hexTransaction) {
final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction);
final TransactionType transactionType = getPrivateTransactionType(transaction);
if (transactionType == TransactionType.EIP1559) {
return... | @Test
public void testDecodingSignedPrivacyGroup() throws Exception {
final BigInteger nonce = BigInteger.ZERO;
final BigInteger gasPrice = BigInteger.ONE;
final BigInteger gasLimit = BigInteger.TEN;
final String to = "0x0add5355";
final RawPrivateTransaction rawTransaction =... |
@Override
public FindCoordinatorRequest.Builder buildRequest(Set<CoordinatorKey> keys) {
unrepresentableKeys = keys.stream().filter(k -> k == null || !isRepresentableKey(k.idValue)).collect(Collectors.toSet());
Set<CoordinatorKey> representableKeys = keys.stream().filter(k -> k != null && isRepresen... | @Test
public void testBuildLookupRequestNonRepresentable() {
CoordinatorStrategy strategy = new CoordinatorStrategy(CoordinatorType.GROUP, new LogContext());
FindCoordinatorRequest.Builder request = strategy.buildRequest(new HashSet<>(Arrays.asList(
CoordinatorKey.byGroupId("foo"),
... |
@Override
public void unlock(final Path file, final String token) throws BackgroundException {
try {
for(LockFileResultEntry result : new DbxUserFilesRequests(session.getClient(file)).unlockFileBatch(Collections.singletonList(
new UnlockFileArg(containerService.getKey(file)))).ge... | @Test
public void testLockNotfound() throws Exception {
final DropboxTouchFeature touch = new DropboxTouchFeature(session);
final Path file = touch.touch(new Path(new Path(new DefaultHomeFinderService(session).find(), "Projects", EnumSet.of(Path.Type.directory, Path.Type.shared)).withAttributes(new ... |
public static Map<String, Object> entries() {
return CONTEXT_HOLDER.entries();
} | @Test
public void testEntries() {
RootContext.bind(DEFAULT_XID);
Map<String, Object> entries = RootContext.entries();
assertThat(entries.get(RootContext.KEY_XID)).isEqualTo(DEFAULT_XID);
RootContext.unbind();
} |
@Override
public Map<String, Object> create(final T entity, final Class<?> entityClass) {
final Map<String, Object> respEntityContext = this.responseEntityConverter.convertValue(entity, entityClass);
if (respEntityContext != null) {
return Map.of("response_entity", respEntityContext);
... | @Test
void createsProperContext() {
final Map<String, Object> expected = Map.of("response_entity", Map.of(
"tiny_id", "42",
"tiny_title", "Carramba!"
));
DefaultSuccessContextCreator<TinyEntity> toTest = new DefaultSuccessContextCreator<>(new ResponseEntityCo... |
@Override
@SuppressWarnings("unchecked") // compatibility is explicitly checked
public <T> Set<T> convertTo(Class<T> type) {
if (type.isAssignableFrom(getClass())) {
return (Set<T>) Collections.singleton(this);
}
if (type.isAssignableFrom(Dependency.class)) {
retu... | @Test
public void convertTo() {
TestJavaAccess access = javaAccessFrom(importClassWithContext(String.class), "toString")
.to(Object.class, "toString")
.inLineNumber(11);
assertThatConversionOf(access)
.satisfiesStandardConventions()
.i... |
static void maybeReportHybridDiscoveryIssue(PluginDiscoveryMode discoveryMode, PluginScanResult serviceLoadingScanResult, PluginScanResult mergedResult) {
SortedSet<PluginDesc<?>> missingPlugins = new TreeSet<>();
mergedResult.forEach(missingPlugins::add);
serviceLoadingScanResult.forEach(missin... | @Test
public void testHybridFailNoPlugins() {
try (LogCaptureAppender logCaptureAppender = LogCaptureAppender.createAndRegister(Plugins.class)) {
Plugins.maybeReportHybridDiscoveryIssue(PluginDiscoveryMode.HYBRID_FAIL, empty, empty);
assertTrue(logCaptureAppender.getEvents().stream()... |
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId,
@RequestParam("namespaceName") String namespaceName,
@RequestParam(value = "namesp... | @Test
void testCreateNamespaceWithCustomId() throws Exception {
namespaceController.createNamespace("test-Id", "testName", "testDesc");
verify(namespaceOperationService).createNamespace("test-Id", "testName", "testDesc");
} |
public static <T> CheckedSupplier<T> recover(CheckedSupplier<T> supplier,
CheckedFunction<Throwable, T> exceptionHandler) {
return () -> {
try {
return supplier.get();
} catch (Throwable throwable) {
return ... | @Test
public void shouldRecoverFromException() throws Throwable {
CheckedSupplier<String> callable = () -> {
throw new IOException("BAM!");
};
CheckedSupplier<String> callableWithRecovery = CheckedFunctionUtils.recover(callable, (ex) -> "Bla");
String result = callableWi... |
public long cardinality()
{
// The initial guess of 1 may seem awful, but this converges quickly, and starting small returns better results for small cardinalities.
// This generally takes <= 40 iterations, even for cardinalities as large as 10^33.
double guess = 1;
double changeInGu... | @Test
public void testSimulatedCardinalityEstimates()
{
// Instead of creating sketches by adding items, we simulate them for fast testing of huge cardinalities.
// For reference, 10^33 is one decillion.
// The goal here is to test general functionality and numerical stability.
i... |
public static long getNumSector(String requestSize, String sectorSize) {
Double memSize = Double.parseDouble(requestSize);
Double sectorBytes = Double.parseDouble(sectorSize);
Double nSectors = memSize / sectorBytes;
Double memSizeKB = memSize / 1024;
Double memSizeGB = memSize / (1024 * 1024 * 1024... | @Test
public void getSectorTestGB() {
String testRequestSize = "1073741824"; // 1GB
String testSectorSize = "512";
long result = HFSUtils.getNumSector(testRequestSize, testSectorSize);
assertEquals(2128667L, result); // 1GB/512B = 2097152
} |
protected String createPermissionString(ActiveMQDestination dest, String verb) {
if (dest.isComposite()) {
throw new IllegalArgumentException("Use createPermissionStrings for composite destinations.");
}
StringBuilder sb = new StringBuilder();
if (permissionStringPrefix != ... | @Test(expected = IllegalArgumentException.class)
public void testCreatePermissionStringWithCompositeDestination() {
ActiveMQTopic topicA = new ActiveMQTopic("A");
ActiveMQTopic topicB = new ActiveMQTopic("B");
ActiveMQDestination composite = new AnyDestination(new ActiveMQDestination[]{topic... |
@Override
public void destroy() {
super.destroy();
// remove child listener
Set<URL> urls = zkListeners.keySet();
for (URL url : urls) {
ConcurrentMap<NotifyListener, ChildListener> map = zkListeners.get(url);
if (CollectionUtils.isEmptyMap(map)) {
... | @Test
void testDestroy() {
zookeeperRegistry.destroy();
assertThat(zookeeperRegistry.isAvailable(), is(false));
} |
public Schema toKsqlSchema(final Schema schema) {
try {
final Schema rowSchema = toKsqlFieldSchema(schema);
if (rowSchema.type() != Schema.Type.STRUCT) {
throw new KsqlException("KSQL stream/table schema must be structured");
}
if (rowSchema.fields().isEmpty()) {
throw new K... | @Test
public void shouldTranslateTimeTypes() {
final Schema connectSchema = SchemaBuilder
.struct()
.field("timefield", Time.SCHEMA)
.field("datefield", Date.SCHEMA)
.field("timestampfield", Timestamp.SCHEMA)
.build();
final Schema ksqlSchema = translator.toKsqlSchema(... |
@VisibleForTesting
public static String parseErrorMessage( String errorMessage, Date now ) {
StringBuilder parsed = new StringBuilder();
try {
String[] splitString = errorMessage.split( "\\n" );
parsed.append( splitString[1] ).append( "\n" );
for ( int i = 2; i < splitString.length; i++ ) {
... | @Test
public void parseErrorMessageUsingSameDateTest() {
String result = TransPreviewProgressDialog.parseErrorMessage( ERROR_MSG, parseDate( SAME_DATE_STR ) );
assertEquals( FAILED_TO_INIT_MSG + EXPECTED_ERROR_MSG, result );
} |
public abstract String getErrorCodeName(); | @Test
public void testErrorCode()
{
assertEquals(
new ClusterConnectionException(new SocketTimeoutException(), QUERY_STAGE).getErrorCodeName(),
"CLUSTER_CONNECTION(SocketTimeoutException)");
assertEquals(
new PrestoQueryException(new SQLException()... |
@Override
public OpenstackVtapNetwork createVtapNetwork(Mode mode, Integer networkId, IpAddress serverIp) {
checkNotNull(mode, VTAP_DESC_NULL, "mode");
checkNotNull(serverIp, VTAP_DESC_NULL, "serverIp");
DefaultOpenstackVtapNetwork vtapNetwork = DefaultOpenstackVtapNetwork.builder()
... | @Test(expected = NullPointerException.class)
public void testCreateNullVtapNetwork() {
target.createVtapNetwork(null, null, null);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.