focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static <T> Set<T> findMissing(Set<T> toFind, Set<T> toSearch) {
Set<T> ret = new LinkedHashSet<>();
for (T toFindItem: toFind) {
if (!toSearch.contains(toFindItem)) {
ret.add(toFindItem);
}
}
return ret;
} | @Test
public void testFindMissing() {
TopicPartition foo0 = new TopicPartition("foo", 0);
TopicPartition foo1 = new TopicPartition("foo", 1);
TopicPartition bar0 = new TopicPartition("bar", 0);
TopicPartition bar1 = new TopicPartition("bar", 1);
TopicPartition baz0 = new Topi... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void retryOnResultUsingSingle() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.of("testName", config);
... |
public static byte[] zlib(String content, String charset, int level) {
return zlib(StrUtil.bytes(content, charset), level);
} | @Test
public void zlibTest() {
final String data = "我是一个需要压缩的很长很长的字符串";
final byte[] bytes = StrUtil.utf8Bytes(data);
byte[] gzip = ZipUtil.zlib(bytes, 0);
//保证zlib长度正常
assertEquals(62, gzip.length);
final byte[] unGzip = ZipUtil.unZlib(gzip);
//保证正常还原
assertEquals(data, StrUtil.utf8Str(unGzip));
g... |
@Override
public boolean archive(String fileName, byte[] data) {
checkArgument(!Strings.isNullOrEmpty(fileName));
checkNotNull(data);
try {
logger.atInfo().log("Archiving data to file system with filename '%s'.", fileName);
Files.asByteSink(new File(fileName)).write(data);
return true;
... | @Test
public void archive_whenValidTargetFileAndByteArrayData_archivesGivenDataWithGivenName()
throws IOException {
File tempFile = temporaryFolder.newFile();
byte[] data = newPreFilledByteArray(200);
RawFileArchiver rawFileArchiver = new RawFileArchiver();
assertThat(rawFileArchiver.archive(t... |
@Override
public long getDictDataCountByDictType(String dictType) {
return dictDataMapper.selectCountByDictType(dictType);
} | @Test
public void testGetDictDataCountByDictType() {
// mock 数据
dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai")));
dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("tudou")));
dictDataMapper.insert(randomDictDataDO(o -> o.setDictType("yunai")));
//... |
@Override
public String resolve(Method method, Object[] arguments, String spelExpression) {
if (StringUtils.isEmpty(spelExpression)) {
return spelExpression;
}
if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) {
return stringValueReso... | @Test
public void placeholderSpelTest2() throws Exception {
String testExpression = "${property:default}";
DefaultSpelResolverTest target = new DefaultSpelResolverTest();
Method testMethod = target.getClass().getMethod("testMethod", String.class);
String result = sut.resolve(testMe... |
@Override
public void close() {
close(Duration.ofMillis(DEFAULT_CLOSE_TIMEOUT_MS));
} | @Test
public void testVerifyApplicationEventOnShutdown() {
consumer = newConsumer();
completeUnsubscribeApplicationEventSuccessfully();
doReturn(null).when(applicationEventHandler).addAndGet(any());
consumer.close();
verify(applicationEventHandler).add(any(UnsubscribeEvent.cl... |
@Override
public AuthenticationToken authenticate(HttpServletRequest request,
final HttpServletResponse response)
throws IOException, AuthenticationException {
// If the request servlet path is in the whitelist,
// skip Kerberos authentication and return anonymous token.
final String path = r... | @Test
public void testRequestWithInvalidAuthorization() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
.thenReturn(... |
public static Builder builder(String bucket, String testClassName, Credentials credentials) {
checkArgument(!bucket.equals(""));
checkArgument(!testClassName.equals(""));
return new Builder(bucket, testClassName, credentials);
} | @Test
public void testBuilderWithEmptyTestClassName() {
assertThrows(
IllegalArgumentException.class, () -> GcsResourceManager.builder(BUCKET, "", null).build());
} |
public TopicList getAllTopicList() {
TopicList topicList = new TopicList();
try {
this.lock.readLock().lockInterruptibly();
topicList.getTopicList().addAll(this.topicQueueTable.keySet());
} catch (Exception e) {
log.error("getAllTopicList Exception", e);
... | @Test
public void testGetAllTopicList() {
byte[] topicInfo = routeInfoManager.getAllTopicList().encode();
Assert.assertTrue(topicInfo != null);
assertThat(topicInfo).isNotNull();
} |
public void createOrUpdate(final String key, final String value, final CreateMode mode) {
String val = StringUtils.isEmpty(value) ? "" : value;
try {
client.create().orSetData().creatingParentsIfNeeded().withMode(mode).forPath(key, val.getBytes(StandardCharsets.UTF_8));
} catch (Exce... | @Test
void createOrUpdate() throws Exception {
assertThrows(ShenyuException.class, () ->
client.createOrUpdate("/test", "hello", CreateMode.PERSISTENT));
CreateBuilder createBuilder = mock(CreateBuilder.class);
when(curatorFramework.create()).thenReturn(createBuilder);
... |
public MatchIterator getEqualOrdinals(int fromOrdinal) {
int hashCode = HashCodes.hashInt(fromOrdinal);
int bucket = hashCode & (fromOrdinalsMap.length - 1);
while(fromOrdinalsMap[bucket] != -1L) {
if((int)fromOrdinalsMap[bucket] == fromOrdinal) {
if((fromOrdinalsMa... | @Test
public void testFromOrdinals() {
assertMatchIterator(map.getEqualOrdinals(1), 1, 2, 3);
assertMatchIterator(map.getEqualOrdinals(2), 4, 5, 6);
assertMatchIterator(map.getEqualOrdinals(3), 7, 8, 9);
assertMatchIterator(map.getEqualOrdinals(100), 5025);
assertMatchIterato... |
@Override
public String toString() {
return "ChildEipStatistic{" +
"id='" + id + '\'' +
", eipStatisticMap=" + eipStatisticMap +
'}';
} | @Test
public void testToString() {
String toString = getInstance().toString();
assertNotNull(toString);
assertTrue(toString.contains("ChildEipStatistic"));
} |
@Override
public void validTenant(Long id) {
TenantDO tenant = getTenant(id);
if (tenant == null) {
throw exception(TENANT_NOT_EXISTS);
}
if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
throw exception(TENANT_DISABLE, tenant.getName());
... | @Test
public void testValidTenant_notExists() {
assertServiceException(() -> tenantService.validTenant(randomLongId()), TENANT_NOT_EXISTS);
} |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final P4PipelineModel other = (P4PipelineModel) obj;
return Objects.equals(this.tables, other.tab... | @Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(P4_PIPELINE_MODEL_1, SAME_AS_P4_PIPELINE_MODEL_1)
.addEqualityGroup(P4_PIPELINE_MODEL_2)
.addEqualityGroup(P4_PIPELINE_MODEL_3)
.addEqualityGroup(P4_PIPELINE_MODEL_4)
... |
@Override
public Image getImageResponseFromBody(String responseBody) {
return new ImageDeserializer().fromJSON(responseBody);
} | @Test
public void shouldDeserializeImageFromJson() throws Exception {
com.thoughtworks.go.plugin.domain.common.Image image = new ArtifactMessageConverterV2().getImageResponseFromBody("{\"content_type\":\"foo\", \"data\":\"bar\"}");
assertThat(image.getContentType(), is("foo"));
assertThat(im... |
public static long findAndVerifyWindowGrace(final GraphNode graphNode) {
return findAndVerifyWindowGrace(graphNode, "");
} | @Test
public void shouldExtractGraceFromKStreamSessionWindowAggregateNode() {
final SessionWindows windows = SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1234L));
final StatefulProcessorNode<String, Long> node = new StatefulProcessorNode<>(
"asdf",
new Proc... |
public static byte[] getByteArraySlice(byte[] array, int begin, int end) {
byte[] slice = new byte[end - begin + 1];
System.arraycopy(array, begin, slice, 0, slice.length);
return slice;
} | @Test
public void testGetByteArraySlice() throws Exception {
assertArrayEquals(new byte[]{1, 2},
JOrphanUtils.getByteArraySlice(new byte[]{0, 1, 2, 3}, 1, 2));
} |
@Override
public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src,
DeviceId dst) {
checkNotNull(src, DEVICE_ID_NULL);
checkNotNull(dst, DEVICE_ID_NULL);
return defaultTopology(topology).getDisjointPaths(src, dst);
} | @Test
public void testGetDisjointPaths() {
VirtualNetwork virtualNetwork = setupVirtualNetworkTopology();
TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class);
Topology topology = topologyService.currentTopology();
VirtualDevice srcVirtualDevice... |
@Override
protected void parse(final ProtocolFactory protocols, final Local folder) throws AccessDeniedException {
for(Local f : folder.list().filter(new NullFilter<Local>() {
@Override
public boolean accept(Local file) {
if(file.isFile()) {
return... | @Test
public void testParse() throws AccessDeniedException {
Transmit5BookmarkCollection c = new Transmit5BookmarkCollection();
assertEquals(0, c.size());
c.parse(new ProtocolFactory(new HashSet<>(Collections.singletonList(new TestProtocol(Scheme.sftp)))), new Local("src/test/resources/"));
... |
public static boolean isNumber(CharSequence value) {
return NumberUtil.isNumber(value);
} | @Test
public void isNumberTest() {
assertTrue(Validator.isNumber("45345365465"));
assertTrue(Validator.isNumber("0004545435"));
assertTrue(Validator.isNumber("5.222"));
assertTrue(Validator.isNumber("0.33323"));
} |
public String getProperty(String name) {
return getProperty(name, true);
} | @Test
public void testGetProperty() throws Exception {
XMLProperties props = XMLProperties.getNonPersistedInstance(Objects.requireNonNull(getClass().getResourceAsStream("XMLProperties.test01.xml")));
assertEquals("123", props.getProperty("foo.bar"));
assertEquals("456", props.getProperty("fo... |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testEnabledAsyncScheduling() throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
new FSConfigToCSConfigArgumentHandler(conversionOptions, mockValidator);
String[] args = getArgumentsAsArrayWithDefaults("-f",
... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 3) {
onInvalidDataReceived(device, data);
return;
}
final int responseCode = data.getIntValue(Data.FORMAT_UINT8, 0);
final int requestCode = da... | @Test
public void onSCOperationCompleted() {
final MutableData data = new MutableData(new byte[] { 0x10, 0x01, 0x01});
response.onDataReceived(null, data);
assertTrue(success);
assertEquals(0, errorCode);
assertEquals(1, requestCode);
assertNull(locations);
} |
static OkHttpClient prepareOkHttpClient(OkHttpClient okHttpClient, WsRequest wsRequest) {
if (!wsRequest.getTimeOutInMs().isPresent() && !wsRequest.getWriteTimeOutInMs().isPresent()) {
return okHttpClient;
}
OkHttpClient.Builder builder = okHttpClient.newBuilder();
if (wsRequest.getTimeOutInMs().i... | @Test
public void override_timeouts_with_request() {
OkHttpClient client = new OkHttpClient.Builder().build();
WsRequest request = new PostRequest("abc").setWriteTimeOutInMs(123).setTimeOutInMs(234);
client = underTest.prepareOkHttpClient(client, request);
assertThat(client.writeTimeoutMillis()).isEqu... |
@Override
public boolean isRepeatable() {
return httpAsyncRequestProducer.isRepeatable();
} | @Test
public void isRepeatable() {
final HttpAsyncRequestProducer delegate = Mockito.mock(HttpAsyncRequestProducer.class);
final HttpAsyncRequestProducerDecorator decorator = new HttpAsyncRequestProducerDecorator(
delegate, null, null);
decorator.isRepeatable();
Mocki... |
@Override
public int compare(Event a, Event b) {
return eventOrder.compare(a, b);
} | @Test
void verifyTestSourceReadSortedCorrectly() {
assertAll(
() -> assertThat(comparator.compare(testRead, runStarted), greaterThan(EQUAL_TO)),
() -> assertThat(comparator.compare(testRead, testRead), equalTo(EQUAL_TO)),
() -> assertThat(comparator.compare(testRead, test... |
public static Set<SchemaChangeEventType> resolveSchemaEvolutionOptions(
List<String> includedSchemaEvolutionTypes, List<String> excludedSchemaEvolutionTypes) {
List<SchemaChangeEventType> resultTypes = new ArrayList<>();
if (includedSchemaEvolutionTypes.isEmpty()) {
resultTypes.... | @Test
public void testResolveSchemaEvolutionOptions() {
assertThat(
ChangeEventUtils.resolveSchemaEvolutionOptions(
Collections.emptyList(), Collections.emptyList()))
.isEqualTo(
Sets.set(
... |
protected static void validateTimestampColumnType(
final Optional<String> timestampColumnName,
final Schema avroSchema
) {
if (timestampColumnName.isPresent()) {
if (avroSchema.getField(timestampColumnName.get()) == null) {
throw new IllegalArgumentException("The indicated timestamp fiel... | @Test
public void shouldThrowIfTimestampColumnTypeNotLong() throws IOException {
// When
final IllegalArgumentException illegalArgumentException = assertThrows(
IllegalArgumentException.class,
() -> DataGenProducer.validateTimestampColumnType(Optional.of("pageid"), getAvroSchema())
);
... |
@Override
protected List<DavResource> list(final Path directory) throws IOException {
return session.getClient().list(new DAVPathEncoder().encode(directory), 1,
Stream.of(
NextcloudAttributesFinderFeature.OC_FILEID_CUSTOM_NAMESPACE,
... | @Test
public void testList() throws Exception {
final Path home = new DefaultHomeFinderService(session).find();
final Path directory = new DAVDirectoryFeature(session, new NextcloudAttributesFinderFeature(session)).mkdir(new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.... |
@SuppressWarnings("MethodLength")
static void dissectControlRequest(
final ArchiveEventCode eventCode,
final MutableDirectBuffer buffer,
final int offset,
final StringBuilder builder)
{
int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder);
... | @Test
void controlRequestStopRecording()
{
internalEncodeLogHeader(buffer, 0, 32, 64, () -> 5_600_000_000L);
final StopRecordingRequestEncoder requestEncoder = new StopRecordingRequestEncoder();
requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder)
.cont... |
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext ctx) {
log.fine(() -> String.format("retryRequest(exception='%s', executionCount='%d', ctx='%s'",
exception.getClass().getName(), executionCount, ctx));
HttpClientContext... | @Test
void retry_with_fixed_backoff_sleeps_for_expected_durations() {
Sleeper sleeper = mock(Sleeper.class);
Duration startDelay = Duration.ofMillis(500);
Duration maxDelay = Duration.ofSeconds(5);
int maxRetries = 10;
DelayedConnectionLevelRetryHandler handler = DelayedCon... |
public URLNormalizer replaceIPWithDomainName() {
URL u = toURL();
if (!PATTERN_DOMAIN.matcher(u.getHost()).matches()) {
try {
InetAddress addr = InetAddress.getByName(u.getHost());
String host = addr.getHostName();
if (!u.getHost().equalsIgnore... | @Test
public void testReplaceIPWithDomainName() {
s = "http://208.80.154.224/wiki/Main_Page";
t = null;
// System.out.println("Result: " + n(s).replaceIPWithDomainName().toString());
Assert.assertTrue(
n(s).replaceIPWithDomainName().toString().contains("wikimedia"));
... |
@Override
public Optional<ComputationConfig> fetchConfig(String computationId) {
Preconditions.checkArgument(
!computationId.isEmpty(),
"computationId is empty. Cannot fetch computation config without a computationId.");
GetConfigResponse response =
applianceComputationConfigFetcher.f... | @Test
public void testGetComputationConfig_errorOnNoComputationConfig() {
StreamingApplianceComputationConfigFetcher configLoader =
createStreamingApplianceConfigLoader();
when(mockWindmillServer.getConfig(any()))
.thenReturn(Windmill.GetConfigResponse.newBuilder().build());
assertThrows(N... |
@Override
public Acl getPermission(final Path file) throws BackgroundException {
try {
final Acl acl = new Acl();
if(containerService.isContainer(file)) {
final BucketAccessControls controls = session.getClient().bucketAccessControls().list(
co... | @Test
public void testReadBucketAnalayticsAcl() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory));
final GoogleStorageAccessControlListFeature f = new GoogleStorageAccessControlListFeature(session);
final Acl acl = f.getPermission(contai... |
@Override
public Set<NodeHealth> readAll() {
long clusterTime = hzMember.getClusterTime();
long timeout = clusterTime - TIMEOUT_30_SECONDS;
Map<UUID, TimestampedNodeHealth> sqHealthState = readReplicatedMap();
Set<UUID> hzMemberUUIDs = hzMember.getMemberUuids();
Set<NodeHealth> existingNodeHealths... | @Test
public void readAll_logs_message_for_each_timed_out_NodeHealth_ignored_if_TRACE() {
logging.setLevel(Level.TRACE);
Map<UUID, TimestampedNodeHealth> map = new HashMap<>();
UUID memberUuid1 = UUID.randomUUID();
UUID memberUuid2 = UUID.randomUUID();
map.put(memberUuid1, new TimestampedNodeHealt... |
public static int appendToLabel(
final AtomicBuffer metaDataBuffer, final int counterId, final String value)
{
Objects.requireNonNull(metaDataBuffer);
if (counterId < 0)
{
throw new IllegalArgumentException("counter id " + counterId + " is negative");
}
f... | @Test
void appendToLabelShouldAddAPortionOfSuffixUpToTheMaxLength()
{
final CountersManager countersManager = new CountersManager(
new UnsafeBuffer(new byte[CountersReader.METADATA_LENGTH]),
new UnsafeBuffer(ByteBuffer.allocateDirect(CountersReader.COUNTER_LENGTH)),
S... |
static <T, V> ThrowingFunction<KV<T, V>, KV<T, String>> createToStringFunctionForPTransform(
String ptransformId, PTransform pTransform) {
return (KV<T, V> input) -> KV.of(input.getKey(), Objects.toString(input.getValue()));
} | @Test
public void testPrimitiveToString() throws Exception {
String pTransformId = "pTransformId";
SdkComponents components = SdkComponents.create();
components.registerEnvironment(Environments.createDockerEnvironment("java"));
RunnerApi.PTransform pTransform = RunnerApi.PTransform.newBuilder().build... |
public static OAuthBearerValidationResult validateClaimForExistenceAndType(OAuthBearerUnsecuredJws jwt,
boolean required, String claimName, Class<?>... allowedTypes) {
Object rawClaim = Objects.requireNonNull(jwt).rawClaim(Objects.requireNonNull(claimName));
if (rawClaim == null)
... | @Test
public void validateClaimForExistenceAndType() throws OAuthBearerIllegalTokenException {
String claimName = "foo";
for (Boolean exists : new Boolean[] {null, Boolean.TRUE, Boolean.FALSE}) {
boolean useErrorValue = exists == null;
for (Boolean required : new boolean[] {t... |
public static <K, InputT> GroupIntoBatches<K, InputT> ofByteSize(long batchSizeBytes) {
return new GroupIntoBatches<K, InputT>(BatchingParams.createDefault())
.withByteSize(batchSizeBytes);
} | @Test
@Category({
ValidatesRunner.class,
NeedsRunner.class,
UsesTimersInParDo.class,
UsesStatefulParDo.class,
UsesOnWindowExpiration.class
})
public void testInGlobalWindowBatchSizeByteSize() {
PCollection<KV<String, Iterable<String>>> collection =
pipeline
.apply("Inpu... |
public Date retryAfter() {
return Optional.ofNullable(retryAfter).map(Date::new).orElse(null);
} | @Test
public void retryAfterTest() {
Date date = retryableException.retryAfter();
Assert.assertNotNull(date);
} |
@IntRange(from = 0)
public int size() {
return buffer.size();
} | @Test
public void size() {
final DataStream stream = new DataStream();
stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6});
assertEquals(7, stream.size());
} |
@Override
public final Set<Entry<K, V>> entrySet() {
return delegate.entrySet();
} | @Test
public void requireThatSingletonEntryImplementsEquals() {
Map.Entry<String, String> map = newSingletonMap("foo", "bar").entrySet().iterator().next();
assertNotEquals(map, null);
assertNotEquals(map, new Object());
assertEquals(map, map);
assertNotEquals(map, newSingleto... |
public static <T extends Type> Type decodeIndexedValue(
String rawInput, TypeReference<T> typeReference) {
return decoder.decodeEventParameter(rawInput, typeReference);
} | @Test
public void testDecodeIndexedBytes16Value() {
String rawInput = "0x1234567890123456789012345678901200000000000000000000000000000000";
byte[] rawInputBytes = Numeric.hexStringToByteArray(rawInput.substring(0, 34));
assertEquals(
FunctionReturnDecoder.decodeIndexedValue(... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testDecodeStaticStructNested() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000001"
+ "000000000000000000000000000000000000000000000000000000000000000a"
+ "0000000000000000000000000000000000... |
public static boolean containsUpperCase(final long word) {
return applyUpperCasePattern(word) != 0;
} | @Test
void containsUpperCaseLong() {
// given
final byte[] asciiTable = getExtendedAsciiTable();
shuffleArray(asciiTable, random);
// when
for (int idx = 0; idx < asciiTable.length; idx += Long.BYTES) {
final long value = getLong(asciiTable, idx);
fin... |
private CompletionStage<RestResponse> pushStateStatus(RestRequest request) {
return statusOperation(request, PUSH_STATE_STATUS);
} | @Test
public void testPushState() {
RestCacheClient cache = getCacheClient(LON);
RestCacheClient backupCache = getCacheClient(NYC);
String key = "key";
String value = "value";
Function<String, Integer> keyOnBackup = k -> responseStatus(backupCache.get(key));
takeBackupOffline(LON... |
public void listenToCluster(String clusterName)
{
// if cluster name is a symlink, watch for D2SymlinkNode instead
String resourceName = D2_CLUSTER_NODE_PREFIX + clusterName;
if (SymlinkUtil.isSymlinkNodeOrPath(clusterName))
{
listenToSymlink(clusterName, resourceName);
}
else
{
... | @Test
public void testListenToNormalCluster()
{
XdsToD2PropertiesAdaptorFixture fixture = new XdsToD2PropertiesAdaptorFixture();
fixture.getSpiedAdaptor().listenToCluster(PRIMARY_CLUSTER_NAME);
verify(fixture._xdsClient).watchXdsResource(eq(PRIMARY_CLUSTER_RESOURCE_NAME), anyNodeWatcher());
verifyC... |
IdBatchAndWaitTime newIdBaseLocal(int batchSize) {
return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize);
} | @Test
public void when_10mIdsInOneBatch_then_wait() {
int batchSize = 10_000_000;
IdBatchAndWaitTime result = gen.newIdBaseLocal(1516028439000L, 1234, batchSize);
assertEquals(batchSize / IDS_PER_SECOND - DEFAULT_ALLOWED_FUTURE_MILLIS, result.waitTimeMillis);
} |
public static byte[] serialize(final Object body) throws IOException {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream);
try {
outputStream.writeObject(body);
... | @Test
public void testSerializationOfString() throws Exception {
String in = "Hello World!";
byte[] expected = PulsarMessageUtils.serialize(in);
assertNotNull(expected);
} |
static InvokerResult convertToResult(Query query, SearchProtocol.SearchReply protobuf,
DocumentDatabase documentDatabase, int partId, int distKey)
{
InvokerResult result = new InvokerResult(query, protobuf.getHitsCount());
result.getResult().setTotalHitCount... | @Test
void testSearchReplyDecodingWithRelevance() {
Query q = new Query("search/?query=test");
InvokerResult result = ProtobufSerialization.convertToResult(q, createSearchReply(5, false), null, 1, 2);
assertEquals(result.getResult().getTotalHitCount(), 7);
List<LeanHit> hits = result... |
protected final AnyKeyboardViewBase getMiniKeyboard() {
return mMiniKeyboard;
} | @Test
public void testShortPressWhenNoPrimaryKeyButTextWithPopupShouldOutputText() throws Exception {
ExternalAnyKeyboard anyKeyboard =
new ExternalAnyKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
keyboard_with_ke... |
@GetMapping("/authenticate")
public ResponseEntity<UsernamePasswordAuthenticationToken> getAuthentication(@RequestParam String token) {
UsernamePasswordAuthenticationToken authentication = tokenService.getAuthentication(token);
return ResponseEntity.ok(authentication);
} | @Test
void givenValidToken_whenGetAuthentication_thenReturnAuthentication() throws Exception {
// Given
String validToken = "validToken";
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("user", "password");
// When
when(toke... |
public void mirrorKeys() {
/* how to mirror?
width = 55
[0..15] [20..35] [40..55]
phase 1: multiple by -1
[0] [-20] [-40]
phase 2: add keyboard width
[55] [35] [15]
phase 3: subtracting the key's width
[40] [20] [0]
cool?
*/
final int keyboardWidth = getMinWidth();
f... | @Test
public void testKeyboardPopupSupportsMirrorOneRowNotFull() throws Exception {
String popupCharacters = "qwe";
AnyPopupKeyboard keyboard =
new AnyPopupKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
popupCh... |
@Override
public InputStream fetch(String fetchKey, Metadata metadata, ParseContext parseContext) throws TikaException, IOException {
LOGGER.debug("about to fetch fetchkey={} from endpoint ({})", fetchKey, endpoint);
try {
BlobClient blobClient = blobClientFactory.getClient(fetchKey);
... | @Test
public void testConfig() throws Exception {
FetcherManager fetcherManager = FetcherManager.load(Paths.get(this
.getClass()
.getResource("/tika-config-az-blob.xml")
.toURI()));
Fetcher fetcher = fetcherManager.getFetcher("az-blob");
List<M... |
public static DataSchema buildSchemaByProjection(DataSchema schema, DataMap maskMap)
{
return buildSchemaByProjection(schema, maskMap, Collections.emptyList());
} | @Test
public void testBuildSchemaByProjectionAllowWhitelistedFields()
{
final String whiteListedFieldName = "$URN";
RecordDataSchema schema = (RecordDataSchema) DataTemplateUtil.getSchema(RecordTemplateWithComplexKey.class);
DataMap projectionMask = buildProjectionMaskDataMap("body", whiteListedFieldNam... |
public String getActualValue() {
return actualValue;
} | @Test
public void getValue_returns_toString_of_Object_passed_in_constructor() {
assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, new A()).getActualValue()).isEqualTo("A string");
} |
@Override
public IntStream intStream() {
return IntStream.of(value);
} | @Test
public void testIntStream() throws Exception {
IntSet sis = new SingletonIntSet(3);
assertEquals(1, sis.intStream().count());
} |
public ConfigCenterBuilder highestPriority(Boolean highestPriority) {
this.highestPriority = highestPriority;
return getThis();
} | @Test
void highestPriority() {
ConfigCenterBuilder builder = ConfigCenterBuilder.newBuilder();
builder.highestPriority(true);
Assertions.assertTrue(builder.build().isHighestPriority());
} |
public boolean handleSentinelResourceReconciliation(CR resource, KubernetesClient client) {
if (!isSentinelResource(resource)) {
return false;
}
ResourceID resourceId = ResourceID.fromResource(resource);
sentinelResources.compute(
resourceId,
(id, previousState) -> {
boo... | @Test
@Order(3)
void testHandleSentinelResourceReconciliation() throws InterruptedException {
// Reduce the SENTINEL_RESOURCE_RECONCILIATION_DELAY time to 0
SparkOperatorConfManager.INSTANCE.refresh(
Collections.singletonMap(
SparkOperatorConf.SENTINEL_RESOURCE_RECONCILIATION_DELAY.getKe... |
public static org.kie.pmml.api.models.MiningField convertToKieMiningField(final MiningField toConvert,
final Field<?> field) {
final String name = toConvert.getName() != null ?toConvert.getName() : null;
final FIELD_USAGE_TYPE... | @Test
void convertToKieMiningField() {
final String fieldName = "fieldName";
final MiningField.UsageType usageType = MiningField.UsageType.ACTIVE;
final MiningField toConvert = getMiningField(fieldName, usageType);
toConvert.setOpType(null);
final DataField dataField = getDat... |
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) {
FunctionConfig mergedConfig = existingConfig.toBuilder().build();
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
... | @Test
public void testMergeDifferentLogTopic() {
FunctionConfig functionConfig = createFunctionConfig();
FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("logTopic", "Different");
FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig... |
public void setOtherBits(Bits bits) {
mOtherBits = bits;
} | @Test
public void setOtherBits() {
Mode mode = new Mode((short) 0000);
mode.setOtherBits(Mode.Bits.READ_EXECUTE);
assertEquals(Mode.Bits.READ_EXECUTE, mode.getOtherBits());
mode.setOtherBits(Mode.Bits.WRITE);
assertEquals(Mode.Bits.WRITE, mode.getOtherBits());
mode.setOtherBits(Mode.Bits.ALL);... |
public Collection<String> getAllShadowTableNames() {
return shadowTableRules.keySet();
} | @Test
void assertGetAllShadowTableNames() {
Collection<String> allShadowTableNames = shadowRule.getAllShadowTableNames();
assertThat(allShadowTableNames.size(), is(2));
Iterator<String> iterator = allShadowTableNames.iterator();
assertThat(iterator.next(), is("t_user"));
asse... |
public static <K, V> Map<K, V> fieldValueAsMap(Iterable<?> iterable, String fieldNameForKey, String fieldNameForValue) {
return IterUtil.fieldValueAsMap(IterUtil.getIter(iterable), fieldNameForKey, fieldNameForValue);
} | @Test
public void fieldValueAsMapTest() {
final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12, DateUtil.parse("2018-05-01")), //
new TestBean("李四", 13, DateUtil.parse("2018-03-01")), //
new TestBean("王五", 14, DateUtil.parse("2018-04-01"))//
);
final Map<String, Integer> map = CollUtil.... |
@Override
public List<ServiceInstance> filter(String serviceName, List<ServiceInstance> serviceInstances) {
return serviceInstances;
} | @Test
public void filter() {
final DefaultServiceInstance instance = new DefaultServiceInstance("localhost", "127.0.0.1", 8080,
Collections.emptyMap(), "zk");
final InstanceFilter nopInstanceFilter = new NopInstanceFilter();
final List<ServiceInstance> defaultServiceInstances... |
public OpenAPI read(Class<?> cls) {
return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
} | @Test(description = "response generic subclass")
public void testTicket3082() {
Reader reader = new Reader(new OpenAPI());
OpenAPI openAPI = reader.read(ProcessTokenRestService.class);
String yaml = "openapi: 3.0.1\n" +
"paths:\n" +
" /token:\n" +
... |
@Override
public long getOffsetInQueueByTime(String topic, int queueId, long timestamp, BoundaryType type) {
FlatMessageFile flatFile = flatFileStore.getFlatFile(new MessageQueue(topic, brokerName, queueId));
if (flatFile == null) {
return -1L;
}
return flatFile.getQueueO... | @Test
public void testGetOffsetInQueueByTime() throws Exception {
this.getMessageFromTieredStoreTest();
mq = dispatcherTest.mq;
messageStore = dispatcherTest.messageStore;
storeConfig = dispatcherTest.storeConfig;
// message time is all 11
Assert.assertEquals(-1L, fe... |
@VisibleForTesting
@Override
List<String> cancelNonTerminalTasks(Workflow workflow) {
List<String> erroredTasks = new ArrayList<>();
// Update non-terminal tasks' status to CANCELED
for (Task task : workflow.getTasks()) {
if (!task.getStatus().isTerminal()) {
// Cancel the ones which are n... | @Test
public void testCancelNonTerminalTasksFailed() {
Task mockTask1 = mock(Task.class);
when(mockTask1.getTaskId()).thenReturn("task-id-1");
when(mockTask1.getTaskType()).thenReturn(Constants.MAESTRO_PREFIX);
when(mockTask1.getStatus()).thenReturn(Task.Status.IN_PROGRESS);
workflow.getTasks().a... |
static boolean allowCIDToUnicodeRange(Map.Entry<Integer, String> prev,
Map.Entry<Integer, String> next)
{
if (prev == null || next == null)
{
return false;
}
return allowCodeRange(prev.getKey(), next.getKey())
&& allowDestinationRange(prev.getV... | @Test
void testAllowCIDToUnicodeRange()
{
Map.Entry<Integer, String> six = new AbstractMap.SimpleEntry<>(0x03FF, "6");
Map.Entry<Integer, String> seven = new AbstractMap.SimpleEntry<>(0x0400,
"7");
Map.Entry<Integer, String> eight = new AbstractMap.SimpleEntry<>(0x0401,
... |
public SessionFactory build(HibernateBundle<?> bundle,
Environment environment,
PooledDataSourceFactory dbConfig,
List<Class<?>> entities) {
return build(bundle, environment, dbConfig, entities, DEFAULT_NAME);
} | @Test
void setsACustomPoolName() {
this.sessionFactory = factory.build(bundle, environment, config,
Collections.singletonList(Person.class), "custom-hibernate-db");
ArgumentCaptor<SessionFactoryManager> sessionFactoryManager = ArgumentCaptor.forClass(SessionFactoryManager.class);
... |
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}... | @Test
public void testCoXKillNoPb()
{
ChatMessage chatMessage = new ChatMessage(null, FRIENDSCHATNOTIFICATION, "", "<col=ef20ff>Congratulations - your raid is complete!</col><br>Team size: <col=ff0000>11-15 players</col> Duration:</col> <col=ff0000>23:25.40</col> Personal best: </col><col=ff0000>20:19.20</col>", nu... |
public void stop() {
try {
sharedHealthState.clearMine();
} catch (HazelcastInstanceNotActiveException | RetryableHazelcastException e) {
LOG.debug("Hazelcast is not active anymore", e);
}
} | @Test
void stop_whenThrowHazelcastInactiveException_shouldSilenceError() {
logging.setLevel(DEBUG);
SharedHealthState sharedHealthStateMock = mock(SharedHealthState.class);
doThrow(HazelcastInstanceNotActiveException.class).when(sharedHealthStateMock).clearMine();
HealthStateRefresher underTest = new ... |
public TopicConsumerConfigurationData getMatchingTopicConfiguration(String topicName) {
return topicConfigurations.stream()
.filter(topicConf -> topicConf.getTopicNameMatcher().matches(topicName))
.findFirst()
.orElseGet(() -> TopicConsumerConfigurationData.ofTopi... | @Test(dataProvider = "topicConf")
public void testTopicConsumerConfigurationData(String topicName, int expectedPriority) {
ConsumerConfigurationData<String> consumerConfigurationData = new ConsumerConfigurationData<>();
consumerConfigurationData.setPriorityLevel(1);
consumerConfigurationDat... |
public static String getFileName(String source) {
return source.contains(File.separator) ?
source.substring(source.lastIndexOf(File.separatorChar) + 1) : source;
} | @Test
void getFileName() {
String fileName = "file_name.txt";
String source = fileName;
assertThat(FileNameUtils.getFileName(source)).isEqualTo(fileName);
source = File.separator + "dir" + File.separator + fileName;
assertThat(FileNameUtils.getFileName(source)).isEqualTo(file... |
public boolean createMetadataTable() {
GCRules.GCRule gcRules = GCRules.GCRULES.maxVersions(1);
if (tableAdminClient.exists(tableId)) {
Table table = tableAdminClient.getTable(tableId);
List<ColumnFamily> currentCFs = table.getColumnFamilies();
ModifyColumnFamiliesRequest request = ModifyColu... | @Test
public void testCreateTableDoesNotExist() {
assertTrue(metadataTableAdminDao.createMetadataTable());
com.google.bigtable.admin.v2.ColumnFamily gcRule =
com.google.bigtable.admin.v2.ColumnFamily.newBuilder()
.setGcRule(GcRule.newBuilder().setMaxNumVersions(1).build())
.bui... |
public String anonymize(final ParseTree tree) {
return build(tree);
} | @Test
public void shouldAnonymizeCreateSourceStreamQueryCorrectly() {
final String output = anon.anonymize(
"CREATE SOURCE STREAM my_stream (profileId VARCHAR, latitude DOUBLE, longitude DOUBLE)\n"
+ "WITH (kafka_topic='locations', value_format='json');");
Approvals.verify(output);
} |
SqlResult execute(CreateMappingPlan plan, SqlSecurityContext ssc) {
catalog.createMapping(plan.mapping(), plan.replace(), plan.ifNotExists(), ssc);
return UpdateSqlResultImpl.createUpdateCountResult(0);
} | @Test
public void test_insertExecution() {
// given
QueryId queryId = QueryId.create(UuidUtil.newSecureUUID());
DmlPlan plan = new DmlPlan(
Operation.INSERT,
planKey(),
QueryParameterMetadata.EMPTY,
emptySet(),
d... |
public static UForLoop create(
Iterable<? extends UStatement> initializer,
@Nullable UExpression condition,
Iterable<? extends UExpressionStatement> update,
UStatement statement) {
return new AutoValue_UForLoop(
ImmutableList.copyOf(initializer),
condition,
ImmutableL... | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(
UForLoop.create(
ImmutableList.of(
UVariableDecl.create("i", UPrimitiveTypeTree.INT, UFreeIdent.create("from"))),
UBinary.create(Kind.LESS_THAN, ULocalVarIdent.create("i"), ... |
public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException {
if ((defaultManagedBean == null && customManagedBean == null) || objectName == null)
return null;
// skip proxy classes
if (defaultManagedBean != null && P... | @Test
public void testInherited() throws JMException {
ModelMBeanInfo beanInfo = mbeanInfoAssembler.getMBeanInfo(new BadInherited(), null, "someName");
assertThat(beanInfo).isNotNull();
assertThat(beanInfo.getAttributes()).hasSize(2);
assertThat(beanInfo.getOperations()).hasSize(3);
... |
@CanIgnoreReturnValue
public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
// TODO(kak): Possible enhancement: Include "[1 copy]" if... | @Test
public void containsAtLeastInOrderFailure() {
ImmutableMultimap<Integer, String> actual =
ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four");
ImmutableMultimap<Integer, String> expected =
ImmutableMultimap.of(4, "four", 3, "six", 3, "two", 3, "one");
assertThat... |
@Override
public GlobalBeginResponseProto convert2Proto(GlobalBeginResponse globalBeginResponse) {
final short typeCode = globalBeginResponse.getTypeCode();
final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType(
MessageTypeProto.forNumber(typeCode... | @Test
public void convert2Proto() {
GlobalBeginResponse globalBeginResponse = new GlobalBeginResponse();
globalBeginResponse.setResultCode(ResultCode.Failed);
globalBeginResponse.setMsg("msg");
globalBeginResponse.setExtraData("extraData");
globalBeginResponse.setXid("xid")... |
@Override
public ValidationResult validate() {
final ValidationResult validationResult = new ValidationResult();
if (searchWithinMs() <= 0) {
validationResult.addError(FIELD_SEARCH_WITHIN_MS,
"Filter & Aggregation search_within_ms must be greater than 0.");
}... | @Test
public void testValidConfiguration() {
final ValidationResult validationResult = getConfig().validate();
assertThat(validationResult.failed()).isFalse();
assertThat(validationResult.getErrors().size()).isEqualTo(0);
} |
public static <K, V> WithKeys<K, V> of(SerializableFunction<V, K> fn) {
checkNotNull(
fn, "WithKeys constructed with null function. Did you mean WithKeys.of((Void) null)?");
return new WithKeys<>(fn, null);
} | @Test
@Category(NeedsRunner.class)
public void testConstantKeys() {
PCollection<String> input =
p.apply(Create.of(Arrays.asList(COLLECTION)).withCoder(StringUtf8Coder.of()));
PCollection<KV<Integer, String>> output = input.apply(WithKeys.of(100));
PAssert.that(output).containsInAnyOrder(WITH_C... |
public static AggregationUnit create(final AggregationType type, final boolean isDistinct) {
switch (type) {
case MAX:
return new ComparableAggregationUnit(false);
case MIN:
return new ComparableAggregationUnit(true);
case SUM:
... | @Test
void assertCreateAverageAggregationUnit() {
assertThat(AggregationUnitFactory.create(AggregationType.AVG, false), instanceOf(AverageAggregationUnit.class));
} |
public Paragraph addNewParagraph(AuthenticationInfo authenticationInfo) {
return insertNewParagraph(paragraphs.size(), authenticationInfo);
} | @Test
void addParagraphWithLastReplNameTest() throws InterpreterNotFoundException {
when(interpreterFactory.getInterpreter(eq("spark"), any())).thenReturn(interpreter);
Note note = new Note("test", "", interpreterFactory, interpreterSettingManager, paragraphJobListener, credentials, noteEventListener, zConf, ... |
public NodeModel commonAncestor() {
return commonAncestor;
} | @Test
public void oneLevelAncestor(){
final NodeModel parent = root();
final NodeModel node1 = new NodeModel("node1", map);
parent.insert(node1);
final NodeModel node2 = new NodeModel("node2", map);
parent.insert(node2);
NodeModel commonAncestor = new NodeRelativePath(node1, node2).commonAncestor();
asse... |
public ShuffleDescriptor getShuffleDescriptor() {
return shuffleDescriptor;
} | @Test
void testSerializationWithNettyShuffleDescriptor() throws IOException {
ShuffleDescriptor shuffleDescriptor =
new NettyShuffleDescriptor(
producerLocation,
new NetworkPartitionConnectionInfo(address, connectionIndex),
... |
@Override
public void close() throws IOException {
zkServiceManager.chooseService().close();
} | @Test
public void close() throws IOException {
zkDiscoveryClient.close();
Mockito.verify(zkService34, Mockito.times(1)).close();
} |
@NonNull
public Client authenticate(@NonNull Request request) {
// https://datatracker.ietf.org/doc/html/rfc7521#section-4.2
try {
if (!CLIENT_ASSERTION_TYPE_PRIVATE_KEY_JWT.equals(request.clientAssertionType())) {
throw new AuthenticationException(
"unsupported client_assertion_ty... | @Test
void authenticate_missingJwtId() throws JOSEException {
var key = generateKey();
var jwkSource = new StaticJwkSource<>(key);
var claims =
new JWTClaimsSet.Builder()
.audience(RP_ISSUER.toString())
.subject("not the right client")
.issuer(CLIENT_ID)
... |
@Override
public int getColumnLength(final Object value) {
throw new UnsupportedSQLOperationException("PostgreSQLInt4ArrayBinaryProtocolValue.getColumnLength()");
} | @Test
void assertGetColumnLength() {
assertThrows(UnsupportedSQLOperationException.class, () -> newInstance().getColumnLength("val"));
} |
protected void setJobProperties(Map<String, String> properties) throws DdlException {
// resource info
if (ConnectContext.get() != null) {
loadMemLimit = ConnectContext.get().getSessionVariable().getLoadMemLimit();
}
if (ConnectContext.get() != null) {
user = Con... | @Test
public void testSetJobPropertiesWithErrorTimeout() {
Map<String, String> jobProperties = Maps.newHashMap();
jobProperties.put(LoadStmt.TIMEOUT_PROPERTY, "abc");
LoadJob loadJob = new BrokerLoadJob();
try {
loadJob.setJobProperties(jobProperties);
Assert.... |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForTableSelect() {
// Given:
final TableSelect<?> step = new TableSelect<>(
PROPERTIES,
tableSource,
ImmutableList.of(),
ImmutableList.of(
add("JUICE", "ORANGE", "APPLE"),
ref("PLANTAIN", "BANANA"),
ref("C... |
@Override
public void validTenant(Long id) {
TenantDO tenant = getTenant(id);
if (tenant == null) {
throw exception(TENANT_NOT_EXISTS);
}
if (tenant.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
throw exception(TENANT_DISABLE, tenant.getName());
... | @Test
public void testValidTenant_expired() {
// mock 数据
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L).setStatus(CommonStatusEnum.ENABLE.getStatus())
.setExpireTime(buildTime(2020, 2, 2)));
tenantMapper.insert(tenant);
// 调用,并断言业务异常
assertServ... |
public V put(final int key, final V value) {
final Entry<V>[] table = this.table;
final int index = HashUtil.indexFor(key, table.length, mask);
for (Entry<V> e = table[index]; e != null; e = e.hashNext) {
if (e.key == key) {
moveToTop(e);
return e.set... | @Test
public void keySet() {
final IntLinkedHashMap<String> tested = new IntLinkedHashMap<>();
for (int i = 0; i < 10000; ++i) {
tested.put(i, Integer.toString(i));
}
int i = 10000;
for (Integer key : tested.keySet()) {
Assert.assertEquals(--i, key.int... |
@Override
public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) {
File[] allFiles = getFiles(configRepoCheckoutDirectory, context);
// if context had changed files list then we could parse only new content
PartialConfig[] allFragments = parseFiles(al... | @Test
public void shouldLoadDirectoryWithTwoPipelineGroupsAndEnvironment() throws Exception {
GoConfigMother mother = new GoConfigMother();
PipelineGroups groups = mother.cruiseConfigWithTwoPipelineGroups().getGroups();
EnvironmentConfig env = EnvironmentConfigMother.environment("dev");
... |
public ClusterStatus appendNewState(ClusterState state) {
return new ClusterStatus(
state,
createUpdatedHistoryWithNewState(state),
previousAttemptSummary,
currentAttemptSummary);
} | @Test
void testAppendNewState() {
ClusterStatus status = new ClusterStatus();
ClusterState newState = new ClusterState(ClusterStateSummary.RunningHealthy, "foo");
ClusterStatus newStatus = status.appendNewState(newState);
assertEquals(2, newStatus.getStateTransitionHistory().size());
assertEquals(... |
public Map<String, String> getParameters() {
return urlParam.getParameters();
} | @Test
void testGetParameters() {
URL url = URL.valueOf(
"10.20.130.230:20880/context/path?interface=org.apache.dubbo.test.interfaceName&group=group&version=1.0.0");
Map<String, String> parameters = url.getParameters(i -> "version".equals(i));
String version = parameters.get("... |
public static NotFoundException itemNotFound(long itemId) {
return new NotFoundException("item not found for itemId:%s",itemId);
} | @Test
public void testItemNotFoundException(){
NotFoundException exception = NotFoundException.itemNotFound(66);
assertEquals(exception.getMessage(), "item not found for itemId:66");
exception = NotFoundException.itemNotFound("test.key");
assertEquals(exception.getMessage(), "item not found for itemK... |
@Override
public ResultSet getExportedKeys(final String catalog, final String schema, final String table) throws SQLException {
return createDatabaseMetaDataResultSet(getDatabaseMetaData().getExportedKeys(getActualCatalog(catalog), getActualSchema(schema), getActualTable(getActualCatalog(catalog), table)));... | @Test
void assertGetExportedKeys() throws SQLException {
when(databaseMetaData.getExportedKeys("test", null, null)).thenReturn(resultSet);
assertThat(shardingSphereDatabaseMetaData.getExportedKeys("test", null, null), instanceOf(DatabaseMetaDataResultSet.class));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.