focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
protected int compareDataNode(final DatanodeDescriptor a,
final DatanodeDescriptor b, boolean isBalanceLocal) {
boolean toleranceLimit = Math.max(a.getDfsUsedPercent(), b.getDfsUsedPercent())
< balancedSpaceToleranceLimit;
if (a.equals(b)
|| (toleranceLimit && Math.abs(a.getDfsUsedPercent... | @Test
public void testCompareDataNode() {
DatanodeDescriptor[] tolerateDataNodes;
DatanodeStorageInfo[] tolerateStorages;
int capacity = 5;
Collection<Node> allTolerateNodes = new ArrayList<>(capacity);
String[] ownerRackOfTolerateNodes = new String[capacity];
for (int i = 0; i < capacity; i+... |
@Override
public synchronized ScheduleResult schedule()
{
dropListenersFromWhenFinishedOrNewLifespansAdded();
int overallSplitAssignmentCount = 0;
ImmutableSet.Builder<RemoteTask> overallNewTasks = ImmutableSet.builder();
List<ListenableFuture<?>> overallBlockedFutures = new Arr... | @Test
public void testScheduleSplitsOneAtATime()
{
SubPlan plan = createPlan();
NodeTaskMap nodeTaskMap = new NodeTaskMap(finalizerService);
SqlStageExecution stage = createSqlStageExecution(plan, nodeTaskMap);
StageScheduler scheduler = getSourcePartitionedScheduler(createFixed... |
@Override
public FsStateChangelogWriter createWriter(
String operatorID, KeyGroupRange keyGroupRange, MailboxExecutor mailboxExecutor) {
UUID logId = new UUID(0, logIdGenerator.getAndIncrement());
LOG.info("createWriter for operator {}/{}: {}", operatorID, keyGroupRange, logId);
... | @Test
public void testDeadlockOnUploadCompletion() throws Throwable {
int capacity = 10; // in bytes, allow the first two uploads without waiting (see below)
CountDownLatch remainingUploads = new CountDownLatch(3);
BlockingUploader blockingUploader = new BlockingUploader();
Completab... |
public static Options options() {
return new Options("/tmp", 100, SorterType.HADOOP);
} | @Test
public void testNegativeMemory() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("memoryMB must be greater than zero");
BufferedExternalSorter.Options options =
BufferedExternalSorter.options().withTempLocation(getTmpLocation().toString());
options.withMemoryMB(-1);... |
void placeOrder(Order order) {
sendShippingRequest(order);
} | @Test
void testPlaceOrderUnknownException() throws Exception {
long paymentTime = timeLimits.paymentTime();
long queueTaskTime = timeLimits.queueTaskTime();
long messageTime = timeLimits.messageTime();
long employeeTime = timeLimits.employeeTime();
long queueTime = timeLimits.queueTime... |
public boolean includes(String ipAddress) {
if (all) {
return true;
}
if (ipAddress == null) {
throw new IllegalArgumentException("ipAddress is null.");
}
try {
return includes(addressFactory.getByName(ipAddress));
} catch (UnknownHostException e) {
return fals... | @Test
public void testCIDRWith8BitMask() {
//create MachineList with a list of of ip ranges specified in CIDR format
MachineList ml = new MachineList(CIDR_LIST2, new TestAddressFactory());
//test for inclusion/exclusion
assertFalse(ml.includes("10.241.22.255"));
assertTrue(ml.includes("10.241.2... |
public static float bytesToFloatBE(byte[] bytes, int off) {
return Float.intBitsToFloat(bytesToIntBE(bytes, off));
} | @Test
public void testBytesToFloatBE() {
assertEquals((float) Math.PI,
ByteUtils.bytesToFloatBE(FLOAT_PI_BE, 0), 0);
} |
@Override
public void putAll(final List<KeyValue<K, V>> entries) {
entries.forEach(entry -> Objects.requireNonNull(entry.key, "key cannot be null"));
maybeMeasureLatency(() -> wrapped().putAll(innerEntries(entries)), time, putAllSensor);
} | @Test
public void shouldThrowNullPointerOnPutAllIfAnyKeyIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> metered.putAll(Collections.singletonList(KeyValue.pair(null, VALUE))));
} |
String getRole(DecodedJWT jwt) {
try {
Claim roleClaim = jwt.getClaim(this.roleClaim);
if (roleClaim.isNull()) {
// The claim was not present in the JWT
return null;
}
String role = roleClaim.asString();
if (role != nul... | @Test void ensureMissingRoleClaimReturnsNull() throws Exception {
// Build an empty JWT
DefaultJwtBuilder defaultJwtBuilder = new DefaultJwtBuilder();
defaultJwtBuilder.setAudience(basicProviderAudience);
DecodedJWT jwtWithoutSub = JWT.decode(defaultJwtBuilder.compact());
// A J... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void doNotCastNameExprLiterals2() {
final TypedExpression left = expr("exprDouble", java.lang.Double.class);
final TypedExpression right = expr("$age", int.class);
final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, false).coerce();
... |
public static void main(String[] args) {
// Dummy Persons
Person person1 = new Person(1, "John", 27304159);
Person person2 = new Person(2, "Thomas", 42273631);
Person person3 = new Person(3, "Arthur", 27489171);
Person person4 = new Person(4, "Finn", 20499078);
Person person5 = new Person(5, "M... | @Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
} |
void uncaughtExceptionInternal(
final Thread t,
final Throwable e,
final SystemExit systemExit) {
if (t instanceof StreamThread) {
countDownLatch.ifPresent(CountDownLatch::countDown);
return;
}
log.error("Unhandled exception caught in thread {}.", t.getName(), e);
System.er... | @Test
public void shouldNotSystemExitWhenStreamThreadThrowsAnError() throws InterruptedException {
// When
final CountDownLatch latch = new CountDownLatch(1);
KsqlUncaughtExceptionHandler handler = new KsqlUncaughtExceptionHandler(LogManager::shutdown, Optional.of(latch));
handler.uncaughtExceptionInt... |
@Override
public char readChar() {
return (char) readShort();
} | @Test
public void testReadCharAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().readChar();
}
});
} |
public void writeUbyte(int value) throws IOException {
if (value < 0 || value > 0xFF) {
throw new ExceptionWithContext("Unsigned byte value out of range: %d", value);
}
write(value);
} | @Test(expected=ExceptionWithContext.class)
public void testWriteUbyteOutOfBounds2() throws IOException {
writer.writeUbyte(256);
} |
static boolean isWindows0(String osName) {
return osName.toLowerCase().contains("windows");
} | @Test
public void test_isWindows0() {
assertTrue(OS.isWindows0("Windows"));
assertTrue(OS.isWindows0("wInDoWs"));
assertTrue(OS.isWindows0("Windows 10"));
assertTrue(OS.isWindows0("Windows 11"));
assertFalse(OS.isWindows0("LINUX"));
assertFalse(OS.isWindows0("LiNuX"))... |
public static long fromHex(String string) {
return UnsignedLongs.parseUnsignedLong(string, 16);
} | @Test
public void fromHex() throws Exception {
assertEquals(15, Tools.fromHex("0f"));
assertEquals(16, Tools.fromHex("10"));
assertEquals(65535, Tools.fromHex("ffff"));
assertEquals(4096, Tools.fromHex("1000"));
assertEquals(0xffffffffffffffffL, Tools.fromHex("fffffffffffffff... |
@Override
@Transactional(value="defaultTransactionManager")
public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException {
if (Strings.isNullOrEmpty(refreshTokenValue)) {
// throw an invalid token exception if there's no refresh token val... | @Test
public void refreshAccessToken_requestingSameScope() {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
verify(scopeService, atLeastOnce()).removeReservedScopes(anySet());
assertThat(token.getScope(), equalTo(storedScope));
} |
@Override
public void setConfigAttributes(Object attributes) {
clear();
if (attributes == null) {
return;
}
Map attributeMap = (Map) attributes;
String materialType = (String) attributeMap.get(AbstractMaterialConfig.MATERIAL_TYPE);
if (SvnMaterialConfig.TY... | @Test
public void shouldSetGitConfigAttributesForMaterial() {
MaterialConfigs materialConfigs = new MaterialConfigs();
Map<String, String> hashMap = new HashMap<>();
hashMap.put(GitMaterialConfig.URL, "foo");
hashMap.put(GitMaterialConfig.BRANCH, "master");
HashMap<String, ... |
public SelType evaluate(String expr, Map<String, Object> varsMap, Extension ext)
throws Exception {
checkExprLength(expr);
selParser.ReInit(new ByteArrayInputStream(expr.getBytes()));
ASTExecute n = selParser.Execute();
try {
selEvaluator.resetWithInput(varsMap, ext);
return (SelType) ... | @Test(expected = IllegalArgumentException.class)
public void testInvalidEvaluate() throws Exception {
t1.evaluate("Integer.valueOf(new int[1, 2]);", new HashMap<>(), null);
} |
@Override
public String getIdentifier(UserInfo userInfo, ClientDetailsEntity client) {
String sectorIdentifier = null;
if (!Strings.isNullOrEmpty(client.getSectorIdentifierUri())) {
UriComponents uri = UriComponentsBuilder.fromUriString(client.getSectorIdentifierUri()).build();
sectorIdentifier = uri.getHo... | @Test
public void testGetIdentifer_unique() {
String pairwise1 = service.getIdentifier(userInfoRegular, pairwiseClient1);
String pairwise3 = service.getIdentifier(userInfoRegular, pairwiseClient3);
String pairwise4 = service.getIdentifier(userInfoRegular, pairwiseClient4);
// make sure nothing's equal
asser... |
public static void uncheck(RunnableWithExceptions t) {
try {
t.run();
} catch (Exception exception) {
throwAsUnchecked(exception);
}
} | @Test(expected = ClassNotFoundException.class)
public void test_if_correct_exception_is_still_thrown_by_method() {
Class clazz3 = uncheck(Class::forName, "INVALID");
} |
@Override
public SelJodaDateTimeFormatter assignOps(SelOp op, SelType rhs) {
if (op == SelOp.ASSIGN) {
SelTypeUtil.checkTypeMatch(this.type(), rhs.type());
this.val = ((SelJodaDateTimeFormatter) rhs).val; // direct assignment
return this;
}
throw new UnsupportedOperationException(type() ... | @Test
public void testAssignOps() {
one.assignOps(SelOp.ASSIGN, another);
assertEquals(another.getInternalVal(), one.getInternalVal());
} |
public LogoutRequestModel parseLogoutRequest(HttpServletRequest request) throws SamlValidationException, SamlParseException, SamlSessionException, DienstencatalogusException {
final LogoutRequestModel logoutRequestModel = new LogoutRequestModel();
try {
final BaseHttpServletRequestXMLMessa... | @Test
public void parseLogoutRequestWrongVersion() {
httpRequestMock.setParameter("SAMLRequest", "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS... |
@Override
public boolean tryClaim(Timestamp position) {
if (position.equals(lastAttemptedPosition)) {
return true;
}
return super.tryClaim(position);
} | @Test
public void testTryClaim() {
assertEquals(range, tracker.currentRestriction());
assertTrue(tracker.tryClaim(Timestamp.ofTimeMicroseconds(10L)));
assertTrue(tracker.tryClaim(Timestamp.ofTimeMicroseconds(10L)));
assertTrue(tracker.tryClaim(Timestamp.ofTimeMicroseconds(11L)));
assertTrue(tracke... |
public static String getMimeType(Path file) {
try {
return Files.probeContentType(file);
} catch (IOException ignore) {
// issue#3179,使用OpenJDK可能抛出NoSuchFileException,此处返回null
return null;
}
} | @Test
public void issue3179Test() {
final String mimeType = PathUtil.getMimeType(Paths.get("xxxx.jpg"));
assertEquals("image/jpeg", mimeType);
} |
public List<Document> export(final String collectionName,
final List<String> exportedFieldNames,
final int limit,
final Bson dbFilter,
final List<Sort> sorts,
... | @Test
void testExportUsesFilterCorrectly() {
insertTestData();
simulateAdminUser();
final List<Document> exportedDocuments = toTest.export(TEST_COLLECTION_NAME,
List.of("name"),
200,
Filters.gt("age", 40),
List.of(),
... |
public int computeMinVersion() {
int minVersion = Integer.MAX_VALUE;
for (Connection c : this.connectionSet) {
if (c.getVersion() < minVersion) {
minVersion = c.getVersion();
}
}
return minVersion;
} | @Test
public void testComputeMinVersion() {
ConsumerConnection consumerConnection = new ConsumerConnection();
HashSet<Connection> connections = new HashSet<>();
Connection conn1 = new Connection();
conn1.setVersion(1);
connections.add(conn1);
Connection conn2 = new Co... |
@Override
public boolean dropNamespace(Namespace namespace) throws NamespaceNotEmptyException {
namespaceExists(namespace);
GetTablesResponse response =
glue.getTables(
GetTablesRequest.builder()
.catalogId(awsProperties.glueCatalogId())
.databaseName(
... | @Test
public void testDropNamespace() {
Mockito.doReturn(GetTablesResponse.builder().build())
.when(glue)
.getTables(Mockito.any(GetTablesRequest.class));
Mockito.doReturn(
GetDatabaseResponse.builder().database(Database.builder().name("db1").build()).build())
.when(glue)
... |
@Override
public ByteBuf getBytes(int index, byte[] dst) {
getBytes(index, dst, 0, dst.length);
return this;
} | @Test
public void getByteArrayBoundaryCheck1() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.getBytes(-1, EMPTY_BYTES);
}
});
} |
@Override
public boolean tableExists(String dbName, String tableName) {
return delegate.tableExists(dbName, tableName);
} | @Test
public void testTableExists() {
CachingDeltaLakeMetastore cachingDeltaLakeMetastore =
CachingDeltaLakeMetastore.createCatalogLevelInstance(metastore, executor, expireAfterWriteSec,
refreshAfterWriteSec, 100);
Assert.assertTrue(cachingDeltaLakeMetastore.... |
public void remove(PropertyKey key) {
// remove is a nop if the key doesn't already exist
if (mUserProps.containsKey(key)) {
mUserProps.remove(key);
mSources.remove(key);
mHash.markOutdated();
}
} | @Test
public void remove() {
mProperties.remove(mKeyWithValue);
assertEquals(mKeyWithValue.getDefaultValue(), mProperties.get(mKeyWithValue));
assertEquals(Source.DEFAULT, mProperties.getSource(mKeyWithValue));
} |
@Override
public boolean syncVerifyData(DistroData verifyData, String targetServer) {
if (isNoExistTarget(targetServer)) {
return true;
}
// replace target server as self server so that can callback.
verifyData.getDistroKey().setTargetServer(memberManager.getSelf().getAdd... | @Test
void testSyncVerifyDataWithCallbackForMemberUnhealthy() throws NacosException {
DistroData verifyData = new DistroData();
verifyData.setDistroKey(new DistroKey());
when(memberManager.hasMember(member.getAddress())).thenReturn(true);
when(memberManager.find(member.getAddress()))... |
public Properties getProperties()
{
return properties;
} | @Test
public void testUriWithSslEnabled()
throws SQLException
{
PrestoDriverUri parameters = createDriverUri("presto://localhost:8080/blackhole?SSL=true");
assertUriPortScheme(parameters, 8080, "https");
Properties properties = parameters.getProperties();
assertNull(... |
@Override
public SSLContext getIdentitySslContext() {
return sslContext;
} | @Test
void constructs_ssl_context_with_pem_trust_store() throws IOException {
File keyFile = File.createTempFile("junit", null, tempDirectory);
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
createPrivateKeyFile(keyFile, keypair);
X509Certificate certificate = createC... |
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 testKeyboardPopupSupportsMirrorMultipleFullRows() throws Exception {
String popupCharacters = "qwertasdfg";
// asdfg
// qwert
AnyPopupKeyboard keyboard =
new AnyPopupKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getAppli... |
public MergePolicyConfig setBatchSize(int batchSize) {
this.batchSize = checkPositive("batchSize", batchSize);
return this;
} | @Test
public void setBatchSize() {
config.setBatchSize(1234);
assertEquals(1234, config.getBatchSize());
} |
@Override
public boolean sendElectionMessage(int currentId, String content) {
var nextInstance = this.findNextInstance(currentId);
var electionMessage = new Message(MessageType.ELECTION, content);
nextInstance.onMessage(electionMessage);
return true;
} | @Test
void testSendElectionMessage() {
try {
var instance1 = new RingInstance(null, 1, 1);
var instance2 = new RingInstance(null, 1, 2);
var instance3 = new RingInstance(null, 1, 3);
Map<Integer, Instance> instanceMap = Map.of(1, instance1, 2, instance2, 3, instance3);
var messageMan... |
public static String toMultiCrcString(final byte[] bytes) {
if (bytes.length % 4 != 0) {
throw new IllegalArgumentException((String.format(
"Unexpected byte[] length '%d' not divisible by 4. Contents: %s",
bytes.length, Arrays.toString(bytes))));
}
StringBuilder sb = new StringBuil... | @Test
public void testToMultiCrcStringBadLength()
throws Exception {
LambdaTestUtils.intercept(
IllegalArgumentException.class,
"length",
() -> CrcUtil.toMultiCrcString(new byte[6]));
} |
@Override
public void executeUpdate(final ImportMetaDataStatement sqlStatement, final ContextManager contextManager) throws SQLException {
String jsonMetaDataConfig;
if (sqlStatement.getFilePath().isPresent()) {
File file = new File(sqlStatement.getFilePath().get());
try {
... | @Test
void assertImportEmptyMetaData() {
init(null);
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
assertThrows(EmptyStorageUnitException.class, () -> executor.executeUpdate(
new ImportMetaDataStatement(null, Objects.requireNonNull(ImportMeta... |
@VisibleForTesting
protected void copyFromHost(MapHost host) throws IOException {
// reset retryStartTime for a new host
retryStartTime = 0;
// Get completed maps on 'host'
List<TaskAttemptID> maps = scheduler.getMapsForHost(host);
// Sanity check to catch hosts with only 'OBSOLETE' maps,
... | @Test
public void testCopyFromHostIncompatibleShuffleVersionWithRetry()
throws Exception {
String replyHash = SecureShuffleUtils.generateHash(encHash.getBytes(), key);
when(connection.getResponseCode()).thenReturn(200);
when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME))
.th... |
@Override
public GlobalRollbackResponseProto convert2Proto(GlobalRollbackResponse globalRollbackResponse) {
final short typeCode = globalRollbackResponse.getTypeCode();
final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType(
MessageTypeProto.forNum... | @Test
public void convert2Proto() {
GlobalRollbackResponse globalRollbackResponse = new GlobalRollbackResponse();
globalRollbackResponse.setGlobalStatus(GlobalStatus.AsyncCommitting);
globalRollbackResponse.setMsg("msg");
globalRollbackResponse.setResultCode(ResultCode.Failed);
... |
public static CommandAPDU getNikGACommand() {
return new CommandAPDU(
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
);
} | @Test
void getNikGACommand() {
assertEquals("SSSSSSSSSSSSSSSS", Hex.toHexString(ApduFactory.getNikGACommand().getBytes()).toUpperCase());
assertEquals("2.16.528.1.1003.10.9.3.3", PolymorphType.PIP.getOid().toString());
} |
@Override
public String getDescription() {
return "Write a file with the given filename and body.";
} | @Test
void testGetDescription() {
assertEquals("Write a file with the given filename and body.", writeFileAction.getDescription());
} |
public ClusterSerdes init(Environment env,
ClustersProperties clustersProperties,
int clusterIndex) {
ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex);
log.debug("Configuring serdes for cluster {}", clusterP... | @Test
void serdeWithBuiltInNameAndNoPropertiesCantBeInitializedIfSerdeNotSupportAutoConfigure() {
ClustersProperties.SerdeConfig serdeConfig = new ClustersProperties.SerdeConfig();
serdeConfig.setName("BuiltIn2"); //auto-configuration not supported
serdeConfig.setTopicKeysPattern("keys");
serdeConfig.... |
private static boolean canSatisfyConstraints(ApplicationId appId,
PlacementConstraint constraint, SchedulerNode node,
AllocationTagsManager atm,
Optional<DiagnosticsCollector> dcOpt)
throws InvalidAllocationTagsQueryException {
if (constraint == null) {
LOG.debug("Constraint is found e... | @Test
public void testNotSelfAppConstraints()
throws InvalidAllocationTagsQueryException {
long ts = System.currentTimeMillis();
ApplicationId application1 = BuilderUtils.newApplicationId(ts, 100);
ApplicationId application2 = BuilderUtils.newApplicationId(ts, 101);
ApplicationId application3 = ... |
@Override
public void handleAsyncException(String message, Throwable exception) {
if (isRestoring || isRunning) {
// only fail if the task is still in restoring or running
asyncExceptionHandler.handleAsyncException(message, exception);
}
} | @Test
void testAsyncExceptionHandlerHandleExceptionForwardsMessageProperly() {
MockEnvironment mockEnvironment = MockEnvironment.builder().build();
RuntimeException expectedException = new RuntimeException("RUNTIME EXCEPTION");
final StreamTask.StreamTaskAsyncExceptionHandler asyncException... |
@PostMapping("/config")
public Result<Boolean> addConfig(@RequestBody ConfigInfo configInfo) {
if (StringUtils.isEmpty(configInfo.getGroup()) || StringUtils.isEmpty(configInfo.getKey())
|| StringUtils.isEmpty(configInfo.getContent())) {
return new Result<>(ResultCodeType.MISS_PAR... | @Test
public void addConfig() {
Result<Boolean> result = configController.addConfig(configInfo);
Assert.assertFalse(result.isSuccess());
Result<Boolean> result1 = configController.addConfig(addConfigInfo);
Assert.assertTrue(result1.isSuccess());
} |
@Override
String getFileName(double lat, double lon) {
int intKey = calcIntKey(lat, lon);
String str = areas.get(intKey);
if (str == null)
return null;
int minLat = Math.abs(down(lat));
int minLon = Math.abs(down(lon));
str += "/";
if (lat >= 0)
... | @Disabled
@Test
public void testGetEleVerticalBorder() {
instance = new SRTMProvider();
// Border between the tiles N42E011 and N43E011
assertEquals("Eurasia/N42E011", instance.getFileName(42.999999, 11.48));
assertEquals(419, instance.getEle(42.999999, 11.48), precision);
... |
@Override
public void createEndpoints(Endpoints endpoints) {
checkNotNull(endpoints, ERR_NULL_ENDPOINTS);
checkArgument(!Strings.isNullOrEmpty(endpoints.getMetadata().getUid()),
ERR_NULL_ENDPOINTS_UID);
k8sEndpointsStore.createEndpoints(endpoints);
log.info(String.f... | @Test(expected = IllegalArgumentException.class)
public void testCreateDuplicateEndpoints() {
target.createEndpoints(ENDPOINTS);
target.createEndpoints(ENDPOINTS);
} |
protected Object getValidJMSHeaderValue(String headerName, Object headerValue) {
if (headerValue instanceof String) {
return headerValue;
} else if (headerValue instanceof BigInteger) {
return headerValue.toString();
} else if (headerValue instanceof BigDecimal) {
... | @Test
public void testGetValidJmsHeaderValueWithBigIntegerShouldSucceed() {
Object value = jmsBindingUnderTest.getValidJMSHeaderValue("foo", new BigInteger("12345"));
assertEquals("12345", value);
} |
@GetMapping(value = "/configs")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
public Result<List<ConfigInfoWrapper>> getConfigsByTenant(@RequestParam("namespaceId") String namespaceId)
throws NacosApiException {
// check namespaceId
ParamUtils.checkTenantV2(namespac... | @Test
void testGetConfigListByNamespaceWhenIsPublic() throws NacosApiException {
ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper();
configInfoWrapper.setDataId("test");
configInfoWrapper.setGroup("test");
configInfoWrapper.setContent("test");
List<ConfigInfoWrappe... |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void create_query() {
List<Criterion> criteria = asList(
Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build(),
Criterion.builder().setKey("coverage").setOperator(LTE).setValue("80").build());
ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emp... |
@Override
public Map<String, String> generationCodes(Long tableId) {
// 校验是否已经存在
CodegenTableDO table = codegenTableMapper.selectById(tableId);
if (table == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
List<CodegenColumnDO> columns = codegenColumnMapper.se... | @Test
public void testGenerationCodes_columnNotExists() {
// mock 数据(CodegenTableDO)
CodegenTableDO table = randomPojo(CodegenTableDO.class,
o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())
.setTemplateType(CodegenTemplateTypeEnum.MASTER_NORMAL.getType()));
... |
OffsetAndEpoch findHighestRemoteOffset(TopicIdPartition topicIdPartition, UnifiedLog log) throws RemoteStorageException {
OffsetAndEpoch offsetAndEpoch = null;
Option<LeaderEpochFileCache> leaderEpochCacheOpt = log.leaderEpochCache();
if (leaderEpochCacheOpt.isDefined()) {
LeaderEpoc... | @Test
void testFindHighestRemoteOffsetWithUncleanLeaderElection() throws RemoteStorageException {
List<EpochEntry> totalEpochEntries = Arrays.asList(
new EpochEntry(0, 0),
new EpochEntry(1, 150),
new EpochEntry(2, 300)
);
checkpoint.write(total... |
public Map<String, String> build() {
Map<String, String> builder = new HashMap<>();
configureFileSystem(builder);
configureNetwork(builder);
configureCluster(builder);
configureSecurity(builder);
configureOthers(builder);
LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]",
... | @Test
public void test_default_settings_for_cluster_mode() throws Exception {
File homeDir = temp.newFolder();
Props props = new Props(new Properties());
props.set(SEARCH_PORT.getKey(), "1234");
props.set(SEARCH_HOST.getKey(), "127.0.0.1");
props.set(CLUSTER_NODE_SEARCH_HOST.getKey(), "127.0.0.1")... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test(timeout = 1000)
public void detectCircularReferences3() {
context.putProperty("A", "${B}");
context.putProperty("B", "${C}");
context.putProperty("C", "${A}");
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Circular variable reference detected whi... |
@Override
public void discardState() throws Exception {
Exception aggregatedExceptions = null;
if (jobManagerOwnedSnapshot != null) {
try {
jobManagerOwnedSnapshot.discardState();
} catch (Exception remoteDiscardEx) {
aggregatedExceptions = r... | @Test
void discardState() throws Exception {
SnapshotResult<StateObject> result =
SnapshotResult.withLocalState(mock(StateObject.class), mock(StateObject.class));
result.discardState();
verify(result.getJobManagerOwnedSnapshot()).discardState();
verify(result.getTaskL... |
@Override
public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) {
selectedBundlesCache.clear();
Map<String, BrokerData> brokersData = loadData.getBrokerData();
Map<String, BundleData> loadBundleData = loadData.getBundleDataForLoadSh... | @Test
public void testBrokerWithMultipleBundles() {
int numBundles = 10;
LoadData loadData = new LoadData();
LocalBrokerData broker1 = new LocalBrokerData();
LocalBrokerData broker2 = new LocalBrokerData();
String broker2Name = "broker2";
double brokerThroughput = ... |
@Override
public Result reconcile(Request request) {
return client.fetch(Backup.class, request.name())
.map(backup -> {
var metadata = backup.getMetadata();
var status = backup.getStatus();
var spec = backup.getSpec();
if (isDeleted... | @Test
void somethingWentWrongWhenBackup() {
var name = "fake-backup";
var backup = createPureBackup(name);
backup.getSpec().setFormat("zip");
when(client.fetch(Backup.class, name)).thenReturn(Optional.of(backup));
doNothing().when(client).update(backup);
when(migratio... |
public abstract long observeWm(int queueIndex, long wmValue); | @Test
public void when_allIdleAndDuplicateIdleMessage_then_processed() {
// Duplicate idle messages are possible in this scenario:
// A source instance emits IDLE_MESSAGE, then an event (not causing a WM) and then another
// IDLE_MESSAGE again. The IDLE_MESSAGE is broadcast, but the event is... |
int getLowestObservedDistributionBits() {
return lowestObservedDistributionBits;
} | @Test
void lowest_observed_distribution_bit_is_initially_16() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertEquals(16, versionTracker.getLowestObservedDistributionBits());
} |
public static Single<Uri> proxy(@NonNull Context context, @NonNull Uri data) {
return Single.just(data)
.subscribeOn(RxSchedulers.background())
.observeOn(RxSchedulers.mainThread())
.map(remoteUri -> proxyContentUriToLocalFileUri(context, remoteUri));
} | @Test
@Config(shadows = ShadowFileProvider.class)
public void testHappyPathKnownMime() throws IOException {
var shadowMimeTypeMap = Shadows.shadowOf(MimeTypeMap.getSingleton());
shadowMimeTypeMap.addExtensionMimeTypeMapping("png", "image/png");
final var uriSingle = LocalProxy.proxy(ApplicationProvider.... |
public static Duration parseDuration(String text) {
checkNotNull(text);
final String trimmed = text.trim();
checkArgument(!trimmed.isEmpty(), "argument is an empty- or whitespace-only string");
final int len = trimmed.length();
int pos = 0;
char current;
while ... | @Test
void testParseDurationSeconds() {
assertThat(TimeUtils.parseDuration("667766s").getSeconds()).isEqualTo(667766);
assertThat(TimeUtils.parseDuration("667766sec").getSeconds()).isEqualTo(667766);
assertThat(TimeUtils.parseDuration("667766secs").getSeconds()).isEqualTo(667766);
as... |
@Override
public InputStream getAsciiStream(final int columnIndex) throws SQLException {
return mergeResultSet.getInputStream(columnIndex, ASCII);
} | @Test
void assertGetAsciiStreamWithColumnIndex() throws SQLException {
InputStream inputStream = mock(InputStream.class);
when(mergeResultSet.getInputStream(1, "Ascii")).thenReturn(inputStream);
assertThat(shardingSphereResultSet.getAsciiStream(1), instanceOf(InputStream.class));
} |
public void setPolicyManager(FederationPolicyManager policyManager)
throws YarnException {
if (policyManager == null) {
LOG.warn("Attempting to set null policy manager");
return;
}
// Extract the configuration from the policy manager
String queue = policyManager.getQueue();
SubClus... | @Test
public void testReadOnly() throws YarnException {
conf.setBoolean(YarnConfiguration.GPG_POLICY_GENERATOR_READONLY, true);
stateStore = mock(MemoryFederationStateStore.class);
facade.reinitialize(stateStore, conf);
when(stateStore.getPolicyConfiguration(Matchers.any(
GetSubClusterPolicyCo... |
public void archive(final Archive archive, final Path workdir, final List<Path> files,
final ProgressListener listener, final TranscriptListener transcript) throws BackgroundException {
command.send(archive.getCompressCommand(workdir, files), listener, transcript);
} | @Test
@Ignore
public void testArchive() throws Exception {
final SFTPCompressFeature feature = new SFTPCompressFeature(session);
for(Archive archive : Archive.getKnownArchives()) {
final Path workdir = new SFTPHomeDirectoryService(session).find();
final Path test = new Pa... |
@Override
public Object evaluate(final ProcessingDTO processingDTO) {
String input = (String) getFromPossibleSources(name, processingDTO)
.orElse(null);
if (input == null) {
return mapMissingTo;
}
return input.equals(value) ? 1.0 : 0.0;
} | @Test
void evaluateMissingValue() {
String fieldName = "fieldName";
String fieldValue = "fieldValue";
Number mapMissingTo = 1.0;
KiePMMLNormDiscrete kiePMMLNormContinuous = getKiePMMLNormDiscrete(fieldName, fieldValue, mapMissingTo);
ProcessingDTO processingDTO = getProcessin... |
public static short translateBucketAcl(AccessControlList acl, String userId) {
short mode = (short) 0;
for (Grant grant : acl.getGrantsAsList()) {
Permission perm = grant.getPermission();
Grantee grantee = grant.getGrantee();
if (perm.equals(Permission.Read)) {
if (isUserIdInGrantee(gr... | @Test
public void translateUserFullPermission() {
mAcl.grantPermission(mUserGrantee, Permission.FullControl);
Assert.assertEquals((short) 0700, S3AUtils.translateBucketAcl(mAcl, ID));
Assert.assertEquals((short) 0000, S3AUtils.translateBucketAcl(mAcl, OTHER_ID));
} |
@Override
public int compare( Object data1, Object data2 ) throws KettleValueException {
InetAddress inet1 = getInternetAddress( data1 );
InetAddress inet2 = getInternetAddress( data2 );
int cmp = 0;
if ( inet1 == null ) {
if ( inet2 == null ) {
cmp = 0;
} else {
cmp = -1;
... | @Test
public void testCompare_PDI17270() throws UnknownHostException, KettleValueException {
ValueMetaInternetAddress vm = new ValueMetaInternetAddress();
InetAddress smaller = InetAddress.getByName( "0.0.0.0" );
InetAddress larger = InetAddress.getByName( "255.250.200.128" );
assertEquals( -1, vm.co... |
@Override
public List<TaskProperty> getPropertiesForDisplay() {
return new ArrayList<>();
} | @Test
public void shouldReturnEmptyPropertiesForDisplay() {
assertThat(new KillAllChildProcessTask().getPropertiesForDisplay().isEmpty(), is(true));
} |
@Override
public PGobject parse(final String value) {
try {
PGobject result = new PGobject();
result.setType("bit");
result.setValue(value);
return result;
} catch (final SQLException ex) {
throw new SQLWrapperException(ex);
}
} | @Test
void assertParse() {
PGobject actual = new PostgreSQLBitValueParser().parse("1");
assertThat(actual.getType(), is("bit"));
assertThat(actual.getValue(), is("1"));
} |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public Long createTenant(TenantSaveReqVO createReqVO) {
// 校验租户名称是否重复
validTenantNameDuplicate(createReqVO.getName(), null);
// 校验租户域名是否重复
validTenantWebsiteDuplicate(createReqVO.getWebsite(), null);
/... | @Test
public void testCreateTenant() {
// mock 套餐 100L
TenantPackageDO tenantPackage = randomPojo(TenantPackageDO.class, o -> o.setId(100L));
when(tenantPackageService.validTenantPackage(eq(100L))).thenReturn(tenantPackage);
// mock 角色 200L
when(roleService.createRole(argThat... |
@GET
@Path("{name}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getConfig(@PathParam("name") String configName) {
log.trace(String.format(MESSAGE_CONFIG, QUERY));
final TelemetryConfig config =
nullIsNotFound(configService... | @Test
public void testUpdateConfigAddressWithoutOperation() {
expect(mockConfigAdminService.getConfig(anyString())).andReturn(null).once();
replay(mockConfigAdminService);
final WebTarget wt = target();
Response response = wt.path(PATH + "/address/test1/address1")
.r... |
public static boolean shouldStartHazelcast(AppSettings appSettings) {
return isClusterEnabled(appSettings.getProps()) && toNodeType(appSettings.getProps()).equals(NodeType.APPLICATION);
} | @Test
@UseDataProvider("validIPv4andIPv6Addresses")
public void shouldStartHazelcast_must_be_false_on_SearchNode(String host) {
TestAppSettings settings = newSettingsForSearchNode(host);
assertThat(ClusterSettings.shouldStartHazelcast(settings)).isFalse();
} |
public static <T> Class<? extends T>[] convertStringListToClassTypeArray(List<String> classNames, Class<? extends T> targetClassType) {
Class<? extends T>[] array = (Class<? extends T>[]) Array.newInstance(Class.class, classNames.size());
return classNames.stream()
.map(className -> (Cl... | @Test
public void testConvertStringsToClassesList() {
List<String> recordExceptionsList = List.of("java.lang.Exception", "java.lang.RuntimeException");
Class<? extends Throwable>[] recordExceptions = ClassParseUtil
.convertStringListToClassTypeArray(recordExceptionsList, Throwable.c... |
public static String format(Integer id) {
return format(id, " ");
} | @Test
public void testFormat() {
assertEquals(AreaUtils.format(110105), "北京市 北京市 朝阳区");
assertEquals(AreaUtils.format(1), "中国");
assertEquals(AreaUtils.format(2), "蒙古");
} |
void updateInactivityStateIfExpired(long ts, DeviceId deviceId, DeviceStateData stateData) {
log.trace("Processing state {} for device {}", stateData, deviceId);
if (stateData != null) {
DeviceState state = stateData.getState();
if (!isActive(ts, state)
&& (st... | @Test
public void givenNotMyPartition_whenUpdateInactivityTimeoutIfExpired_thenShouldCleanupDevice() {
// GIVEN
long currentTime = System.currentTimeMillis();
DeviceState deviceState = DeviceState.builder()
.active(true)
.lastConnectTime(currentTime - 8000)
... |
@Override
public void prepare(
PrepareJobRequest request, StreamObserver<PrepareJobResponse> responseObserver) {
try {
LOG.trace("{} {}", PrepareJobRequest.class.getSimpleName(), request);
// insert preparation
String preparationId =
String.format("%s_%s", request.getJobName(), U... | @Test
public void testPrepareIsSuccessful() {
JobApi.PrepareJobRequest request =
JobApi.PrepareJobRequest.newBuilder()
.setJobName(TEST_JOB_NAME)
.setPipeline(RunnerApi.Pipeline.getDefaultInstance())
.setPipelineOptions(Struct.getDefaultInstance())
.build();... |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null) {
return rule.getInverted();
}
final String value = msg.getField(rule.getField()).toString();
return rule.getInverted() ^ value.trim().equals(rule.getValue());
} | @Test
public void testInvertedMatch() {
StreamRule rule = getSampleRule();
rule.setInverted(true);
Message msg = getSampleMessage();
msg.addField("something", "nonono");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(matcher.match(msg, rule));
} |
static String parseAccessToken(String responseBody) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(responseBody);
JsonNode accessTokenNode = rootNode.at("/access_token");
if (accessTokenNode == null) {
// Only grab the firs... | @Test
public void testParseAccessTokenEmptyAccessToken() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("access_token", "");
assertThrows(IllegalArgumentException.class, () -> HttpAccessTokenRetriever.parseAccessToken(mapper.writeVa... |
public static SessionInformations getSessionInformationsBySessionId(String sessionId) {
final HttpSession session = getSessionById(sessionId);
if (session == null) {
return null;
}
// dans Jenkins notamment, une session invalidée peut rester un peu dans cette map
try {
return new SessionInformations(ses... | @Test
public void testGetSessionInformationsBySessionId() {
final HttpSessionEvent sessionEvent = createSessionEvent();
sessionListener.sessionCreated(sessionEvent);
final SessionInformations sessionInformations = SessionListener
.getSessionInformationsBySessionId(sessionEvent.getSession().getId());
assert... |
int getLowestObservedDistributionBits() {
return lowestObservedDistributionBits;
} | @Test
void lowest_observed_distribution_bit_is_tracked_across_states() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
updateAndPromote(versionTracker, stateWithoutAnnotations("bits:15 distributor:2 storage:2"), 100);
assertEquals(15, versionTracker.getLowestObservedD... |
public static <T> Inner<T> create() {
return new Inner<>();
} | @Test
@Category(NeedsRunner.class)
public void renameNestedInArrayFields() {
Schema nestedSchema = Schema.builder().addStringField("field1").addInt32Field("field2").build();
Schema schema =
Schema.builder().addArrayField("array", Schema.FieldType.row(nestedSchema)).build();
PCollection<Row> ren... |
@Override
public void notify(Metrics metrics) {
WithMetadata withMetadata = (WithMetadata) metrics;
MetricsMetaInfo meta = withMetadata.getMeta();
int scope = meta.getScope();
if (!DefaultScopeDefine.inServiceCatalog(scope) && !DefaultScopeDefine.inServiceInstanceCatalog(scope)
... | @Test
public void testNotifyWithServiceInstanceCatalog() {
String metricsName = "service-instance-metrics";
when(metadata.getMetricsName()).thenReturn(metricsName);
when(DefaultScopeDefine.inServiceInstanceCatalog(0)).thenReturn(true);
String instanceInventoryName = "instance-inven... |
public static String extractFromURIPattern(String paramsRuleString, String pattern, String realURI) {
Map<String, String> criteriaMap = new TreeMap<>();
pattern = sanitizeURLForRegExp(pattern);
realURI = sanitizeURLForRegExp(realURI);
// Build a pattern for extracting parts from pattern and a p... | @Test
void testExtractFromURIPattern2() {
String resourcePath = "/pet/2";
String operationName = "/pet/:petId";
String paramRule = "petId";
String dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(paramRule, operationName, resourcePath);
assertEquals("/petId=2", dispatchC... |
@Override
public void verifyCompatibility(WindowFn<?, ?> other) throws IncompatibleWindowException {
if (!this.isCompatible(other)) {
throw new IncompatibleWindowException(
other,
String.format(
"Only %s objects with the same size, period and offset are compatible.",
... | @Test
public void testVerifyCompatibility() throws IncompatibleWindowException {
SlidingWindows.of(Duration.millis(10))
.verifyCompatibility(SlidingWindows.of(Duration.millis(10)));
thrown.expect(IncompatibleWindowException.class);
SlidingWindows.of(Duration.millis(10))
.verifyCompatibilit... |
public ClientTelemetrySender telemetrySender() {
return clientTelemetrySender;
} | @Test
public void testHandleResponseGetSubscriptionsWithoutMetrics() {
ClientTelemetryReporter.DefaultClientTelemetrySender telemetrySender = (ClientTelemetryReporter.DefaultClientTelemetrySender) clientTelemetryReporter.telemetrySender();
assertTrue(telemetrySender.maybeSetState(ClientTelemetryStat... |
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (GetXMLDataMeta) smi;
data = (GetXMLDataData) sdi;
if ( super.init( smi, sdi ) ) {
data.rownr = 1L;
data.nrInputFields = meta.getInputFields().length;
// correct attribute path if needed
// do it once
... | @Test
public void testGetXMLData_MissingNodesYieldNullValues() throws Exception {
KettleEnvironment.init();
System.setProperty( Const.KETTLE_XML_MISSING_TAG_YIELDS_NULL_VALUE, "Y" );
testGetXMLData( null );
} |
public static Object extractValue(Object object, String attributeName, boolean failOnMissingAttribute) throws Exception {
return createGetter(object, attributeName, failOnMissingAttribute).getValue(object);
} | @Test
public void extractValue_whenIntermediateFieldIsInterfaceAndDoesNotContainField_returnsNull()
throws Exception {
OuterObject object = new OuterObject();
assertNull(ReflectionHelper.extractValue(object, "emptyInterface.doesNotExist", false));
} |
public boolean assign(DefaultIssue issue, @Nullable UserDto user, IssueChangeContext context) {
String assigneeUuid = user != null ? user.getUuid() : null;
if (!Objects.equals(assigneeUuid, issue.assignee())) {
String newAssigneeName = user == null ? null : user.getName();
issue.setFieldChange(conte... | @Test
void change_assignee() {
UserDto user = newUserDto().setLogin("emmerik").setName("Emmerik");
issue.setAssigneeUuid("user_uuid");
boolean updated = underTest.assign(issue, user, context);
assertThat(updated).isTrue();
assertThat(issue.assignee()).isEqualTo(user.getUuid());
assertThat(iss... |
protected void addModel(EpoxyModel<?> modelToAdd) {
int initialSize = models.size();
pauseModelListNotifications();
models.add(modelToAdd);
resumeModelListNotifications();
notifyItemRangeInserted(initialSize, 1);
} | @Test
public void testAddModel() {
testAdapter.addModel(new TestModel());
verify(observer).onItemRangeInserted(0, 1);
assertEquals(1, testAdapter.models.size());
testAdapter.addModel(new TestModel());
verify(observer).onItemRangeInserted(1, 1);
assertEquals(2, testAdapter.models.size());
... |
public void isIn(@Nullable Iterable<?> iterable) {
checkNotNull(iterable);
if (!contains(iterable, actual)) {
failWithActual("expected any of", iterable);
}
} | @Test
public void isInFailure() {
expectFailure.whenTesting().that("x").isIn(oneShotIterable("a", "b", "c"));
assertFailureKeys("expected any of", "but was");
assertFailureValue("expected any of", "[a, b, c]");
} |
@VisibleForTesting
CopyObjectResult atomicCopy(
S3ResourceId sourcePath, S3ResourceId destinationPath, ObjectMetadata sourceObjectMetadata)
throws AmazonClientException {
CopyObjectRequest copyObjectRequest =
new CopyObjectRequest(
sourcePath.getBucket(),
sourcePath.get... | @Test
public void testAtomicCopy() {
testAtomicCopy(s3Config("s3"));
testAtomicCopy(s3Config("other"));
testAtomicCopy(s3ConfigWithSSECustomerKey("s3"));
testAtomicCopy(s3ConfigWithSSECustomerKey("other"));
} |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListLexicographicSortOrderAssumption() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path directory = new GoogleStorageDirectoryFeature(session).mkdir(
new Path(container, new Al... |
@VisibleForTesting
public static boolean isTtlEnough(ConfidenceBasedTtlInfo ttlInfo, Duration estimatedExecutionTime)
{
Instant expiryTime = ttlInfo.getExpiryInstant();
long timeRemainingInSeconds = SECONDS.between(Instant.now(), expiryTime);
return new Duration(Math.max(timeRemainingInS... | @Test
public void testTtlComparison()
{
ConfidenceBasedTtlInfo confidenceBasedTtlInfo = ConfidenceBasedTtlInfo.getInfiniteTtl();
Duration estimatedExecutionTime = new Duration(1, TimeUnit.HOURS);
assertTrue(SimpleTtlNodeSelector.isTtlEnough(confidenceBasedTtlInfo, estimatedExecutionTime)... |
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
return usage(args);
}
String action = args[0];
String name = args[1];
int result;
if (A_LOAD.equals(action)) {
result = loadClass(name);
} else if (A_CREATE.equals(action)) {
//first load t... | @Test
public void testFailsNoSuchResource() throws Throwable {
run(FindClass.E_NOT_FOUND,
FindClass.A_RESOURCE,
"org/apache/hadoop/util/ThereIsNoSuchClass.class");
} |
public void metricRemoval(KafkaMetric metric) {
ledger.metricRemoval(metric);
} | @Test
public void testMetricRemoval() {
metrics.addMetric(metricName, (config, now) -> 100.0);
collector.collect(testEmitter);
assertEquals(2, testEmitter.emittedMetrics().size());
metrics.removeMetric(metricName);
assertFalse(collector.getTrackedMetrics().contains(metricNa... |
public void returnFury(Fury fury) {
Objects.requireNonNull(fury);
try {
lock.lock();
idleCacheQueue.add(fury);
activeCacheNumber.decrementAndGet();
furyCondition.signalAll();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new RuntimeException(e);
} finall... | @Test
public void testReturnFuryForbidden() {
ClassLoaderFuryPooled pooled = getPooled(4, 9);
Assert.assertThrows(NullPointerException.class, () -> pooled.returnFury(null));
} |
public int getBackupCount() {
return backupCount;
} | @Test
public void testGetBackupCount() {
assertEquals(MapConfig.DEFAULT_BACKUP_COUNT, new MapConfig().getBackupCount());
} |
KIn deserializeKey(final String topic, final Headers headers, final byte[] data) {
return keyDeserializer.deserialize(topic, headers, data);
} | @Test
public void shouldProvideTopicHeadersAndDataToKeyDeserializer() {
final SourceNode<String, String> sourceNode = new MockSourceNode<>(new TheDeserializer(), new TheDeserializer());
final RecordHeaders headers = new RecordHeaders();
final String deserializeKey = sourceNode.deserializeKey... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.