focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Long sendSingleNotify(Long userId, Integer userType, String templateCode, Map<String, Object> templateParams) {
// 校验模版
NotifyTemplateDO template = validateNotifyTemplate(templateCode);
if (Objects.equals(template.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
... | @Test
public void testSendSingleMail_successWhenSmsTemplateDisable() {
// 准备参数
Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>buil... |
@Override
public MergedResult decorate(final QueryResult queryResult, final SQLStatementContext sqlStatementContext, final ShardingSphereRule rule) {
return new TransparentMergedResult(queryResult);
} | @Test
void assertDecorateQueryResult() throws SQLException {
QueryResult queryResult = mock(QueryResult.class);
when(queryResult.next()).thenReturn(true);
TransparentResultDecorator decorator = new TransparentResultDecorator();
assertTrue(decorator.decorate(queryResult, mock(SQLState... |
public static synchronized void e(final String tag, String text, Object... args) {
if (msLogger.supportsE()) {
String msg = getFormattedString(text, args);
msLogger.e(tag, msg);
addLog(LVL_E, tag, msg);
}
} | @Test
public void testE1() throws Exception {
Logger.e("mTag", "Text with %d digits", 0);
Mockito.verify(mMockLog).e("mTag", "Text with 0 digits");
Logger.e("mTag", "Text with no digits");
Mockito.verify(mMockLog).e("mTag", "Text with no digits");
} |
@Override
public Flux<String> getServices() {
return Flux.defer(() -> {
try {
return Flux.fromIterable(polarisServiceDiscovery.getServices());
}
catch (Exception e) {
LOGGER.error("get services from polaris server fail,", e);
return Flux.empty();
}
}).subscribeOn(Schedulers.boundedElastic()... | @Test
public void testGetServices() throws PolarisException {
when(serviceDiscovery.getServices()).thenAnswer(invocation -> {
if (count == 0) {
count++;
return Arrays.asList(SERVICE_PROVIDER + 1, SERVICE_PROVIDER + 2);
}
else {
throw new PolarisException(ErrorCode.UNKNOWN_SERVER_ERROR);
}
... |
@Nullable
public <T> T getInstanceWithoutAncestors(String name, Class<T> type) {
try {
return BeanFactoryUtils.beanOfType(getContext(name), type);
}
catch (BeansException ex) {
return null;
}
} | @Test
void getInstanceWithoutAncestors() {
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
parent.refresh();
FeignClientFactory feignClientFactory = new FeignClientFactory();
feignClientFactory.setApplicationContext(parent);
feignClientFactory.setConfigurations(Lists.ne... |
boolean isWriteShareGroupStateSuccessful(List<PersisterStateBatch> stateBatches) {
WriteShareGroupStateResult response;
try {
response = persister.writeState(new WriteShareGroupStateParameters.Builder()
.setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<Partition... | @Test
public void testIsWriteShareGroupStateFailure() {
Persister persister = Mockito.mock(Persister.class);
mockPersisterReadStateMethod(persister);
SharePartition sharePartition = SharePartitionBuilder.builder().withPersister(persister).build();
// Mock Write state RPC to return er... |
public Set<String> getColumnNames() {
if (_segment == null) {
throw new IllegalStateException("Index segment for Lazy row is uninitialized.");
}
return _segment.getColumnNames();
} | @Test
public void testGetColumnNames() {
IndexSegment segment = getMockSegment();
LazyRow lazyRow = new LazyRow();
lazyRow.init(segment, 1);
HashSet<String> columnNames = new HashSet<>(Arrays.asList("col1", "col2"));
when(segment.getColumnNames()).thenReturn(columnNames);
assertEquals(lazyRow... |
static <T extends Type> String encodeDynamicArray(DynamicArray<T> value) {
int size = value.getValue().size();
String encodedLength = encode(new Uint(BigInteger.valueOf(size)));
String valuesOffsets = encodeArrayValuesOffsets(value);
String encodedValues = encodeArrayValues(value);
... | @Test
public void testDynamicArray() {
DynamicArray<Uint> array =
new DynamicArray<>(
Uint.class,
new Uint(BigInteger.ONE),
new Uint(BigInteger.valueOf(2)),
new Uint(BigInteger.valueOf(3)));
... |
@SuppressWarnings("unchecked")
@Override
public void handle(ContainerAllocatorEvent event) {
if (event.getType() == ContainerAllocator.EventType.CONTAINER_REQ) {
LOG.info("Processing the event " + event.toString());
// Assign the same container ID as the AM
ContainerId cID =
Containe... | @Test
public void testAllocatedContainerResourceIsNotNull() {
ArgumentCaptor<TaskAttemptContainerAssignedEvent> containerAssignedCaptor
= ArgumentCaptor.forClass(TaskAttemptContainerAssignedEvent.class);
@SuppressWarnings("unchecked")
EventHandler<Event> eventHandler = mock(EventHandler.class);
... |
@Override
public CompletionStage<V> removeAsync(K key) {
return map.removeAsync(key);
} | @Test
public void testRemoveAsync() throws Exception {
map.put(23, "value-23");
assertTrue(map.containsKey(23));
String value = adapter.removeAsync(23).toCompletableFuture().get();
assertEquals("value-23", value);
assertFalse(map.containsKey(23));
} |
@Override
public BasicTypeDefine reconvert(Column column) {
try {
return super.reconvert(column);
} catch (SeaTunnelRuntimeException e) {
throw CommonError.convertToConnectorTypeError(
DatabaseIdentifier.KINGBASE,
column.getDataType().g... | @Test
public void testReconvertFloat() {
Column column =
PhysicalColumn.builder().name("test").dataType(BasicType.FLOAT_TYPE).build();
BasicTypeDefine typeDefine = KingbaseTypeConverter.INSTANCE.reconvert(column);
Assertions.assertEquals(column.getName(), typeDefine.getName(... |
@Override
public int getOrder() {
return PluginEnum.SPRING_CLOUD.getCode();
} | @Test
public void getOrder() {
final int result = springCloudPlugin.getOrder();
assertEquals(PluginEnum.SPRING_CLOUD.getCode(), result);
} |
public static int compose(final int major, final int minor, final int patch)
{
if (major < 0 || major > 255)
{
throw new IllegalArgumentException("major must be 0-255: " + major);
}
if (minor < 0 || minor > 255)
{
throw new IllegalArgumentException("m... | @Test
void shouldDetectExcessivePatch()
{
assertThrows(IllegalArgumentException.class, () -> SemanticVersion.compose(1, 1, 256));
} |
public final void isNegativeInfinity() {
isEqualTo(Float.NEGATIVE_INFINITY);
} | @Test
public void isNegativeInfinity() {
assertThat(Float.NEGATIVE_INFINITY).isNegativeInfinity();
assertThatIsNegativeInfinityFails(1.23f);
assertThatIsNegativeInfinityFails(Float.POSITIVE_INFINITY);
assertThatIsNegativeInfinityFails(Float.NaN);
assertThatIsNegativeInfinityFails(null);
} |
@Override
public BeamSqlTable buildBeamSqlTable(Table table) {
return new BigQueryTable(table, getConversionOptions(table.getProperties()));
} | @Test
public void testSelectWriteDispositionMethodAppend() {
Table table =
fakeTableWithProperties(
"hello",
"{ "
+ WRITE_DISPOSITION_PROPERTY
+ ": "
+ "\""
+ WriteDisposition.WRITE_APPEND.toString()
+ ... |
public PipelineColumnMetaData getColumnMetaData(final int columnIndex) {
return getColumnMetaData(columnNames.get(columnIndex - 1));
} | @Test
void assertGetColumnMetaDataGivenColumnName() {
PipelineColumnMetaData actual = pipelineTableMetaData.getColumnMetaData("test");
assertNull(pipelineTableMetaData.getColumnMetaData("non_exist"));
assertThat(actual.getOrdinalPosition(), is(1));
assertThat(actual.getName(), is("te... |
public static TransMeta loadMappingMeta( StepWithMappingMeta mappingMeta, Repository rep,
IMetaStore metaStore, VariableSpace space ) throws KettleException {
return loadMappingMeta( mappingMeta, rep, metaStore, space, true );
} | @Test
public void loadMappingMetaTest() throws Exception {
String childParam = "childParam";
String childValue = "childValue";
String paramOverwrite = "paramOverwrite";
String parentParam = "parentParam";
String parentValue = "parentValue";
String variablePath = "Internal.Entry.Current.Direc... |
public void isNotInstanceOf(Class<?> clazz) {
if (clazz == null) {
throw new NullPointerException("clazz");
}
if (Platform.classMetadataUnsupported()) {
throw new UnsupportedOperationException(
"isNotInstanceOf is not supported under -XdisableClassMetadata");
}
if (actual == nu... | @Test
public void isNotInstanceOfSuperclass() {
expectFailure.whenTesting().that(5).isNotInstanceOf(Number.class);
} |
@Override
void validateKeyPresent(final SourceName sinkName, final Projection projection) {
if (joinKey.isForeignKey()) {
final DataSourceNode leftInputTable = getLeftmostSourceNode();
final SourceName leftInputTableName = leftInputTable.getAlias();
final List<Column> leftInputTableKeys = leftI... | @Test
public void shouldThrowIfProjectionDoesNotIncludeAnyJoinColumns() {
// Given:
final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, true, left, right,
empty(),"KAFKA");
when(joinKey.getAllViableKeys(any()))
.thenReturn((List) ImmutableList.of(expression1, expression2));
... |
@SuppressWarnings("unchecked")
public V replace(final int key, final V value)
{
final V val = (V)mapNullValue(value);
requireNonNull(val, "value cannot be null");
final int[] keys = this.keys;
final Object[] values = this.values;
@DoNotSub final int mask = values.length ... | @Test
void replaceThrowsNullPointerExceptionIfValueIsNull()
{
final NullPointerException exception =
assertThrowsExactly(NullPointerException.class, () -> intToObjectMap.replace(42, null));
assertEquals("value cannot be null", exception.getMessage());
} |
public synchronized void startRequest()
{
lastRequestStart = ticker.read();
} | @Test
public void testStartRequest()
{
TestingTicker ticker = new TestingTicker();
ticker.increment(1, NANOSECONDS);
Backoff backoff = new Backoff(1, new Duration(15, SECONDS), ticker, ImmutableList.of(new Duration(10, MILLISECONDS)));
ticker.increment(10, MICROSECONDS);
... |
public void or(BitmapValue other) {
switch (other.bitmapType) {
case EMPTY:
break;
case SINGLE_VALUE:
add(other.singleValue);
break;
case BITMAP_VALUE:
switch (this.bitmapType) {
case EMPTY:
... | @Test
public void testBitmapValueOr() throws IOException {
// empty or empty
BitmapValue bitmap = new BitmapValue(emptyBitmap);
bitmap.or(emptyBitmap);
checkBitmap(bitmap, BitmapValue.EMPTY, 0, 0);
// empty or single
bitmap = new BitmapValue(emptyBitmap);
bit... |
@Override
public boolean deleteMep(MdId mdName, MaIdShort maName, MepId mepId,
Optional<MaintenanceDomain> oldMd) throws CfmConfigException {
MepKeyId key = new MepKeyId(mdName, maName, mepId);
//Will throw IllegalArgumentException if ma does not exist
cfmMdServ... | @Test
public void testDeleteMep() throws CfmConfigException {
expect(mdService.getMaintenanceAssociation(MDNAME1, MANAME1))
.andReturn(Optional.ofNullable(ma1))
.anyTimes();
replay(mdService);
expect(deviceService.getDevice(DEVICE_ID1)).andReturn(device1).any... |
public String toSql() {
List<String> subSQLs = new ArrayList<>();
if (columnSeparator != null) {
subSQLs.add("COLUMNS TERMINATED BY " + columnSeparator.toSql());
}
if (rowDelimiter != null) {
subSQLs.add("ROWS TERMINATED BY " + rowDelimiter.toSql());
}
... | @Test
public void testToSql() throws Exception {
RoutineLoadDesc originLoad = CreateRoutineLoadStmt.getLoadDesc(new OriginStatement("CREATE ROUTINE LOAD job ON tbl " +
"COLUMNS TERMINATED BY ';', " +
"ROWS TERMINATED BY '\n', " +
"COLUMNS(`a`, `b`, `c`=1), " +... |
@Converter
public static String toString(Record dataRecord) {
Charset charset = StandardCharsets.UTF_8;
ByteBuffer buffer = dataRecord.data().asByteBuffer();
if (buffer.hasArray()) {
byte[] bytes = dataRecord.data().asByteArray();
return new String(bytes, charset);
... | @Test
public void convertRecordToString() {
Record record = Record.builder().sequenceNumber("1")
.data(SdkBytes.fromByteBuffer(ByteBuffer.wrap("this is a String".getBytes(StandardCharsets.UTF_8)))).build();
String result = RecordStringConverter.toString(record);
assertThat(r... |
@Override
public void commitAndIndexOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, EntityEvent cause) {
indexOnEvent(dbSession, indexer -> indexer.prepareForRecoveryOnEntityEvent(dbSession, entityUuids, cause));
} | @Test
public void commitAndIndexOnEntityEvent_shouldCallIndexerWithSupportedItems() {
List<EsQueueDto> items1 = List.of(EsQueueDto.create("fake/fake1", "P1"), EsQueueDto.create("fake/fake1", "P1"));
List<EsQueueDto> items2 = List.of(EsQueueDto.create("fake/fake2", "P1"));
EventIndexer indexer1 = mock(Eve... |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 1) {
if ("dateIntToTs".equals(methodName)) {
return dateIntToTs(args[0]);
} else if ("tsToDateInt".equals(methodName)) {
return tsToDateInt(args[0]);
}
} else if (args.length == 2) {
i... | @Test(expected = IllegalFieldValueException.class)
public void testCallDateIntToTsInvalid() {
SelUtilFunc.INSTANCE.call("dateIntToTs", new SelType[] {SelLong.of(20200230)});
} |
@UdafFactory(description = "collect values of a field into a single Array")
public static <T> TableUdaf<T, List<T>, List<T>> createCollectListT() {
return new Collect<>();
} | @Test
public void shouldCollectTimestamps() {
final TableUdaf<Timestamp, List<Timestamp>, List<Timestamp>> udaf = CollectListUdaf.createCollectListT();
final Timestamp[] values = new Timestamp[] {new Timestamp(1), new Timestamp(2)};
List<Timestamp> runningList = udaf.initialize();
for (final Timestamp... |
@Override
public long length() {
return get(lengthAsync());
} | @Test
public void testLength() {
RBitSet bs = redisson.getBitSet("testbitset");
bs.set(0, 5);
bs.clear(0, 1);
assertThat(bs.length()).isEqualTo(5);
bs.clear();
bs.set(28);
bs.set(31);
assertThat(bs.length()).isEqualTo(32);
bs.clear();
... |
@Config("metadata-uri")
public ExampleConfig setMetadata(URI metadata)
{
this.metadata = metadata;
return this;
} | @Test
public void testDefaults()
{
ConfigAssertions.assertRecordedDefaults(ConfigAssertions.recordDefaults(ExampleConfig.class)
.setMetadata(null));
} |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testZeroRecordFile() {
DataFile empty = new TestDataFile("file.parquet", Row.of(), 0);
Expression[] exprs =
new Expression[] {
lessThan("id", 5),
lessThanOrEqual("id", 30),
equal("id", 70),
greaterThan("id", 78),
greaterThanOrEqual("... |
public static Long getFileLineNumberFromDir(@NonNull String dirPath) {
File file = new File(dirPath);
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files == null) {
return 0L;
}
return Arrays.stream(files)
... | @Test
public void testGetFileLineNumberFromDir() throws Exception {
String rootPath = "/tmp/test/file_utils1";
String dirPath1 = rootPath + "/dir1";
String dirPath2 = rootPath + "/dir2";
String file1 = dirPath1 + "/file1.txt";
String file2 = dirPath1 + "/file2.txt";
... |
public MethodBuilder retry(Boolean retry) {
this.retry = retry;
return getThis();
} | @Test
void retry() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.retry(true);
Assertions.assertTrue(builder.build().isRetry());
} |
public void writeIntLenenc(final long value) {
if (value < 0xfb) {
byteBuf.writeByte((int) value);
return;
}
if (value < Math.pow(2D, 16D)) {
byteBuf.writeByte(0xfc);
byteBuf.writeShortLE((int) value);
return;
}
if (valu... | @Test
void assertWriteIntLenencWithThreeBytes() {
new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).writeIntLenenc(Double.valueOf(Math.pow(2D, 24D)).longValue() - 1L);
verify(byteBuf).writeByte(0xfd);
verify(byteBuf).writeMediumLE(Double.valueOf(Math.pow(2D, 24D)).intValue() - 1);
... |
static List<String> parse(String cmdline) {
List<String> matchList = new ArrayList<>();
Matcher shellwordsMatcher = SHELLWORDS_PATTERN.matcher(cmdline);
while (shellwordsMatcher.find()) {
if (shellwordsMatcher.group(1) != null) {
matchList.add(shellwordsMatcher.group(... | @Test
void ensure_name_with_spaces_works_with_args() {
assertThat(ShellWords.parse("--name 'some Name'"), contains("--name", "some Name"));
} |
public static Expression convert(Predicate[] predicates) {
Expression expression = Expressions.alwaysTrue();
for (Predicate predicate : predicates) {
Expression converted = convert(predicate);
Preconditions.checkArgument(
converted != null, "Cannot convert Spark predicate to Iceberg expres... | @Test
public void testNotEqualToNull() {
String col = "col";
NamedReference namedReference = FieldReference.apply(col);
LiteralValue value = new LiteralValue(null, DataTypes.IntegerType);
org.apache.spark.sql.connector.expressions.Expression[] attrAndValue =
new org.apache.spark.sql.connector... |
static Serde<List<?>> createSerde(final PersistenceSchema schema) {
final List<SimpleColumn> columns = schema.columns();
if (columns.isEmpty()) {
// No columns:
return new KsqlVoidSerde<>();
}
if (columns.size() != 1) {
throw new KsqlException("The '" + FormatFactory.KAFKA.name()
... | @Test
public void shouldDeserializeNullAsNull() {
// Given:
final PersistenceSchema schema = schemaWithFieldOfType(SqlTypes.INTEGER);
final Serde<List<?>> serde = KafkaSerdeFactory.createSerde(schema);
// When:
final Object result = serde.deserializer().deserialize("topic", null);
// Then:
... |
public static int bytesToUShortBE(byte[] bytes, int off) {
return ((bytes[off] & 255) << 8) + (bytes[off + 1] & 255);
} | @Test
public void testBytesToUShortBE() {
assertEquals(-12345 & 0xffff,
ByteUtils.bytesToUShortBE(SHORT_12345_BE, 0));
} |
public Map<String, String> mergeOptions(
MergingStrategy mergingStrategy,
Map<String, String> sourceOptions,
Map<String, String> derivedOptions) {
Map<String, String> options = new HashMap<>();
if (mergingStrategy != MergingStrategy.EXCLUDING) {
options.pu... | @Test
void mergeIncludingOptionsFailsOnDuplicate() {
Map<String, String> sourceOptions = new HashMap<>();
sourceOptions.put("offset", "1");
Map<String, String> derivedOptions = new HashMap<>();
derivedOptions.put("offset", "2");
assertThatThrownBy(
(... |
@Override
public int read() throws IOException
{
checkClosed();
if (pointer >= this.size)
{
return -1;
}
if (currentBufferPointer >= chunkSize)
{
if (bufferListIndex >= bufferListMaxIndex)
{
return -1;
... | @Test
void testPDFBOX5161() throws IOException
{
try (RandomAccessRead rar = new RandomAccessReadBuffer(new ByteArrayInputStream(new byte[4099])))
{
byte[] buf = new byte[4096];
int bytesRead = rar.read(buf);
assertEquals(4096, bytesRead);
bytesRea... |
@Override
public void transform(Message message, DataType fromType, DataType toType) {
final Optional<ValueRange> valueRange = getValueRangeBody(message);
String range = message.getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A:A").toString();
String majorDimension = message
... | @Test
public void testTransformToValueRangeColumnNames() throws Exception {
Exchange inbound = new DefaultExchange(camelContext);
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", "A1:B1");
inbound.getMessage().setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "... |
public static Method getPublicMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) throws SecurityException {
return ReflectUtil.getPublicMethod(clazz, methodName, paramTypes);
} | @Test
public void getPublicMethod() {
Method superPublicMethod = ClassUtil.getPublicMethod(TestSubClass.class, "publicMethod");
assertNotNull(superPublicMethod);
Method superPrivateMethod = ClassUtil.getPublicMethod(TestSubClass.class, "privateMethod");
assertNull(superPrivateMethod);
Method publicMethod = ... |
public PreparedStatementProxy(AbstractConnectionProxy connectionProxy, PreparedStatement targetStatement,
String targetSQL) throws SQLException {
super(connectionProxy, targetStatement, targetSQL);
} | @Test
public void testPreparedStatementProxy() {
Assertions.assertNotNull(preparedStatementProxy);
Assertions.assertNotNull(unusedConstructorPreparedStatementProxy);
} |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) {
// TODO for now the node tag overhead is not worth the effort due to very few data points
// List<Map<String, Object>> nodeTags = way.getTag("node_tags", null);
Boolean b = g... | @Test
public void testTaggingMistake() {
ArrayEdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
ReaderWay way = new ReaderWay(0L);
way.setTag("highway", "road");
// ignore incomplete values
way.setTag("access:conditional", "no @ 2023 Mar-Oct");
... |
public static <T> T[] getAny(Object array, int... indexes) {
if (null == array) {
return null;
}
if (null == indexes) {
return newArray(array.getClass().getComponentType(), 0);
}
final T[] result = newArray(array.getClass().getComponentType(), indexes.length);
for (int i = 0; i < indexes.length; i++)... | @Test
public void getAnyTest() {
final String[] a = {"a", "b", "c", "d", "e"};
final Object o = ArrayUtil.getAny(a, 3, 4);
final String[] resultO = (String[]) o;
final String[] c = {"d", "e"};
assertTrue(ArrayUtil.containsAll(c, resultO[0], resultO[1]));
} |
@Override
public void append(final LogEvent event) {
if(null == event.getMessage()) {
return;
}
// Category name
final String logger = String.format("%s %s", event.getThreadName(), event.getLoggerName());
Level level = event.getLevel();
if(Level.FATAL.equa... | @Test
public void testAppend유준환() {
final UnifiedSystemLogAppender a = new UnifiedSystemLogAppender();
a.log(UnifiedSystemLogAppender.OS_LOG_TYPE_INFO, "http-유준환.txt-1", "유준환");
} |
public static void requireNonNulls(Object... objs) {
for (int i = 0; i < objs.length; i++) {
int effectivelyFinal = i;
Objects.requireNonNull(objs[i], () -> "Argument at index %d is null".formatted(effectivelyFinal));
}
} | @Test
void testNonNulls() {
assertDoesNotThrow(() -> Validation.requireNonNulls("hei", 123L, List.of("hoi")));
var exception = assertThrows(NullPointerException.class, () -> Validation.requireNonNulls("hei", null, List.of("hoi")));
assertEquals("Argument at index 1 is null", exception.getMes... |
public HttpResponse getLogs(ApplicationId applicationId, Optional<DomainName> hostname, Query apiParams) {
Exception exception = null;
for (var uri : getLogServerUris(applicationId, hostname)) {
try {
return logRetriever.getLogs(uri.withQuery(apiParams), activationTime(applic... | @Test
public void getLogsForHostname() {
ApplicationId applicationId = ApplicationId.from("hosted-vespa", "tenant-host", "default");
deployApp(testAppLogServerWithContainer, new PrepareParams.Builder().applicationId(applicationId).build());
HttpResponse response = applicationRepository.getLo... |
@Override
public ValidationResult toValidationResult(String responseBody) {
ValidationResult validationResult = new ValidationResult();
ArrayList<String> exceptions = new ArrayList<>();
try {
Map result = (Map) GSON.fromJson(responseBody, Object.class);
if (result == ... | @Test
public void shouldConvertJsonResponseToValidationResultWhenValidationPasses() {
String jsonResponse = "{}";
TaskConfig configuration = new TaskConfig();
TaskConfigProperty property = new TaskConfigProperty("URL", "http://foo");
property.with(Property.SECURE, false);
pr... |
public void convertPostRepoSave( RepositoryFile repositoryFile ) {
if ( repositoryFile != null ) {
try {
Repository repo = connectToRepository();
if ( repo != null ) {
TransMeta
transMeta =
repo.loadTransformation( new StringObjectId( repositoryFile.getId(... | @Test
public void convertPostRepoSave() throws Exception {
StreamToTransNodeConverter converter = mock( StreamToTransNodeConverter.class );
doCallRealMethod().when( converter ).convertPostRepoSave( any( RepositoryFile.class ) );
Repository repository = mock( Repository.class );
when( converter.connect... |
public static DataflowRunner fromOptions(PipelineOptions options) {
DataflowPipelineOptions dataflowOptions =
PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options);
ArrayList<String> missing = new ArrayList<>();
if (dataflowOptions.getAppName() == null) {
missing.add("appN... | @Test
public void testRegionRequiredForServiceRunner() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setRegion(null);
options.setDataflowEndpoint("https://dataflow.googleapis.com");
assertThrows(IllegalArgumentException.class, () -> DataflowRunner.fromOptions(o... |
public void close() {
directoryCache.close();
fileDistributionFactory.close();
try {
zkCacheExecutor.shutdown();
checkForRemovedApplicationsService.shutdown();
zkApplicationWatcherExecutor.shutdownAndWait();
zkSessionWatcherExecutor.shutdownAndWait... | @Test
public void testFailingBootstrap() {
tenantRepository.close(); // stop using the one setup in Before method
expectedException.expect(RuntimeException.class);
expectedException.expectMessage("Could not create all tenants when bootstrapping, failed to create: [default]");
new Fa... |
public JsonParseException(String message) {
super(message);
} | @Test
public void testJsonParseException() {
Assertions.assertThrowsExactly(JsonParseException.class, () -> {
throw new JsonParseException("error");
});
Assertions.assertThrowsExactly(JsonParseException.class, () -> {
throw new JsonParseException("error", new Throwabl... |
public static void compareProviders(List<ProviderInfo> oldList, List<ProviderInfo> newList,
List<ProviderInfo> add, List<ProviderInfo> remove) {
// 比较老列表和当前列表
if (CommonUtils.isEmpty(oldList)) {
// 空变成非空
if (CommonUtils.isNotEmpty(newList))... | @Test
public void compareProviders() throws Exception {
ProviderGroup group1 = new ProviderGroup("a");
ProviderGroup group2 = new ProviderGroup("a");
List<ProviderInfo> oldList = new ArrayList<ProviderInfo>();
List<ProviderInfo> newList = new ArrayList<ProviderInfo>();
List... |
@Override
public void setNonNullParameter(final PreparedStatement preparedStatement, final int columnIndex,
final Boolean columnValue, final JdbcType jdbcType) throws SQLException {
preparedStatement.setInt(columnIndex, columnValue ? 1 : 0);
} | @Test
public void setNonNullParameterTest() {
final OpenGaussSQLBooleanHandler openGaussSQLBooleanHandler = new OpenGaussSQLBooleanHandler();
Assertions.assertDoesNotThrow(() -> openGaussSQLBooleanHandler.setNonNullParameter(mock(PreparedStatement.class), 1, true, JdbcType.BIGINT));
} |
public static Http2Headers toHttp2Headers(HttpMessage in, boolean validateHeaders) {
HttpHeaders inHeaders = in.headers();
final Http2Headers out = new DefaultHttp2Headers(validateHeaders, inHeaders.size());
if (in instanceof HttpRequest) {
HttpRequest request = (HttpRequest) in;
... | @Test
public void stripTEHeadersCsvSeparatedAccountsForValueSimilarToTrailers() {
HttpHeaders inHeaders = new DefaultHttpHeaders();
inHeaders.add(TE, GZIP + "," + TRAILERS + "foo");
Http2Headers out = new DefaultHttp2Headers();
HttpConversionUtil.toHttp2Headers(inHeaders, out);
... |
public boolean isUnHealth(String address) {
Member member = serverList.get(address);
if (member == null) {
return false;
}
return !NodeState.UP.equals(member.getState());
} | @Test
void testIsUnHealth() {
assertFalse(serverMemberManager.isUnHealth("1.1.1.1"));
} |
void parseArgAndAppend(String entityName, String fieldName, Object arg) {
if (entityName == null || fieldName == null || arg == null) {
return;
}
if (arg instanceof Collection) {
for (Object o : (Collection<?>) arg) {
String matchedValue = String.valueOf(o);
api.appendDataInflue... | @Test
public void testParseArgAndAppendCaseNormalTypeArg() {
final String entityName = "App";
final String fieldName = "Name";
Object arg = new Object();
{
doNothing().when(api).appendDataInfluence(any(), any(), any(), any());
}
aspect.parseArgAndAppend(entityName, fieldName, arg);
... |
public NumericIndicator middle() {
return middle;
} | @Test
public void testCreation() {
final KeltnerChannelFacade facade = new KeltnerChannelFacade(data, 14, 14, 2);
assertEquals(data, facade.middle().getBarSeries());
} |
public static Path resolveRealPath(Path path) {
try {
// Get the real path by resolving all relative paths and symbolic links.
return path.toRealPath();
} catch (IOException e) {
LOG.error("Could not resolve real location of path [{}].", path, e);
}
re... | @Test
public void realPathNullWhenDoesNotExist() {
final Path path = Paths.get("non-existent-file-path");
assertNull(AllowedAuxiliaryPathChecker.resolveRealPath(path));
} |
@Override
public Space get() throws BackgroundException {
try {
final Path home = new DefaultHomeFinderService(session).find();
if(!home.isRoot()) {
if(SDSQuotaFeature.unknown == home.attributes().getQuota()) {
log.warn(String.format("No quota set ... | @Test
public void testAccount() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Quota.Space quota = new SDSQuotaFeature(session, nodeid).get();
assertNotNull(quota.available);
assertNotNull(quota.used);
} |
@Override
public Table getTable(String dbName, String tblName) {
if (!DEFAULT_DB.equalsIgnoreCase(dbName)) {
return null;
}
return toEsTable(esRestClient, properties, tblName, dbName, catalogName);
} | @Test
public void testGetTable(@Mocked EsRestClient client) {
ElasticsearchMetadata metadata = new ElasticsearchMetadata(client, new HashMap<>(), "catalog");
Assert.assertNull(metadata.getTable("default_db", "not_exist_index"));
Assert.assertNull(metadata.getTable("aaaa", "tbl"));
} |
@Override
public void rotate(IndexSet indexSet) {
indexRotator.rotate(indexSet, this::shouldRotate);
} | @Test
public void shouldRotateThrowsNPEIfIndexSetConfigIsNull() throws Exception {
when(indexSet.getConfig()).thenReturn(null);
when(indexSet.getNewestIndex()).thenReturn(IGNORED);
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("Index set confi... |
@Override
public StageBundleFactory forStage(ExecutableStage executableStage) {
return new SimpleStageBundleFactory(executableStage);
} | @Test
public void cachesEnvironment() throws Exception {
try (DefaultJobBundleFactory bundleFactory =
createDefaultJobBundleFactory(envFactoryProviderMap)) {
StageBundleFactory bf1 = bundleFactory.forStage(getExecutableStage(environment));
StageBundleFactory bf2 = bundleFactory.forStage(getExe... |
@Override
public final boolean offer(int ordinal, @Nonnull Object item) {
if (ordinal == -1) {
return offerInternal(allEdges, item);
} else {
if (ordinal == bucketCount()) {
// ordinal beyond bucketCount will add to snapshot queue, which we don't allow through... | @Test
public void when_offer4_then_rateLimited() {
do_when_offer_then_rateLimited(e -> outbox.offer(new int[] {0}, e));
} |
public StreamSummary(int capacity) {
this.capacity = capacity;
counterMap = new HashMap<T, ListNode2<Counter<T>>>();
bucketList = new DoublyLinkedList<Bucket>();
} | @Test
public void testStreamSummary() {
StreamSummary<String> vs = new StreamSummary<String>(3);
String[] stream = {"X", "X", "Y", "Z", "A", "B", "C", "X", "X", "A", "A", "A"};
for (String i : stream) {
vs.offer(i);
/*
for(String s : vs.poll(3))
System... |
@Override
public VersionedKeyValueStore<K, V> build() {
final KeyValueStore<Bytes, byte[]> store = storeSupplier.get();
if (!(store instanceof VersionedBytesStore)) {
throw new IllegalStateException("VersionedBytesStoreSupplier.get() must return an instance of VersionedBytesStore");
... | @Test
public void shouldHaveChangeLoggingStoreByDefault() {
setUp();
final VersionedKeyValueStore<String, String> store = builder.build();
assertThat(store, instanceOf(MeteredVersionedKeyValueStore.class));
final StateStore next = ((WrappedStateStore) store).wrapped();
asser... |
ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, ComponentDto mainComponentDto, BranchDto mainComponentBranchDto) {
checkState(delegate != null, "Current edition does not support branch feature");
return delegate.createBranchComponent(dbSession, componentKey, mainComponentDto,... | @Test
public void createBranchComponent_delegates_to_delegate() {
DbSession dbSession = mock(DbSession.class);
ComponentKey componentKey = mock(ComponentKey.class);
ComponentDto mainComponentDto = new ComponentDto();
ComponentDto expected = new ComponentDto();
BranchDto mainComponentBranchDto = ne... |
@CheckForNull
static BundleParams getBundleParameters(String restOfPath) {
if (restOfPath == null || restOfPath.length() == 0) {
return null;
}
String[] pathTokens = restOfPath.split("/");
List<String> bundleParameters = new ArrayList<>();
for (String pathToken ... | @Test
public void test_getBundleParameters_valid_url() {
BlueI18n.BundleParams bundleParameters = BlueI18n.getBundleParameters("/blue/rest/i18n/pluginx/1.0.0/pluginx.bundle");
Assert.assertNotNull(bundleParameters);
Assert.assertEquals("pluginx", bundleParameters.pluginName);
Assert.... |
@Override
public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) {
IdentityProvider provider = resolveProviderOrHandleResponse(request, response, INIT_CONTEXT);
if (provider != null) {
handleProvider(request, response, provider);
}
} | @Test
public void do_filter_on_basic_identity_provider() {
when(request.getRequestURI()).thenReturn("/sessions/init/" + BASIC_PROVIDER_KEY);
identityProviderRepository.addIdentityProvider(baseIdentityProvider);
underTest.doFilter(request, response, chain);
assertBasicInitCalled();
verifyNoIntera... |
public Page<ConfigHistoryInfo> listConfigHistory(String dataId, String group, String namespaceId, Integer pageNo,
Integer pageSize) {
return historyConfigInfoPersistService.findConfigHistory(dataId, group, namespaceId, pageNo, pageSize);
} | @Test
void testListConfigHistory() {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId(TEST_DATA_ID);
configHistoryInfo.setGroup(TEST_GROUP);
configHistoryInfo.setContent(TEST_CONTENT);
configHistoryInfo.setCreatedTime(new Timestamp(ne... |
public String getUuid() {
return toString();
} | @Test
public void uuidDoesNotChangeBetweenRuns() {
// Given
Uuid uuid = new Uuid();
// When
String firstUuid = uuid.getUuid();
String secondUuid = uuid.getUuid();
// Then
assertEquals(secondUuid, firstUuid);
} |
public static Builder builder() {
return new Builder(ImmutableList.of());
} | @Test
public void shouldThrowOnMultipleHeadersColumns() {
// Given:
final Builder builder = LogicalSchema.builder()
.headerColumn(H0, Optional.empty());
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> builder.headerColumn(F0, Optional.empty())
);
... |
public static InternalLogger getInstance(Class<?> clazz) {
return getInstance(clazz.getName());
} | @Test
public void testError() {
final InternalLogger logger = InternalLoggerFactory.getInstance("mock");
logger.error("a");
verify(mockLogger).error("a");
} |
protected Query<E> query(String queryString) {
return currentSession().createQuery(requireNonNull(queryString), getEntityClass());
} | @Test
void getsTypedQueries() throws Exception {
assertThat(dao.query("HQL"))
.isEqualTo(query);
verify(session).createQuery("HQL", String.class);
} |
@Override
public double p(int k) {
if (k < 0) {
return 0.0;
} else {
return gamma(r + k) / (factorial(k) * gamma(r)) * Math.pow(p, r) * Math.pow(1 - p, k);
}
} | @Test
public void testP() {
System.out.println("p");
NegativeBinomialDistribution instance = new NegativeBinomialDistribution(3, 0.3);
instance.rand();
assertEquals(0.027, instance.p(0), 1E-7);
assertEquals(0.0567, instance.p(1), 1E-7);
assertEquals(0.07938, instance.... |
@Bean
public ShenyuPlugin loggingRocketMQPlugin() {
return new LoggingRocketMQPlugin();
} | @Test
public void testLoggingRocketMQPlugin() {
applicationContextRunner
.withPropertyValues(
"debug=true",
"shenyu.logging.rocketmq.enabled=true"
)
.run(context -> {
PluginDataHandler pluginD... |
public static <E> List<E> ensureMutable(List<E> list) {
if (list instanceof ArrayList) return list;
int size = list.size();
ArrayList<E> mutable = new ArrayList<E>(size);
for (int i = 0; i < size; i++) {
mutable.add(list.get(i));
}
return mutable;
} | @Test void ensureMutable_copiesImmutable() {
List<Object> list = Collections.unmodifiableList(Arrays.asList("foo", "bar"));
assertThat(Lists.ensureMutable(list))
.isInstanceOf(ArrayList.class)
.containsExactlyElementsOf(list);
} |
public static byte[] toByteArray(long value, int length) {
final byte[] buffer = ByteBuffer.allocate(8).putLong(value).array();
for (int i = 0; i < 8 - length; i++) {
if (buffer[i] != 0) {
throw new IllegalArgumentException(
"Value is does not fit into byt... | @Test
public void toByteArrayLongShouldAFit() {
assertArrayEquals(new byte[] { 1 }, ByteArrayUtils.toByteArray(1L, 1));
} |
@Signature
@GetMapping("/orders/{orderId}")
public String getOrder(@PathVariable String orderId, @RequestParam String name, @RequestParam Integer amount){
return "success";
} | @Test
void getOrder() throws Exception {
Map<String, String[]> params = Maps.newHashMap();
params.put("name", new String[]{"iphone"});
params.put("amount", new String[]{"1"});
SignatureVo signatureVo = new SignatureVo();
signatureVo.setPath("/orders/order1");
signatu... |
public static int[] copyWithout(int[] replicas, int value) {
int size = 0;
for (int replica : replicas) {
if (replica != value) {
size++;
}
}
int[] result = new int[size];
int j = 0;
for (int replica : replicas) {
if (re... | @Test
public void testCopyWithout2() {
assertArrayEquals(new int[] {}, Replicas.copyWithout(new int[] {}, new int[] {}));
assertArrayEquals(new int[] {}, Replicas.copyWithout(new int[] {1}, new int[] {1}));
assertArrayEquals(new int[] {1, 3},
Replicas.copyWithout(new int[] {1, 2,... |
public void clear() {
for (int i = 0; i < sections.length; i++) {
sections[i].clear();
}
} | @Test
public void testClear() {
ConcurrentOpenHashSet<String> set =
ConcurrentOpenHashSet.<String>newBuilder()
.expectedItems(2)
.concurrencyLevel(1)
.autoShrink(true)
.mapIdleFactor(0.25f)
.build();
asse... |
@Override
public ExpressionEvaluatorResult evaluateUnaryExpression(String rawExpression, Object resultValue, Class<?> resultClass) {
if (isStructuredResult(resultClass)) {
return verifyResult(rawExpression, resultValue, resultClass);
} else {
return ExpressionEvaluatorResult.... | @Test
public void evaluateUnaryExpression() {
assertThat(expressionEvaluator.evaluateUnaryExpression(null, null, String.class)).is(successful);
assertThat(expressionEvaluator.evaluateUnaryExpression(null, null, Map.class)).is(successful);
assertThat(expressionEvaluator.evaluateUnaryExpressio... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
final Region region = regionService.lookup(file);
try {
if(containerService.isContainer(f... | @Test
public void testFindContainer() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final PathAttributes attributes = new SwiftAttributesFinderFeature(session).find(containe... |
public CompletableFuture<Result> getTerminationFuture() {
return terminationFuture;
} | @Test
void testWorkingDirIsNotDeletedInCaseOfFailure() throws Exception {
final File workingDirBase = TempDirUtils.newFolder(temporaryFolder);
final ResourceID resourceId = ResourceID.generate();
final Configuration configuration =
createConfigurationWithWorkingDirectory(wor... |
@Override
public HiveMetastoreClient createMetastoreClient(Optional<String> token)
throws TException
{
List<HostAndPort> metastores = new ArrayList<>(addresses);
if (metastoreLoadBalancingEnabled) {
Collections.shuffle(metastores);
}
TException lastExcept... | @Test
public void testDefaultHiveMetastore()
throws TException
{
HiveCluster cluster = createHiveCluster(CONFIG_WITH_FALLBACK, singletonList(DEFAULT_CLIENT));
assertEquals(cluster.createMetastoreClient(Optional.empty()), DEFAULT_CLIENT);
} |
@Override
public BackgroundException map(final IOException e) {
final StringBuilder buffer = new StringBuilder();
this.append(buffer, e.getMessage());
if(e instanceof FTPConnectionClosedException) {
return new ConnectionRefusedException(buffer.toString(), e);
}
if... | @Test
public void testMap() {
assertEquals(ConnectionRefusedException.class,
new FTPExceptionMappingService().map(new SocketException("Software caused connection abort")).getClass());
assertEquals(ConnectionRefusedException.class,
new FTPExceptionMappingService().map(new Sock... |
@CallSuper
protected void abortCorrectionAndResetPredictionState(boolean disabledUntilNextInputStart) {
mSuggest.resetNextWordSentence();
mLastSpaceTimeStamp = NEVER_TIME_STAMP;
mJustAutoAddedWord = false;
mKeyboardHandler.removeAllSuggestionMessages();
final InputConnection ic = getCurrentInput... | @Test
public void testStripActionRemovedWhenAbortingPrediction() {
Assert.assertNotNull(
mAnySoftKeyboardUnderTest
.getInputViewContainer()
.findViewById(R.id.close_suggestions_strip_text));
mAnySoftKeyboardUnderTest.abortCorrectionAndResetPredictionState(true);
Assert.as... |
static byte[] adaptArray(byte[] ftdiData)
{
int length = ftdiData.length;
if(length > 64)
{
int n = 1;
int p = 64;
// Precalculate length without FTDI headers
while(p < length)
{
n++;
p = n*64;
... | @Test
public void testMultiplePartial() {
byte[] withHeaders = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,... |
public void doManualTransition(DefaultIssue issue, String transitionKey, String userUuid) {
workflow.doManualTransition(issue, transitionKey, getIssueChangeContextWithUser(userUuid));
} | @Test
public void doManualTransition() {
DefaultIssue issue = new DefaultIssue();
String transitionKey = "transitionKey";
String userUuid = "userUuid";
underTest.doManualTransition(issue, transitionKey, userUuid);
verify(workflow).doManualTransition(issue, transitionKey, getIssueChangeContextWit... |
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, ... | @Test
public void unorderedFlattenIndex_empty_stream_returns_empty_map() {
assertThat(Stream.<MyObj2>empty()
.collect(unorderedFlattenIndex(MyObj2::getId, MyObj2::getTexts))
.size()).isZero();
} |
Map<String, String> describeNetworkInterfaces(List<String> privateAddresses, AwsCredentials credentials) {
if (privateAddresses.isEmpty()) {
return Collections.emptyMap();
}
try {
Map<String, String> attributes = createAttributesDescribeNetworkInterfaces(privateAddresses)... | @Test
public void describeNetworkInterfaces() {
// given
List<String> privateAddresses = asList("10.0.1.207", "10.0.1.82");
String requestUrl = "/?Action=DescribeNetworkInterfaces"
+ "&Filter.1.Name=addresses.private-ip-address"
+ "&Filter.1.Value.1=10.0.1.207"
... |
public static <T> RetryTransformer<T> of(Retry retry) {
return new RetryTransformer<>(retry);
} | @Test
public void retryOnResultFailAfterMaxAttemptsUsingObservable() throws InterruptedException {
RetryConfig config = RetryConfig.<String>custom()
.retryOnResult("retry"::equals)
.waitDuration(Duration.ofMillis(50))
.maxAttempts(3).build();
Retry retry = Retry.o... |
public double getNormalizedEditDistance(String source, String target) {
ImmutableList<String> sourceTerms = NamingConventions.splitToLowercaseTerms(source);
ImmutableList<String> targetTerms = NamingConventions.splitToLowercaseTerms(target);
// costMatrix[s][t] is the edit distance between source term s a... | @Test
public void getNormalizedEditDistance_isSymmetric_withExtraTerm() {
TermEditDistance termEditDistance = new TermEditDistance();
String identifier = "fooBarBaz";
String otherIdentifier = "barBaz";
double distanceFwd = termEditDistance.getNormalizedEditDistance(identifier, otherIdentifier);
d... |
public URI getHttpPublishUri() {
if (httpPublishUri == null) {
final URI defaultHttpUri = getDefaultHttpUri();
LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri);
return defaultHttpUri;
} else {
final InetAddress inetAddress = to... | @Test
public void testHttpPublishUriIPv6Wildcard() throws RepositoryException, ValidationException {
final Map<String, String> properties = ImmutableMap.of(
"http_bind_address", "[::]:9000",
"http_publish_uri", "http://[::]:9000/");
jadConfig.setRepository(new InMemo... |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final CountDownLatch signal = new CountDownLatch(1);
final AtomicReference<BackgroundException> failure = new AtomicReference<>();
final Sc... | @Test
public void testDeleteFiles() throws Exception {
final Path file1 = new DropboxTouchFeature(session).touch(
new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)), new TransferStatus());
final Path file... |
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 fail_to_create_query_on_quality_gate_when_value_is_incorrect() {
assertThatThrownBy(() -> {
newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(EQ).setValue("unknown").build()), emptySet());
})
.isInstanceOf(IllegalArgumentException.class)... |
static void validateCertificate(String clusterName, String clientId, X509Certificate cert, BiConsumer<String, Throwable> reporter, DeployState state) {
try {
var extensions = TBSCertificate.getInstance(cert.getTBSCertificate()).getExtensions();
if (extensions == null) return; // Certific... | @Test
void accepts_valid_certificate() {
var logger = new DeployLoggerStub();
var state = new DeployState.Builder().deployLogger(logger).build();
var cert = readTestCertificate("valid-cert.pem");
assertDoesNotThrow(() -> CloudClientsValidator.validateCertificate("default", "my-feed-c... |
@Override
public ContainersInfo getContainers(HttpServletRequest req,
HttpServletResponse res, String appId, String appAttemptId) {
// Check that the appId/appAttemptId format is accurate
try {
RouterServerUtil.validateApplicationId(appId);
RouterServerUtil.validateApplicationAttemptId(appA... | @Test
public void testGetContainers()
throws YarnException, IOException, InterruptedException {
ApplicationId appId = ApplicationId.newInstance(Time.now(), 1);
ApplicationSubmissionContextInfo context =
new ApplicationSubmissionContextInfo();
context.setApplicationId(appId.toString());
... |
public RowExpression rewriteExpression(RowExpression expression, Predicate<VariableReferenceExpression> variableScope)
{
checkArgument(determinismEvaluator.isDeterministic(expression), "Only deterministic expressions may be considered for rewrite");
return rewriteExpression(expression, variableScope... | @Test
public void testParseEqualityExpression()
{
EqualityInference inference = new EqualityInference.Builder(METADATA)
.addEquality(equals("a1", "b1"))
.addEquality(equals("a1", "c1"))
.addEquality(equals("c1", "a1"))
.build();
Ro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.