focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static SchemaAnnotationProcessResult process(List<SchemaAnnotationHandler> handlers,
DataSchema dataSchema, AnnotationProcessOption options)
{
return process(handlers, dataSchema, options, true);
} | @Test(dataProvider = "denormalizedSchemaTestCases_invalid")
public void testDenormalizedSchemaProcessing_invalid(String filePath, String errorMsg) throws Exception
{
DataSchema dataSchema = TestUtil.dataSchemaFromPdlInputStream(getClass().getResourceAsStream(filePath));
PegasusSchemaAnnotationHandlerImpl c... |
@Override
public void registerInstance(Service service, Instance instance, String clientId) throws NacosException {
NamingUtils.checkInstanceIsLegal(instance);
Service singleton = ServiceManager.getInstance().getSingleton(service);
if (!singleton.isEphemeral()) {
throw new N... | @Test
void testRegisterPersistentInstance() throws NacosException {
assertThrows(NacosRuntimeException.class, () -> {
when(service.isEphemeral()).thenReturn(false);
// Excepted exception
ephemeralClientOperationServiceImpl.registerInstance(service, instance, ipPortBasedCl... |
public void removeDataSources() {
if (nodesToDel == null || nodesToDel.isEmpty()) {
return;
}
lock.lock();
try {
Map<String, DataSource> map = highAvailableDataSource.getDataSourceMap();
Set<String> copySet = new HashSet<String>(nodesToDel);
... | @Test
public void testRemoveDataSources() {
String url = "jdbc:derby:memory:foo;create=true";
String name = "foo";
addNode(url, name);
DruidDataSource ds = (DruidDataSource) haDataSource.getDataSourceMap().get(name);
updater.getNodesToDel().add(name);
haDataSource.ad... |
protected static String getReverseZoneNetworkAddress(String baseIp, int range,
int index) throws UnknownHostException {
if (index < 0) {
throw new IllegalArgumentException(
String.format("Invalid index provided, must be positive: %d", index));
}
if (range < 0) {
throw new Illegal... | @Test
public void testThrowIllegalArgumentExceptionIfIndexIsNegative()
throws Exception {
exception.expect(IllegalArgumentException.class);
ReverseZoneUtils.getReverseZoneNetworkAddress(NET, RANGE, -1);
} |
public FifoOrderingPolicyForPendingApps() {
List<Comparator<SchedulableEntity>> comparators =
new ArrayList<Comparator<SchedulableEntity>>();
comparators.add(new RecoveryComparator());
comparators.add(new PriorityComparator());
comparators.add(new FifoComparator());
this.comparator = new Com... | @Test
public void testFifoOrderingPolicyForPendingApps() {
FifoOrderingPolicyForPendingApps<MockSchedulableEntity> policy =
new FifoOrderingPolicyForPendingApps<MockSchedulableEntity>();
MockSchedulableEntity r1 = new MockSchedulableEntity();
MockSchedulableEntity r2 = new MockSchedulableEntity()... |
@Override
@Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入
public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
if (CollUtil.isEmpty(importUsers)) {
throw exception(USER_IMPORT_LIST_IS_EMPTY);
}
UserImportRespVO... | @Test
public void testImportUserList_01() {
// 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
});
// mock 方法,模拟失败
doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any());
// 调用
UserImportRespVO r... |
public static StorageInterface make(final PluginRegistry pluginRegistry,
final String pluginId,
final Map<String, Object> pluginConfiguration,
final Validator validator) {
Optional<Class<? ext... | @Test
void shouldFailedGivenInvalidId() {
Assertions.assertThrows(KestraRuntimeException.class,
() -> StorageInterfaceFactory.make(registry, "invalid", Map.of(), validator));
} |
@Override
public Catalog getCatalog(String catalogName) throws NoSuchObjectException, MetaException {
LOG.debug("Fetching catalog {}", catalogName);
MCatalog mCat = getMCatalog(catalogName);
if (mCat == null) {
throw new NoSuchObjectException("No catalog " + catalogName);
}
return mCatToCat(... | @Test(expected = NoSuchObjectException.class)
public void getNoSuchCatalog() throws MetaException, NoSuchObjectException {
objectStore.getCatalog("no_such_catalog");
} |
public boolean isAggregatable() {
return (state & MASK_AGG) != 0;
} | @Test
public void isAggregatable() {
LacpState state = new LacpState((byte) 0x4);
assertTrue(state.isAggregatable());
} |
@Override
protected void doStart() throws Exception {
super.doStart();
try {
plc4XEndpoint.setupConnection();
} catch (PlcConnectionException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.error("Connection setup failed, stopping Consumer", e);
... | @Test
public void doStart() {
} |
public static CurlOption parse(String cmdLine) {
List<String> args = ShellWords.parse(cmdLine);
URI url = null;
HttpMethod method = HttpMethod.PUT;
List<Entry<String, String>> headers = new ArrayList<>();
Proxy proxy = NO_PROXY;
while (!args.isEmpty()) {
Str... | @Test
public void must_provide_valid_proxy_protocol() {
String uri = "https://example.com -x no-such-protocol://proxy.example.com:3129";
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> CurlOption.parse(uri));
assertThat(exception.getMessage(),
... |
protected FairSchedulerQueueInfoList getChildQueues(FSQueue queue,
FairScheduler scheduler) {
// Return null to omit 'childQueues' field from the return value of
// REST API if it is empty. We omit the field to keep the consistency
// with CapacitySchedu... | @Test
public void testEmptyChildQueues() {
FairSchedulerConfiguration fsConf = new FairSchedulerConfiguration();
RMContext rmContext = mock(RMContext.class);
PlacementManager placementManager = new PlacementManager();
SystemClock clock = SystemClock.getInstance();
FairScheduler scheduler = mock(Fa... |
public void setWriteTimeout(int writeTimeout) {
this.writeTimeout = writeTimeout;
} | @Test
public void testRetryableErrorRetryEnoughTimes() throws IOException {
List<MockLowLevelHttpResponse> responses = new ArrayList<>();
final int retries = 10;
// The underlying http library calls getStatusCode method of a response multiple times. For a
// response, the method should return the sam... |
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
... | @Test
public void testDisplayDataExcludedFromOverriddenBaseClass() {
ExtendsBaseOptions options = PipelineOptionsFactory.as(ExtendsBaseOptions.class);
options.setFoo("bar");
DisplayData displayData = DisplayData.from(options);
assertThat(displayData, not(hasDisplayItem(hasNamespace(BaseOptions.class)... |
public static int toMonths(int year, int months)
{
try {
return addExact(multiplyExact(year, 12), months);
}
catch (ArithmeticException e) {
throw new IllegalArgumentException(e);
}
} | @Test
public void testFormat()
{
assertMonths(0, "0-0");
assertMonths(toMonths(0, 0), "0-0");
assertMonths(3, "0-3");
assertMonths(-3, "-0-3");
assertMonths(toMonths(0, 3), "0-3");
assertMonths(toMonths(0, -3), "-0-3");
assertMonths(28, "2-4");
a... |
T getFunction(final List<SqlArgument> arguments) {
// first try to get the candidates without any implicit casting
Optional<T> candidate = findMatchingCandidate(arguments, false);
if (candidate.isPresent()) {
return candidate.get();
} else if (!supportsImplicitCasts) {
throw createNoMatchin... | @Test
public void shouldMatchNestedGenericMethodWithMultipleGenerics() {
// Given:
final ArrayType generic = ArrayType.of(GenericType.of("A"));
givenFunctions(
function(EXPECTED, -1, generic, generic)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(Sql... |
@Override
public Object clone() {
try {
SampleSaveConfiguration clone = (SampleSaveConfiguration)super.clone();
if(this.dateFormat != null) {
clone.timestampFormatter = (FastDateFormat)this.threadSafeLenientFormatter().clone();
}
return clone;
... | @Test
public void testClone() throws Exception {
SampleSaveConfiguration a = new SampleSaveConfiguration();
a.setUrl(false);
a.setAssertions(true);
a.setDefaultDelimiter();
a.setDefaultTimeStampFormat();
a.setDataType(true);
assertFalse(a.saveUrl());
a... |
public static RedisSinkConfig load(String yamlFile) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(new File(yamlFile), RedisSinkConfig.class);
} | @Test
public final void loadFromMapTest() throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("redisHosts", "localhost:6379");
map.put("redisPassword", "fake@123");
map.put("redisDatabase", "1");
map.put("clientMode", "Standalone");
m... |
@CanIgnoreReturnValue
public final Ordered containsExactlyElementsIn(@Nullable Iterable<?> expected) {
return containsExactlyElementsIn(expected, false);
} | @Test
@SuppressWarnings("ContainsExactlyElementsInWithVarArgsToExactly")
public void iterableContainsExactlyElementsInIterable() {
assertThat(asList(1, 2)).containsExactlyElementsIn(asList(1, 2));
expectFailureWhenTestingThat(asList(1, 2)).containsExactlyElementsIn(asList(1, 2, 4));
assertFailureValue(... |
public int getLength() {
return length;
} | @Test
public void testGetLength() {
lz4CompressData.setLength(6);
Assertions.assertEquals(lz4CompressData.getLength(), 6);
} |
protected String getSimpleTypeNodeTextValue(JsonNode jsonNode) {
if (!isSimpleTypeNode(jsonNode)) {
throw new IllegalArgumentException("Parameter does not contains a simple type");
}
return jsonNode.get(VALUE).textValue();
} | @Test
public void getSimpleTypeNodeTextValue_intNode() {
ObjectNode jsonNode = new ObjectNode(factory);
jsonNode.set(VALUE, new IntNode(10));
assertThat(expressionEvaluator.getSimpleTypeNodeTextValue(jsonNode)).isNull();
} |
public static FieldScope none() {
return FieldScopeImpl.none();
} | @Test
public void testFieldScopes_none_withAnyField() {
String typeUrl =
isProto3()
? "type.googleapis.com/com.google.common.truth.extensions.proto.SubTestMessage3"
: "type.googleapis.com/com.google.common.truth.extensions.proto.SubTestMessage2";
Message message = parse("o_int:... |
@Override
public Optional<Decision> onMemoryUsageChanged(
int numTotalRequestedBuffers, int currentPoolSize) {
return numTotalRequestedBuffers < currentPoolSize * releaseThreshold
? Optional.of(Decision.NO_ACTION)
: Optional.empty();
} | @Test
void testOnUsedMemoryBelowThreshold() {
Optional<Decision> memoryUsageChangedDecision = spillStrategy.onMemoryUsageChanged(5, 10);
assertThat(memoryUsageChangedDecision).hasValue(Decision.NO_ACTION);
} |
@Override
public String encrypt(String value) {
return encrypt(value, null);
} | @Test
public void testEncryptionForNullString() {
Encryptor encryptor = new AesEncryptor();
String b64Encrypted = encryptor.encrypt(null);
assertNull(b64Encrypted);
} |
@Override
public void deleteTag(Long id) {
// 校验存在
validateTagExists(id);
// 校验标签下是否有用户
validateTagHasUser(id);
// 删除
memberTagMapper.deleteById(id);
} | @Test
public void testDeleteTag_success() {
// mock 数据
MemberTagDO dbTag = randomPojo(MemberTagDO.class);
tagMapper.insert(dbTag);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbTag.getId();
// 调用
tagService.deleteTag(id);
// 校验数据不存在了
assertNull(tagM... |
public Long dimInsert( RowMetaInterface inputRowMeta, Object[] row, Long technicalKey, boolean newEntry,
Long versionNr, Date dateFrom, Date dateTo ) throws KettleException {
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
if ( data.prepStatementInsert == null
&& data.prepSta... | @Test
public void testDimInsert() throws Exception {
RowMetaInterface rowMetaInterface = mock( RowMetaInterface.class );
Object[] objects = mock( List.class ).toArray();
Date date = mock( Date.class );
dimensionLookupSpy.dimInsert( rowMetaInterface, objects, 132323L, true, null, date, date );
veri... |
@Override
public long position() {
int pos = byteBufferHeader.position();
List<ByteBuffer> messageBufferList = this.getMessageResult.getMessageBufferList();
for (ByteBuffer bb : messageBufferList) {
pos += bb.position();
}
return pos;
} | @Test
public void ManyMessageTransferPosTest() {
ByteBuffer byteBuffer = ByteBuffer.allocate(20);
byteBuffer.putInt(20);
GetMessageResult getMessageResult = new GetMessageResult();
ManyMessageTransfer manyMessageTransfer = new ManyMessageTransfer(byteBuffer,getMessageResult);
... |
@Override
public MeterCellId allocateMeterId(DeviceId deviceId, MeterScope meterScope) {
if (userDefinedIndexMode) {
log.warn("Unable to allocate meter id when user defined index mode is enabled");
return null;
}
MeterTableKey meterTableKey = MeterTableKey.key(deviceI... | @Test
public void testAllocateIdInUserDefinedIndexMode() {
initMeterStore(true);
assertNull(meterStore.allocateMeterId(did1, MeterScope.globalScope()));
} |
public static String getCertFingerPrint(Certificate cert) {
byte [] digest = null;
try {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance("SHA-1");
digest = md.digest(encCertInfo);
} catch (Exception e) {
logger... | @Test
public void testGetCertFingerPrintAlice() throws Exception {
X509Certificate cert = null;
try (InputStream is = Config.getInstance().getInputStreamFromFile("alice.crt")){
CertificateFactory cf = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) cf.genera... |
public boolean isAssociatedWithEnvironmentOtherThan(String environmentName) {
return !(this.environmentName == null || this.environmentName.equals(environmentName));
} | @Test
public void shouldUnderstandWhenAssociatedWithADifferentEnvironment() {
EnvironmentPipelineModel foo = new EnvironmentPipelineModel("foo", "env");
assertThat(foo.isAssociatedWithEnvironmentOtherThan("env"), is(false));
assertThat(foo.isAssociatedWithEnvironmentOtherThan("env2"), is(tru... |
@Override
protected int compareFirst(final Path p1, final Path p2) {
if(p1.attributes().getSize() > p2.attributes().getSize()) {
return ascending ? 1 : -1;
}
else if(p1.attributes().getSize() < p2.attributes().getSize()) {
return ascending ? -1 : 1;
}
... | @Test
public void testCompareFirst() {
assertEquals(0,
new SizeComparator(true).compareFirst(new Path("/a", EnumSet.of(Path.Type.file)), new Path("/b", EnumSet.of(Path.Type.file))));
} |
public String transform() throws ScanException {
StringBuilder stringBuilder = new StringBuilder();
compileNode(node, stringBuilder, new Stack<Node>());
return stringBuilder.toString();
} | @Test
public void literal() throws ScanException {
String input = "abv";
Node node = makeNode(input);
NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0);
Assertions.assertEquals(input, nodeToStringTransformer.transform());
} |
@Override
public Map<CompoundKey, AlbumEntry> batchGet(Set<CompoundKey> ids)
{
Map<CompoundKey, AlbumEntry> result = new HashMap<>();
for (CompoundKey key : ids)
result.put(key, get(key));
return result;
} | @Test
public void testBatchGet()
{
// get keys 1-3
Set<CompoundKey> batchIds = new HashSet<>();
for (int i = 1; i <= 3; i++)
{
batchIds.add(_keys[i]);
}
Map<CompoundKey, AlbumEntry> batchEntries = _entryRes.batchGet(batchIds);
Assert.assertEquals(batchEntries.size(), 3);
for (... |
@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() throws JOSEException {
var key = generateKey();
var jwkSource = new StaticJwkSource<>(key);
var claims =
new JWTClaimsSet.Builder()
.audience(RP_ISSUER.toString())
.subject(CLIENT_ID)
.issuer(CLIENT_ID)
.expirationTime(Dat... |
@SuppressWarnings({"unchecked", "rawtypes"})
public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final NullsOrderType nullsOrderType,
final boolean caseSensitive) {
if (null == thisValue && null == otherVal... | @Test
void assertCompareToWhenFirstValueIsNullForOrderByDescAndNullsFirst() {
assertThat(CompareUtils.compareTo(null, 1, OrderDirection.DESC, NullsOrderType.FIRST, caseSensitive), is(-1));
} |
@SuppressWarnings("deprecation")
public static List<SimpleAclRule> fromCrd(AclRule rule) {
if (rule.getOperations() != null && rule.getOperation() != null) {
throw new InvalidResourceException("Both fields `operations` and `operation` cannot be filled in at the same time");
} else if (ru... | @Test
public void testFromCrdWithBothOperationsAndOperationSetAtTheSameTime() {
assertThrows(InvalidResourceException.class, () -> {
AclRule rule = new AclRuleBuilder()
.withType(AclRuleType.ALLOW)
.withResource(ACL_RULE_TOPIC_RESOURCE)
.withHost... |
@SuppressWarnings("squid:S1181")
// Yes we really do want to catch Throwable
@Override
public V apply(U input) {
int retryAttempts = 0;
while (true) {
try {
return baseFunction.apply(input);
} catch (Throwable t) {
if (!exceptionClass.i... | @Test
public void testFailureAfterTwoRetries() {
new RetryingFunction<>(this::succeedAfterTwoFailures, RetryableException.class, 2, 10).apply(null);
} |
public static RestSettingBuilder delete(final RestIdMatcher idMatcher) {
return single(HttpMethod.DELETE, checkNotNull(idMatcher, "ID Matcher should not be null"));
} | @Test
public void should_delete_with_response() throws Exception {
server.resource("targets",
delete("1").response(status(409))
);
running(server, () -> {
HttpResponse httpResponse = helper.deleteForResponse(remoteUrl("/targets/1"));
assertThat(httpRe... |
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
public void testEvaluate() throws Exception {
SelType res = t1.evaluate("1+1;", new HashMap<>(), null);
assertEquals("LONG: 2", res.type() + ": " + res);
} |
public List<Map<String, Artifact>> getBatchStepInstancesArtifactsFromList(
String workflowId, long workflowInstanceId, Map<String, Long> stepIdToRunId) {
List<Map<String, Long>> batches = splitMap(stepIdToRunId);
List<Map<String, Artifact>> results = new ArrayList<>();
for (Map<String, Long> batch :... | @Test
public void testGetBatchStepInstancesArtifactsFromList() throws IOException {
MaestroStepInstanceDao stepDaoSpy = Mockito.spy(stepDao);
StepInstance siSubWf = loadObject(TEST_STEP_INSTANCE_SUBWORKFLOW, StepInstance.class);
Map<String, Long> stepIdToRunId = new LinkedHashMap<>();
int numberOfInst... |
@Override
public boolean checkCredentials(String username, String password) {
if (username == null || password == null) {
return false;
}
Credentials credentials = new Credentials(username, password);
if (validCredentialsCache.contains(credentials)) {
return ... | @Test
public void testPBKDF2WithHmacSHA512_upperCaseWithoutColon() throws Exception {
String algorithm = "PBKDF2WithHmacSHA512";
int iterations = 1000;
int keyLength = 128;
String hash =
"07:6F:E2:27:9B:CA:48:66:9B:13:9E:02:9C:AE:FC:E4:1A:2F:0F:E6:48:A3:FF:8E:D2:30:59... |
@Override
public CompletableFuture<List<DescribeGroupsResponseData.DescribedGroup>> describeGroups(
RequestContext context,
List<String> groupIds
) {
if (!isActive.get()) {
return CompletableFuture.completedFuture(DescribeGroupsRequest.getErrorDescribedGroupList(
... | @Test
public void testDescribeGroupsWhenNotStarted() throws ExecutionException, InterruptedException {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorService(
new LogContext(),
create... |
public NotFoundException(String message) {
super(STATUS, NAME, message);
} | @Test
public void testNotFoundException() throws Exception {
try {
throw new NotFoundException("/hello");
} catch (NotFoundException e) {
assertEquals(e.getStatus(), 404);
assertEquals(e.getName(), "Not Found");
}
} |
@Override
public List<DeptTreeVO> getDeptTree(Integer excludeNodeId, Boolean appendRoot, Boolean needSetTotal) {
QueryWrapper wrapper = QueryWrapper.create()
// .orderBy(SysDept::getDeep).asc()
.orderBy(SysDept::getSort).asc();
// 获取所有部门信息
List<SysDept> list =... | @Test
void getDeepTreeVOS() {
List<DeptTreeVO> tree = sysDeptService.getDeptTree(null, true, false);
System.out.println("树形:" + JsonUtils.toJsonString(tree));
} |
@Override
public synchronized DefaultConnectClient get(
final Optional<String> ksqlAuthHeader,
final List<Entry<String, String>> incomingRequestHeaders,
final Optional<KsqlPrincipal> userPrincipal
) {
if (defaultConnectAuthHeader == null) {
defaultConnectAuthHeader = buildDefaultAuthHead... | @Test
public void shouldBuildAuthHeader() throws Exception {
// Given:
givenCustomBasicAuthHeader();
givenValidCredentialsFile();
// When:
final DefaultConnectClient connectClient =
connectClientFactory.get(Optional.empty(), Collections.emptyList(), Optional.empty());
// Then:
as... |
@Override
@NonNull public CharSequence getKeyboardName() {
return mKeyboardName;
} | @Test
public void testKeyboardPopupCharacterStringThreeRowsConstructor() throws Exception {
AnyPopupKeyboard keyboard =
new AnyPopupKeyboard(
new DefaultAddOn(getApplicationContext(), getApplicationContext()),
getApplicationContext(),
"qwertasdfgzxc",
SIMPLE... |
public static Getter newThisGetter(Getter parent, Object object) {
return new ThisGetter(parent, object);
} | @Test
public void newThisGetter() {
OuterObject object = new OuterObject("name", new InnerObject("inner", 0, 1, 2, 3));
Getter innerObjectThisGetter = GetterFactory.newThisGetter(null, object);
Class<?> returnType = innerObjectThisGetter.getReturnType();
assertEquals(OuterObject.cla... |
public void recordFailedAttempt(String username, String address) {
Log.warn("Failed admin console login attempt by "+username+" from "+address);
Long cnt = (long)0;
if (attemptsPerIP.get(address) != null) {
cnt = attemptsPerIP.get(address);
}
cnt++;
attemptsP... | @Test
public void aFailedLoginWillBeAudited() {
final String username = "test-user-b-" + StringUtils.randomString(10);
loginLimitManager.recordFailedAttempt(username, "a.b.c.e");
verify(securityAuditManager).logEvent(username, "Failed admin console login attempt", "A failed login attempt t... |
void checkPerm(PlainAccessResource needCheckedAccess, PlainAccessResource ownedAccess) {
permissionChecker.check(needCheckedAccess, ownedAccess);
} | @Test(expected = AclException.class)
public void checkPermAdmin() {
PlainAccessResource plainAccessResource = new PlainAccessResource();
plainAccessResource.setRequestCode(17);
plainPermissionManager.checkPerm(plainAccessResource, pubPlainAccessResource);
} |
public DateTimeFormatSpec(String format) {
Preconditions.checkArgument(StringUtils.isNotEmpty(format), "Must provide format");
if (Character.isDigit(format.charAt(0))) {
// Colon format
String[] tokens = StringUtil.split(format, COLON_SEPARATOR, COLON_FORMAT_MAX_TOKENS);
Preconditions.checkA... | @Test
public void testDateTimeFormatSpec() {
DateTimeFormatSpec dateTimeFormatSpec = new DateTimeFormatSpec("5:DAYS:EPOCH");
assertEquals(dateTimeFormatSpec.getTimeFormat(), DateTimeFieldSpec.TimeFormat.EPOCH);
assertEquals(dateTimeFormatSpec.getColumnSize(), 5);
assertEquals(dateTimeFormatSpec.getCol... |
public Optional<User> login(String nameOrEmail, String password) {
if (nameOrEmail == null || password == null) {
return Optional.empty();
}
User user = userDAO.findByName(nameOrEmail);
if (user == null) {
user = userDAO.findByEmail(nameOrEmail);
}
if (user != null && !user.isDisabled()) {
boolean... | @Test
void callingLoginShouldExecutePostLoginActivitiesForUserOnSuccessfulAuthentication() {
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
.thenReturn(true);
Mock... |
@CheckForNull
@Override
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
return Optional.ofNullable((branchChangedFilesWithFileMovementDetection(targetBranchName, rootBaseDir)))
.map(GitScmProvider::extractAbsoluteFilePaths)
.orElse(null);
} | @Test
public void branchChangedFiles_finds_branch_in_specific_origin() throws IOException, GitAPIException {
git.branchCreate().setName("b1").call();
git.checkout().setName("b1").call();
createAndCommitFile("file-b1");
Path worktree2 = temp.newFolder().toPath();
Git.cloneRepository()
.setUR... |
public ByteBuffer fetchOnePacket() throws IOException {
int readLen;
ByteBuffer result = defaultBuffer;
result.clear();
while (true) {
headerByteBuffer.clear();
readLen = readAll(headerByteBuffer);
if (readLen != PACKET_HEADER_LEN) {
/... | @Test(expected = IOException.class)
public void testException() throws IOException {
// mock
new Expectations() {
{
channel.read((ByteBuffer) any);
minTimes = 0;
result = new IOException();
}
};
MysqlChannel cha... |
public void editConnection() {
try {
Collection<UIDatabaseConnection> connections = connectionsTable.getSelectedItems();
if ( connections != null && !connections.isEmpty() ) {
// Grab the first item in the list & send it to the database dialog
DatabaseMeta databaseMeta = ( (UIDatabaseCo... | @Test
public void editConnection_NameExists_SameWithSpaces() throws Exception {
final String dbName = " name";
DatabaseMeta dbmeta = spy( new DatabaseMeta() );
dbmeta.setName( dbName );
List<UIDatabaseConnection> selectedConnection = singletonList( new UIDatabaseConnection( dbmeta, repository ) );
... |
@Override
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already completed!");
return;
}
final List<SearchPivotLimitMigration> pivotLimitMigrations = StreamSupport.stream(this.searches.find().spliterator... | @Test
@MongoDBFixtures("V20230113095301_MigrateGlobalPivotLimitsToGroupingsInSearchesTest_simpleSearch.json")
void migratingSimpleView() {
this.migration.upgrade();
assertThat(migrationCompleted().migratedSearchTypes()).isEqualTo(1);
final Document document = this.collection.find().fir... |
public static String normalize(String url) {
return normalize(url, false);
} | @Test
public void normalizeIpv6Test() {
String url = "http://[fe80::8f8:2022:a603:d180]:9439";
String normalize = URLUtil.normalize("http://[fe80::8f8:2022:a603:d180]:9439", true);
assertEquals(url, normalize);
} |
public static void print(Context context) {
SINGLETON.print(context, 0);
} | @Test
public void testWithException() {
Status s0 = new ErrorStatus("test0", this);
Status s1 = new InfoStatus("test1", this, new Exception("testEx"));
Status s11 = new InfoStatus("test11", this);
Status s12 = new InfoStatus("test12", this);
s1.add(s11);
s1.add(s12);
... |
@Udf
public String concatWS(
@UdfParameter(description = "Separator string and values to join") final String... inputs) {
if (inputs == null || inputs.length < 2) {
throw new KsqlFunctionException("Function Concat_WS expects at least two input arguments.");
}
final String separator = inputs[0... | @Test
public void shouldWorkWithEmptySeparator() {
assertThat(udf.concatWS("", "foo", "bar"), is("foobar"));
assertThat(udf.concatWS(EMPTY_BYTES, ByteBuffer.wrap(new byte[] {1}), ByteBuffer.wrap(new byte[] {2})),
is(ByteBuffer.wrap(new byte[] {1, 2})));
} |
@Override
public void writeAndFlush(final Object obj) {
Future future = writeQueue.enqueue(obj);
future.addListener((FutureListener) future1 -> {
if (!future1.isSuccess()) {
Throwable throwable = future1.cause();
LOGGER.error("Failed to send to "
... | @Test
public void testRunSuccess() throws Exception {
nettyChannel.writeAndFlush("111");
Mockito.verify(mockWriteQueue).enqueue("111");
ArgumentCaptor<GenericFutureListener> captor = ArgumentCaptor.forClass(GenericFutureListener.class);
Mockito.verify(mockFuture).addListener(captor... |
@Override
public void configureAuthenticationConfig(AuthenticationConfig authConfig,
Optional<FunctionAuthData> functionAuthData) {
if (!functionAuthData.isPresent()) {
// if auth data is not present maybe user is trying to use anonymous role thus do... | @Test
public void configureAuthenticationConfig() {
byte[] testBytes = new byte[]{0, 1, 2, 3, 4};
CoreV1Api coreV1Api = mock(CoreV1Api.class);
KubernetesSecretsTokenAuthProvider kubernetesSecretsTokenAuthProvider = new KubernetesSecretsTokenAuthProvider();
kubernetesSecretsTokenAuthP... |
@Override
public boolean emitMetric(SinglePointMetric metric) {
if (!shouldEmitMetric(metric)) {
return false;
}
emitted.add(metric);
return true;
} | @Test
public void testEmitMetric() {
Predicate<? super MetricKeyable> selector = ClientTelemetryUtils.getSelectorFromRequestedMetrics(
Collections.singletonList("name"));
ClientTelemetryEmitter emitter = new ClientTelemetryEmitter(selector, true);
SinglePointMetric gauge = Singl... |
@Override
public Boolean login(Properties properties) {
if (ramContext.validate()) {
return true;
}
loadRoleName(properties);
loadAccessKey(properties);
loadSecretKey(properties);
loadRegionId(properties);
return true;
} | @Test
void testLoginWithRoleName() {
assertTrue(ramClientAuthService.login(roleProperties));
assertNull(ramContext.getAccessKey(), PropertyKeyConst.ACCESS_KEY);
assertNull(ramContext.getSecretKey(), PropertyKeyConst.SECRET_KEY);
assertEquals(PropertyKeyConst.RAM_ROLE_NAME, ramContext... |
@Override
public void close() {
watchCache.forEach((key, configFileChangeListener) -> {
if (Objects.nonNull(configFileChangeListener)) {
final ConfigFile configFile = configFileService.getConfigFile(polarisConfig.getNamespace(), polarisConfig.getFileGroup(), key);
... | @Test
public void testClose() {
polarisSyncDataService.close();
} |
public List<AbstractResultMessage> getResultMessages() {
return resultMessages;
} | @Test
void getResultMessages() {
BatchResultMessage batchResultMessage = new BatchResultMessage();
Assertions.assertTrue(batchResultMessage.getResultMessages().isEmpty());
} |
@VisibleForTesting
static JibContainerBuilder processCommonConfiguration(
RawConfiguration rawConfiguration,
InferredAuthProvider inferredAuthProvider,
ProjectProperties projectProperties)
throws InvalidFilesModificationTimeException, InvalidAppRootException,
IncompatibleBaseImageJav... | @Test
public void testEntrypoint_warningOnExpandClasspathDependenciesForWar()
throws IOException, InvalidCreationTimeException, InvalidImageReferenceException,
IncompatibleBaseImageJavaVersionException, InvalidPlatformException,
InvalidContainerVolumeException, MainClassInferenceException, I... |
public static <T> Write<T> write(String jdbcUrl, String table) {
return new AutoValue_ClickHouseIO_Write.Builder<T>()
.jdbcUrl(jdbcUrl)
.table(table)
.properties(new Properties())
.maxInsertBlockSize(DEFAULT_MAX_INSERT_BLOCK_SIZE)
.initialBackoff(DEFAULT_INITIAL_BACKOFF)
... | @Test
public void testInt64() throws Exception {
Schema schema =
Schema.of(Schema.Field.of("f0", FieldType.INT64), Schema.Field.of("f1", FieldType.INT64));
Row row1 = Row.withSchema(schema).addValue(1L).addValue(2L).build();
Row row2 = Row.withSchema(schema).addValue(2L).addValue(4L).build();
... |
@Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()
&& (node.has("minLength") || node.has("maxLength"))
&& isApplicableType(field... | @Test
public void jsrDisable() {
when(config.isIncludeJsr303Annotations()).thenReturn(false);
JFieldVar result = rule.apply("node", node, null, fieldVar, null);
assertSame(fieldVar, result);
verify(fieldVar, never()).annotate(sizeClass);
verify(annotation, never()).param(any... |
private boolean rename(ChannelSftp channel, Path src, Path dst)
throws IOException {
Path workDir;
try {
workDir = new Path(channel.pwd());
} catch (SftpException e) {
throw new IOException(e);
}
Path absoluteSrc = makeAbsolute(workDir, src);
Path absoluteDst = makeAbsolute(wor... | @Test(expected=java.io.IOException.class)
public void testRenameNonExistFile() throws Exception {
Path file1 = new Path(localDir, name.getMethodName().toLowerCase() + "1");
Path file2 = new Path(localDir, name.getMethodName().toLowerCase() + "2");
sftpFs.rename(file1, file2);
} |
public AggregateAnalysisResult analyze(
final ImmutableAnalysis analysis,
final List<SelectExpression> finalProjection
) {
if (!analysis.getGroupBy().isPresent()) {
throw new IllegalArgumentException("Not an aggregate query");
}
final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ... | @Test
public void shouldNotCaptureNonAggregateGroupByFunction() {
// given:
givenGroupByExpressions(FUNCTION_CALL);
// When:
final AggregateAnalysisResult result = analyzer.analyze(analysis, selects);
// Then:
assertThat(result.getAggregateFunctions(), contains(REQUIRED_AGG_FUNC_CALL));
} |
public static String validateColumnName(@Nullable String columnName) {
String name = requireNonNull(columnName, "Column name cannot be null");
checkDbIdentifierCharacters(columnName, "Column name");
return name;
} | @Test
public void fail_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> validateColumnName(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Column name cannot be null");
} |
public static BigDecimal cast(final Integer value, final int precision, final int scale) {
if (value == null) {
return null;
}
return cast(value.longValue(), precision, scale);
} | @Test
public void shouldCastDoubleNegative() {
// When:
final BigDecimal decimal = DecimalUtil.cast(-1.1, 2, 1);
// Then:
assertThat(decimal, is(new BigDecimal("-1.1")));
} |
@Override
public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) {
Objects.requireNonNull(intentOperationContext);
Optional<IntentData> toUninstall = intentOperationContext.toUninstall();
Optional<IntentData> toInstall = intentOperationContext.toInstall();
... | @Test
public void testFlowInstallationFailedErrorUnderThreshold() {
// And retry two times and success
intentInstallCoordinator = new TestIntentInstallCoordinator();
installer.intentInstallCoordinator = intentInstallCoordinator;
errors = ImmutableList.of(FLOWINSTALLATIONFAILED, FLOWI... |
@Override
public void removeConfigInfo4Beta(final String dataId, final String group, final String tenant) {
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
tjt.execute(status -> {
try {
ConfigInfoStateWrapper configInfo = findConfigInfo4... | @Test
void testRemoveConfigInfo4Beta() {
String dataId = "dataId456789";
String group = "group4567";
String tenant = "tenant56789o0";
//mock exist beta
ConfigInfoStateWrapper mockedConfigInfoStateWrapper = new ConfigInfoStateWrapper();
mockedConfigInfoStateWrapper.set... |
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public RouteContext route(final ConnectionContext connectionContext, final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database) {
RouteContext result = new RouteContext();
Optional<String> ... | @Test
void assertRouteByHintManagerHintWithException() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDataSourceName("ds-3");
QueryContext logicSQL = new QueryContext(commonSQLStatementContext, "", Collections.emptyList(), new HintValueContext(), connect... |
@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 testMaxUnloadBundleNumPerShedding(){
conf.setMaxUnloadBundleNumPerShedding(2);
int numBundles = 20;
LoadData loadData = new LoadData();
LocalBrokerData broker1 = new LocalBrokerData();
LocalBrokerData broker2 = new LocalBrokerData();
String broker2... |
public static LocalDateTime parse(CharSequence text) {
return parse(text, (DateTimeFormatter) null);
} | @Test
public void parseOffsetTest() {
final LocalDateTime localDateTime = LocalDateTimeUtil.parse("2021-07-30T16:27:27+08:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME);
assertEquals("2021-07-30T16:27:27", Objects.requireNonNull(localDateTime).toString());
} |
public void delete(String host) {
db.delete(TABLE_HOSTS, COLUMN_HOST + " = ?", new String[] { host });
} | @Test
public void testDelete() {
Hosts hosts = new Hosts(RuntimeEnvironment.application, "hosts.db");
hosts.put("ni.hao", "127.0.0.1");
assertEquals("ni.hao/127.0.0.1", hosts.get("ni.hao").toString());
hosts.put("ni.hao", "127.0.0.2");
hosts.delete("ni.hao");
assertEquals(null, hosts.get("ni.... |
public void setIncludeCallerData(boolean includeCallerData) {
this.includeCallerData = includeCallerData;
} | @Test
public void settingIncludeCallerDataPropertyCausedCallerDataToBeIncluded() {
asyncAppender.addAppender(listAppender);
asyncAppender.setIncludeCallerData(true);
asyncAppender.start();
asyncAppender.doAppend(builder.build(diff));
asyncAppender.stop();
// check the event
assertEquals... |
public static void clean(
Object func, ExecutionConfig.ClosureCleanerLevel level, boolean checkSerializable) {
clean(func, level, checkSerializable, Collections.newSetFromMap(new IdentityHashMap<>()));
} | @Test
void testSelfReferencingClean() {
final NestedSelfReferencing selfReferencing = new NestedSelfReferencing();
ClosureCleaner.clean(selfReferencing, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true);
} |
@Override
public DdlCommand create(
final String sqlExpression,
final DdlStatement ddlStatement,
final SessionConfig config
) {
return FACTORIES
.getOrDefault(ddlStatement.getClass(), (statement, cf, ci) -> {
throw new KsqlException(
"Unable to find ddl command ... | @Test(expected = KsqlException.class)
public void shouldThrowOnUnsupportedStatementType() {
// Given:
final ExecutableDdlStatement ddlStatement = new ExecutableDdlStatement() {
};
// Then:
commandFactories.create(sqlExpression, ddlStatement, SessionConfig.of(ksqlConfig, emptyMap()));
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
if (readerWay.hasTag("hazmat:adr_tunnel_cat", TUNNEL_CATEGORY_NAMES)) {
HazmatTunnel code = HazmatTunnel.valueOf(readerWay.getTag("hazmat:adr_tunnel_cat"));
hazT... | @Test
public void testADRTunnelCat() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
ReaderWay readerWay = new ReaderWay(1);
readerWay.setTag("hazmat:adr_tunnel_cat", "A");
parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags);
as... |
@Override
public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final java.nio.file.Path p = session.toPath(file);
final Set<OpenOption> options = new HashSet<>();
options.... | @Test(expected = NotfoundException.class)
public void testWriteNotFound() throws Exception {
final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
session.open(new DisabledProxyFinder(), new DisabledHostKeyCallback(), new DisabledLogi... |
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.GET;
} | @Test
void testMethod() {
assertThat(instance.getHttpMethod()).isEqualTo(HttpMethodWrapper.GET);
} |
@Override
public long getMax() {
if (values.length == 0) {
return 0;
}
return values[values.length - 1];
} | @Test
public void calculatesTheMaximumValue() {
assertThat(snapshot.getMax())
.isEqualTo(5);
} |
@Override
public RSet<V> get(K key) {
String keyHash = keyHash(key);
String setName = getValuesName(keyHash);
return new RedissonSetMultimapValues<>(codec, commandExecutor, setName, getTimeoutSetName(), key);
} | @Test
public void testValues() throws InterruptedException {
RMultimapCache<String, String> multimap = getMultimapCache("test");
multimap.put("1", "1");
multimap.put("1", "2");
multimap.put("1", "3");
multimap.put("1", "3");
assertThat(multimap.get("1").size(... |
@Override
public void reset() {
resetCount++;
super.reset();
initEvaluatorMap();
initCollisionMaps();
root.recursiveReset();
resetTurboFilterList();
cancelScheduledTasks();
fireOnReset();
resetListenersExceptResetResistant();
resetStatusListeners();
} | @Test
public void evaluatorMapPostReset() {
lc.reset();
assertNotNull(lc.getObject(CoreConstants.EVALUATOR_MAP));
} |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() < 2) {
onInvalidDataReceived(device, data);
return;
}
// Read flags
int offset = 0;
final int flags = data.getIntValue(Data.FORMAT_UINT8, offse... | @Test
public void onHeartRateMeasurementReceived_noContact() {
success = false;
final Data data = new Data(new byte[] {0x4, (byte) 0xFF});
response.onDataReceived(null, data);
assertTrue(response.isValid());
assertTrue(success);
assertEquals(255, heartRate);
assertNotNull(contactDetected);
assertFalse(... |
@Override
public String toString()
{
final ToStringBuilder builder = new ToStringBuilder(null, ToStringStyle.SHORT_PREFIX_STYLE)
.append("baseUriTemplate", _baseUriTemplate)
.append("pathKeys", _pathKeys)
.append("id", _id)
.append("queryParams", _queryParams);
return builder.toStri... | @Test
public void testID()
{
final GetRequest<?> getRequest = Mockito.mock(GetRequest.class);
Mockito.when(getRequest.getBaseUriTemplate()).thenReturn(BASE_URI_TEMPLATE);
Mockito.when(getRequest.getPathKeys()).thenReturn(PATH_KEYS);
Mockito.when(getRequest.getObjectId()).thenReturn(ID);
Mockito.... |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testTupleSupertype() {
RichMapFunction<?, ?> function =
new RichMapFunction<String, Tuple>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple map(... |
public static String generateCommandKey(String interfaceId, Method method) {
StringBuilder builder = new StringBuilder(interfaceId)
.append("#")
.append(method.getName())
.append("(");
if (method.getParameterTypes().length > 0) {
for (Class<?> parameterTyp... | @Test
public void testGenerateCommandKey() {
for (Method method : TestCase.class.getMethods()) {
if (method.isAnnotationPresent(HystrixCommandKey.class)) {
HystrixCommandKey annotation = method.getAnnotation(HystrixCommandKey.class);
Assert.assertEquals(annotation... |
@Override
public void createSubnet(Subnet osSubnet) {
checkNotNull(osSubnet, ERR_NULL_SUBNET);
checkArgument(!Strings.isNullOrEmpty(osSubnet.getId()), ERR_NULL_SUBNET_ID);
checkArgument(!Strings.isNullOrEmpty(osSubnet.getNetworkId()), ERR_NULL_SUBNET_NET_ID);
checkArgument(!Strings.i... | @Test(expected = IllegalArgumentException.class)
public void testCreateSubnetWithNullId() {
final Subnet testSubnet = NeutronSubnet.builder()
.networkId(NETWORK_ID)
.cidr("192.168.0.0/24")
.build();
target.createSubnet(testSubnet);
} |
@Override
public TransferAction action(final Session<?> source, final Session<?> destination, final boolean resumeRequested, final boolean reloadRequested,
final TransferPrompt prompt, final ListProgressListener listener) {
if(log.isDebugEnabled()) {
log.debug(St... | @Test
public void testAction() throws Exception {
final Path p = new Path("t", EnumSet.of(Path.Type.directory));
Transfer t = new SyncTransfer(new Host(new TestProtocol()), new TransferItem(p, new NullLocal("p", "t") {
@Override
public boolean exists() {
retur... |
@Override
public KeyValueIterator<K, V> range(final K from,
final K to) {
return new KeyValueIteratorFacade<>(inner.range(from, to));
} | @Test
public void shouldReturnPlainKeyValuePairsForRangeIterator() {
when(mockedKeyValueTimestampIterator.next())
.thenReturn(KeyValue.pair("key1", ValueAndTimestamp.make("value1", 21L)))
.thenReturn(KeyValue.pair("key2", ValueAndTimestamp.make("value2", 42L)));
when(mockedKe... |
@Override
public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback,
final ConnectionCallback connectionCallback) throws BackgroundException {
if(containerService.isContainer(source)) {
if(new SimplePathPredicate(sourc... | @Test(expected = InteroperabilityException.class)
public void testMoveDirectoryToRoot() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path(
new AlphanumericRandomStringService().ran... |
@Override
public void validateQuery(
final SessionConfig config,
final ExecutionPlan executionPlan,
final Collection<QueryMetadata> runningQueries
) {
validateCacheBytesUsage(
runningQueries.stream()
.filter(q -> q instanceof PersistentQueryMetadata)
.collect(Co... | @Test
public void shouldNotThrowIfUnderLimit() {
// Given:
final SessionConfig config = configWithLimits(5, OptionalLong.of(60));
// When/Then (no throw)
queryValidator.validateQuery(config, plan, queries);
} |
public static Path getConfigHome() {
return getConfigHome(System.getProperties(), System.getenv());
} | @Test
public void testGetConfigHome_linux() {
Properties fakeProperties = new Properties();
fakeProperties.setProperty("user.home", fakeConfigHome);
fakeProperties.setProperty("os.name", "os is LiNuX");
Assert.assertEquals(
Paths.get(fakeConfigHome, ".config").resolve("google-cloud-tools-java... |
@Override
public boolean resolve(final Path file) {
if(PreferencesFactory.get().getBoolean("path.symboliclink.resolve")) {
// Follow links instead
return false;
}
// Create symbolic link only if supported by the local file system
if(feature != null) {
... | @Test
public void testNotSupported() {
DownloadSymlinkResolver resolver = new DownloadSymlinkResolver(null, Collections.singletonList(
new TransferItem(new Path("/", EnumSet.of(Path.Type.directory)), new Local(System.getProperty("java.io.tmpdir")))
));
Path p = new Path("/a",... |
@Override
public String exec(Tuple t) throws IOException {
return SummaryData.toPrettyJSON(sumUp(getInputSchema(), t));
} | @Test
public void testEvalFunc() throws IOException {
Summary summary = new Summary();
String result = summary.exec(t(TEST_BAG));
validate(result, 1);
} |
public static long getNextScheduledTime(final String cronEntry, long currentTime) throws MessageFormatException {
long result = 0;
if (cronEntry == null || cronEntry.length() == 0) {
return result;
}
// Handle the once per minute case "* * * * *"
// starting the ne... | @Test
public void testgetNextTimeDayOfWeekVariant() throws MessageFormatException {
// using an absolute date so that result will be absolute - Monday 7 March 2011
Calendar current = Calendar.getInstance();
current.set(2011, Calendar.MARCH, 7, 9, 15, 30);
LOG.debug("start:" + curren... |
public void setSortOrder(@Nullable SortOrder sortOrder) {
if (sortOrder != null && sortOrder.scope != SortOrder.Scope.INTRA_FEED) {
throw new IllegalArgumentException("The specified sortOrder " + sortOrder
+ " is invalid. Only those with INTRA_FEED scope are allowed.");
}... | @Test
public void testSetSortOrder_OnlyIntraFeedSortAllowed() {
for (SortOrder sortOrder : SortOrder.values()) {
if (sortOrder.scope == SortOrder.Scope.INTRA_FEED) {
original.setSortOrder(sortOrder); // should be okay
} else {
assertThrows(IllegalArgum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.