focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public byte[] encode(ILoggingEvent event) {
final int initialCapacity = event.getThrowableProxy() == null ? DEFAULT_SIZE : DEFAULT_SIZE_WITH_THROWABLE;
StringBuilder sb = new StringBuilder(initialCapacity);
sb.append(OPEN_OBJ);
if (withSequenceNumber) {
appende... | @Test
void smoke() throws JsonProcessingException {
LoggingEvent event = new LoggingEvent("x", logger, Level.WARN, "hello", null, null);
byte[] resultBytes = jsonEncoder.encode(event);
String resultString = new String(resultBytes, StandardCharsets.UTF_8);
//System.out.println(result... |
public static <T> GoConfigClassLoader<T> classParser(Element e, Class<T> aClass, ConfigCache configCache, GoCipher goCipher, final ConfigElementImplementationRegistry registry, ConfigReferenceElements configReferenceElements) {
return new GoConfigClassLoader<>(e, aClass, configCache, goCipher, registry, configR... | @Test
public void shouldErrorOutIfElementDoesNotHaveConfigTagAnnotation() {
final Element element = new Element("cruise");
final GoConfigClassLoader<ConfigWithoutAnnotation> loader = GoConfigClassLoader.classParser(element, ConfigWithoutAnnotation.class, configCache, goCipher, registry, referenceEle... |
public static RecordBuilder<Schema> record(String name) {
return builder().record(name);
} | @Test
void validateDefaultsDisabled() {
final String fieldName = "IntegerField";
final String defaultValue = "foo";
Schema schema = SchemaBuilder.record("ValidationRecord").fields().name(fieldName).notValidatingDefaults()
.type("int").withDefault(defaultValue) // Would throw an exception on endRec... |
public boolean isHealthy() {
Optional<Boolean> operatorsAreReady = areOperatorsStarted(operators);
if (operatorsAreReady.isEmpty() || !operatorsAreReady.get()) {
return false;
}
Optional<Boolean> runtimeInfosAreHealthy =
operators.stream()
.map(operator -> checkInformersHealth... | @Test
void testHealthProbeWithInformerHealthWithMultiOperators() {
HealthProbe healthyProbe = new HealthProbe(operators, Collections.emptyList());
isRunning.set(true);
assertFalse(
healthyProbe.isHealthy(),
"Healthy Probe should fail when the spark conf monitor operator is not running");
... |
public static Class<?> maxType(Class<?>... numericTypes) {
Preconditions.checkArgument(numericTypes.length >= 2);
int maxIndex = 0;
for (Class<?> numericType : numericTypes) {
int index;
if (isPrimitive(numericType)) {
index = sortedPrimitiveClasses.indexOf(numericType);
} else {
... | @Test
public void testMaxType() {
assertEquals(TypeUtils.maxType(int.class, long.class), long.class);
assertEquals(TypeUtils.maxType(long.class, int.class), long.class);
assertEquals(TypeUtils.maxType(float.class, long.class), long.class);
assertEquals(TypeUtils.maxType(long.class, float.class), long.... |
@Override
public void initialize(URI uri, Configuration conf)
throws IOException
{
requireNonNull(uri, "uri is null");
requireNonNull(conf, "conf is null");
super.initialize(uri, conf);
setConf(conf);
this.uri = URI.create(uri.getScheme() + "://" + uri.getAut... | @Test
public void testCustomCredentialsProvider()
throws Exception
{
Configuration config = new Configuration();
config.set(S3_USE_INSTANCE_CREDENTIALS, "false");
config.set(S3_CREDENTIALS_PROVIDER, TestCredentialsProvider.class.getName());
try (PrestoS3FileSystem fs ... |
@Override
public int compareTo(ByteBuf that) {
return ByteBufUtil.compare(this, that);
} | @Test
public void testCompareTo() {
try {
buffer.compareTo(null);
fail();
} catch (NullPointerException e) {
// Expected
}
// Fill the random stuff
byte[] value = new byte[32];
random.nextBytes(value);
// Prevent overflow /... |
public UriProperties(String clusterName, Map<URI, Map<Integer, PartitionData>> partitionDescriptions)
{
this(clusterName, partitionDescriptions, Collections.<URI, Map<String, Object>>emptyMap());
} | @Test
public void testUriProperties()
{
Map<URI, Map<Integer, PartitionData>> uriData = new HashMap<>();
uriData.put(URI_1, MAP_1);
uriData.put(URI_2, MAP_2);
uriData.put(URI_3, MAP_3);
String clusterName = "TestCluster";
UriProperties properties = new UriProperties(clusterName, uriData);
... |
@Override
public void putConnectorConfig(String connector, Map<String, String> properties, TargetState targetState) {
log.debug("Writing connector configuration for connector '{}'", connector);
Struct connectConfig = new Struct(CONNECTOR_CONFIGURATION_V0);
connectConfig.put("properties", pro... | @Test
public void testPutConnectorConfig() throws Exception {
when(configLog.partitionCount()).thenReturn(1);
configStorage.setupAndCreateKafkaBasedLog(TOPIC, config);
verifyConfigure();
configStorage.start();
// Null before writing
ClusterConfigState configState = ... |
protected boolean isSimpleTypeNode(JsonNode jsonNode) {
if (!jsonNode.isObject()) {
return false;
}
ObjectNode objectNode = (ObjectNode) jsonNode;
int numberOfFields = objectNode.size();
return numberOfFields == 1 && objectNode.has(VALUE);
} | @Test
public void isSimpleTypeNode_nodeWithValueFieldAndOtherField() {
ObjectNode jsonNode = new ObjectNode(factory);
jsonNode.set(VALUE, new TextNode("test"));
assertThat(expressionEvaluator.isSimpleTypeNode(jsonNode)).isTrue();
} |
@Override
public int run(String[] args) throws Exception {
YarnConfiguration yarnConf =
getConf() == null ? new YarnConfiguration() : new YarnConfiguration(
getConf());
boolean isHAEnabled =
yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED,
YarnConfiguration.DEFAULT_... | @Test
public void testNoUnsupportedHACommandsInHelp() throws Exception {
ByteArrayOutputStream dataErr = new ByteArrayOutputStream();
System.setErr(new PrintStream(dataErr));
String[] args = {};
assertEquals(-1, rmAdminCLIWithHAEnabled.run(args));
String errOut = dataErr.toString();
assertFals... |
public Matcher parse(String xpath) {
if (xpath.equals("/text()")) {
return TextMatcher.INSTANCE;
} else if (xpath.equals("/node()")) {
return NodeMatcher.INSTANCE;
} else if (xpath.equals("/descendant::node()") ||
xpath.equals("/descendant:node()")) { // f... | @Test
public void testNamedElement() {
Matcher matcher = parser.parse("/name");
assertFalse(matcher.matchesText());
assertFalse(matcher.matchesElement());
assertFalse(matcher.matchesAttribute(null, "name"));
assertFalse(matcher.matchesAttribute(NS, "name"));
assertFal... |
@Override
public ExecuteContext before(ExecuteContext context) {
Object object = context.getObject();
String serviceId = getServiceId(object).orElse(null);
if (StringUtils.isBlank(serviceId)) {
return context;
}
Object obj = context.getMemberFieldValue("serviceIns... | @Test
public void testBeforeWithInvalidObject() {
ThreadLocalUtils.setRequestData(new RequestData(Collections.emptyMap(), "", ""));
ExecuteContext context = ExecuteContext.forMemberMethod(new Object(), null, null, null, null);
interceptor.before(context);
Assert.assertNotNull(context... |
public boolean isKeyColumn(final ColumnName columnName) {
return findColumnMatching(withNamespace(Namespace.KEY).and(withName(columnName)))
.isPresent();
} | @Test
public void shouldMatchMetaColumnName() {
assertThat(SystemColumns.isPseudoColumn(ROWTIME_NAME), is(true));
assertThat(SOME_SCHEMA.isKeyColumn(ROWTIME_NAME), is(false));
} |
@Override
public void render(Node node, Appendable output) {
RendererContext context = new RendererContext(new MarkdownWriter(output));
context.render(node);
} | @Test
public void testEmphasis() {
assertRoundTrip("*foo*\n");
assertRoundTrip("foo*bar*\n");
// When nesting, a different delimiter needs to be used
assertRoundTrip("*_foo_*\n");
assertRoundTrip("*_*foo*_*\n");
assertRoundTrip("_*foo*_\n");
// Not emphasis (... |
static Object[] adjustByCoercion(Class<?>[] parameterTypes, Object[] actualParams) {
logger.trace("adjustByCoercion {} {}", parameterTypes, actualParams);
Object[] toReturn = actualParams;
int counter = Math.min(parameterTypes.length, actualParams.length);
for (int i = 0; i < counter; i+... | @Test
void adjustByCoercion() {
// no coercion needed
Object actualParam = List.of(true, false);
Class<?>[] parameterTypes = new Class[]{List.class};
Object[] actualParams = {actualParam};
Object[] retrieved = BaseFEELFunctionHelper.adjustByCoercion(parameterTypes, actualPara... |
@Override
public String symmetricEncryptType() {
return "AES";
} | @Test
public void symmetricEncryptType() {
SARSAEncrypt rsaEncrypt = new SARSAEncrypt();
Assert.assertEquals("AES", rsaEncrypt.symmetricEncryptType());
} |
public String format(AlarmEntity alarmEntity) {
StringBuilder message = new StringBuilder();
for (int i = 0; i < formatSegments.size(); i++) {
message.append(formatSegments.get(i));
if (i != formatSegments.size() - 1) {
switch (valueFroms.get(i)) {
... | @Test
public void testStringFormatWithNoArg() {
AlarmMessageFormatter formatter = new AlarmMessageFormatter("abc words {sdf");
String message = formatter.format(new AlarmEntity("SERVICE", -1, null, "", ""));
Assertions.assertEquals("abc words {sdf", message);
} |
@Override
public R apply(R record) {
final Matcher matcher = regex.matcher(record.topic());
if (matcher.matches()) {
final String topic = matcher.replaceFirst(replacement);
log.trace("Rerouting from topic '{}' to new topic '{}'", record.topic(), topic);
return rec... | @Test
public void doesntMatch() {
assertEquals("orig", apply("foo", "bar", "orig"));
} |
@Override
public long getPeriod() {
return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(30_000L);
} | @Test
public void getPeriod_returnNumberFromConfig() {
config.put("sonar.server.monitoring.ce.period", "100000");
long delay = underTest.getPeriod();
assertThat(delay).isEqualTo(100_000L);
} |
public static Protocol parse(File file) throws IOException {
try (JsonParser jsonParser = Schema.FACTORY.createParser(file)) {
return parse(jsonParser);
}
} | @Test
public void parse() throws IOException {
File fic = new File("target/test-classes/share/test/schemas/namespace.avpr");
Protocol protocol = Protocol.parse(fic);
assertNotNull(protocol);
assertEquals("TestNamespace", protocol.getName());
} |
@Override
public Flux<ReactiveRedisConnection.BooleanResponse<RenameCommand>> renameNX(Publisher<RenameCommand> commands) {
return execute(commands, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getNewName(), "New name must not be null... | @Test
public void testRenameNX() {
connection.stringCommands().set(originalKey, value).block();
if (hasTtl) {
connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block();
}
Integer originalSlot = getSlotForKey(originalKey);
newKey = getNewKeyFo... |
public static void checkURIIfPresent(@Nullable String uri,
@Nonnull Predicate<URI> predicate) throws IllegalArgumentException {
checkURIIfPresent(uri, predicate, null);
} | @Test
public void testCheckURIIfPresent() {
checkURIIfPresent(null, uri -> false);
checkURIIfPresent("", uri -> false);
checkURIIfPresent("http://pulsar.apache.org", uri -> true);
try {
checkURIIfPresent("http/pulsar.apache.org", uri -> uri.getScheme() != null, "Error");
... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
public void testDecodeMultipleStaticStructNested() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000001"
+ "000000000000000000000000000000000000000000000000000000000000000a"
+ "00000000000000000000000000... |
@Udf
public String chr(@UdfParameter(
description = "Decimal codepoint") final Integer decimalCode) {
if (decimalCode == null) {
return null;
}
if (!Character.isValidCodePoint(decimalCode)) {
return null;
}
final char[] resultChars = Character.toChars(decimalCode);
return Str... | @Test
public void shouldReturnTwoCharsForNonBMPString() {
final String result = udf.chr("\\ud800\\udc01");
assertThat(result.codePointAt(0), is(65537));
assertThat(result.toCharArray().length, is(2));
} |
private AlarmEntityId(final URI uri) {
super(uri);
} | @Test
public void validSchemaPermitted() {
alarmEntityId("none:foo");
alarmEntityId("port:foo");
alarmEntityId("och:foo");
alarmEntityId("other:foo");
} |
@Override
public int forEachByteDesc(ByteProcessor processor) {
ensureAccessible();
try {
return forEachByteDesc0(writerIndex - 1, readerIndex, processor);
} catch (Exception e) {
PlatformDependent.throwException(e);
return -1;
}
} | @Test
public void testForEachByteDesc() {
buffer.clear();
for (int i = 0; i < CAPACITY; i ++) {
buffer.writeByte(i + 1);
}
final AtomicInteger lastIndex = new AtomicInteger();
assertThat(buffer.forEachByteDesc(CAPACITY / 4, CAPACITY * 2 / 4, new ByteProcessor() {... |
public Sketch<?> merge(Sketch<?> left, Sketch<?> right) {
if (left instanceof NormalSketch && right instanceof NormalSketch) {
return mergeNormalWithNormal(asNormal(left), asNormal(right));
} else if (left instanceof NormalSketch && right instanceof SparseSketch) {
return mergeNo... | @Test
public void requireThatMergingTwoSmallSparseSketchesReturnsSparseSketch() {
SparseSketch s1 = SketchUtils.createSparseSketch(1);
SparseSketch s2 = SketchUtils.createSparseSketch(2);
Sketch<?> result = merger.merge(s1, s2);
assertEquals(result.getClass(), SparseSketch.class);
... |
@Override
public int hashCode() {
return Objects.hash(contextPath, ip, port, startupTime, healthy, enabled);
} | @Test
public void testHashCode() {
assertEquals(236671917, upstreamInstance.hashCode());
} |
public static void verifyChunkedSumsByteArray(int bytesPerSum,
int checksumType, byte[] sums, int sumsOffset, byte[] data,
int dataOffset, int dataLength, String fileName, long basePos)
throws ChecksumException {
nativeComputeChunkedSumsByteArray(bytesPerSum, checksumType,
sums, sumsOffset... | @Test
public void testVerifyChunkedSumsByteArrayFail() {
allocateArrayByteBuffers();
fillDataAndInvalidChecksums();
assertThrows(ChecksumException.class,
() -> NativeCrc32.verifyChunkedSumsByteArray(bytesPerChecksum,
checksumType.id, checksums.array(), checksums.position(),
... |
public void refreshActiveTime(String connectionId) {
Connection connection = connections.get(connectionId);
if (connection != null) {
connection.freshActiveTime();
}
} | @Test
void testRefreshActiveTime() {
try {
connectionManager.refreshActiveTime(connectId);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
} |
protected TransformerInput buildTransformerInput(List<Long> tokens, int maxTokens, boolean isQuery) {
if (!isQuery) {
tokens = tokens.stream().filter(token -> !skipTokens.contains(token)).toList();
}
List<Long> inputIds = new ArrayList<>(maxTokens);
List<Long> attentionMask =... | @Test
public void testInputTensorsWordPiece() {
// wordPiece tokenizer("this is a query !") -> [2023, 2003, 1037, 23032, 999]
List<Long> tokens = List.of(2023L, 2003L, 1037L, 23032L, 999L);
ColBertEmbedder.TransformerInput input = embedder.buildTransformerInput(tokens,10,true);
asser... |
void afterWrite(Runnable task) {
for (int i = 0; i < WRITE_BUFFER_RETRIES; i++) {
if (writeBuffer.offer(task)) {
scheduleAfterWrite();
return;
}
scheduleDrainBuffers();
Thread.onSpinWait();
}
// In scenarios where the writing threads cannot make progress then they at... | @Test @CheckMaxLogLevel(ERROR)
public void afterWrite_exception() {
var expected = new RuntimeException();
var cache = new BoundedLocalCache<Object, Object>(
Caffeine.newBuilder(), /* loader */ null, /* async */ false) {
@Override void maintenance(Runnable task) {
throw expected;
}... |
public GenericRow createRow(final KeyValue<List<?>, GenericRow> row) {
if (row.value() != null) {
throw new IllegalArgumentException("Not a tombstone: " + row);
}
final List<?> key = row.key();
if (key.size() < keyIndexes.size()) {
throw new IllegalArgumentException("Not enough key columns.... | @Test
public void shouldThrowIfDataRowNotATombstone() {
// Given:
final KeyValue<List<?>, GenericRow> kv = KeyValue.keyValue(
ImmutableList.of(4, 2),
genericRow(1, 2, 3, 4, 5)
);
// When/Then:
assertThrows(
IllegalArgumentException.class,
() -> factory.createRow(kv... |
@Override
public void refreshTable(String srDbName, Table table, List<String> partitionNames, boolean onlyCachedPartitions) {
OdpsTableName odpsTableName = OdpsTableName.of(srDbName, table.getName());
tableCache.invalidate(odpsTableName);
get(tableCache, odpsTableName);
if (!table.is... | @Test
public void testRefreshTable() {
Table odpsTable = odpsMetadata.getTable("project", "tableName");
// mock schema change
when(table.getSchema()).thenReturn(new TableSchema());
Table cacheTable = odpsMetadata.getTable("project", "tableName");
Assert.assertTrue(cacheTable... |
public static String sanitize(final String s) {
return s.replace(':', '-')
.replace('_', '-')
.replace('.', '-')
.replace('/', '-')
.replace('\\', '-');
} | @Test
public void testNotFileFriendlySimpleSanitized() {
String out = StringHelper.sanitize("c:\\helloworld");
assertEquals(-1, out.indexOf(':'), "Should not contain : ");
assertEquals(-1, out.indexOf('.'), "Should not contain . ");
} |
public RelDataType createRelDataTypeFromSchema(Schema schema) {
Builder builder = new Builder(this);
boolean enableNullHandling = schema.isEnableColumnBasedNullHandling();
for (Map.Entry<String, FieldSpec> entry : schema.getFieldSpecMap().entrySet()) {
builder.add(entry.getKey(), toRelDataType(entry.g... | @Test(dataProvider = "relDataTypeConversion")
public void testNotNullableArrayTypes(FieldSpec.DataType dataType, RelDataType arrayType, boolean columnNullMode) {
TypeFactory typeFactory = new TypeFactory();
Schema testSchema = new Schema.SchemaBuilder()
.addDimensionField("col", dataType, field -> {
... |
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback)
{
//This code path cannot accept content types or accept types that contain
//multipart/related. This is because these types of requests will usually have very large payloads and therefor... | @Test
public void testRestRequestAttemptVerifyParseFailed() throws Exception
{
//This test verifies that a RestRequest sent to the RestLiServer throws an exception if the content type or accept types
//fail to parse properly. This occurs when we try to verify that the request's content type or accept types ... |
public static int wrappedReadForCompressedData(InputStream is, byte[] buf,
int off, int len) throws IOException {
try {
return is.read(buf, off, len);
} catch (IOException ie) {
throw ie;
} catch (Throwable t) {
throw new IOException("Error while reading compressed data", t);
}
... | @Test
public void testWrappedReadForCompressedData() throws IOException {
byte[] buf = new byte[2];
InputStream mockStream = Mockito.mock(InputStream.class);
Mockito.when(mockStream.read(buf, 0, 1)).thenReturn(1);
Mockito.when(mockStream.read(buf, 0, 2)).thenThrow(
new java.lang.InternalError(... |
public static File saveKarateJson(String targetDir, FeatureResult result, String fileName) {
if (fileName == null) {
fileName = result.getFeature().getKarateJsonFileName();
}
File file = new File(targetDir + File.separator + fileName);
FileUtils.writeToFile(file, JsonUtils.to... | @Test
void testReport() {
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
final PrintStream originalOut = System.out;
Feature feature = Feature.read("classpath:com/intuit/karate/report/test.feature");
FeatureRuntime fr = FeatureRuntime.of(feature);
fr.ru... |
public static Timestamp toTimestamp(String timestampString) {
try {
return Timestamp.valueOf(timestampString);
} catch (Exception e) {
// Try the next format
}
try {
return new Timestamp(Long.parseLong(timestampString));
} catch (Exception e) {
}
try {
return Timestam... | @Test
public void testValidTimestampFormats() {
// Test ISO8601 variations with and without milliseconds and timezones
assertEquals(
TimestampUtils.toTimestamp("2024-07-12T15:32:36Z"),
Timestamp.from(LocalDateTime.of(2024, 7, 12, 15, 32, 36).atZone(ZoneOffset.UTC).toInstant()));
assertEqua... |
public Collection<StreamsMetadata> getAllMetadata() {
return Collections.unmodifiableList(allMetadata);
} | @Test
public void shouldNotReturnMutableReferenceToInternalAllMetadataCollection() {
final Collection<StreamsMetadata> allMetadata = metadataState.getAllMetadata();
assertFalse(allMetadata.isEmpty(), "invalid test");
try {
// Either this should not affect internal state of 'meta... |
private static Map<String, Set<Dependency>> checkOptionalFlags(
Map<String, Set<Dependency>> bundledDependenciesByModule,
Map<String, DependencyTree> dependenciesByModule) {
final Map<String, Set<Dependency>> allViolations = new HashMap<>();
for (String module : bundledDependen... | @Test
void testNonBundledDependencyIsIgnoredEvenIfOthersAreBundled() {
final Dependency dependencyA = createMandatoryDependency("a");
final Dependency dependencyB = createMandatoryDependency("B");
final Set<Dependency> bundled = Collections.singleton(dependencyB);
final DependencyTre... |
@Override
public String buildContext() {
final String metaData = ((Collection<?>) getSource())
.stream()
.map(s -> ((MetaDataDO) s).getAppName())
.collect(Collectors.joining(","));
return String.format("the meta data [%s] is %s", metaData, StringUtils.... | @Test
public void batchMetaDataDeletedContextTest() {
BatchMetaDataDeletedEvent batchMetaDataChangedEvent =
new BatchMetaDataDeletedEvent(Arrays.asList(one, two), "test-operator");
String context = String.format("the meta data [%s] is %s",
"testAppNameOne,testAppName... |
@Udf(description = "Returns the hyperbolic tangent of an INT value")
public Double tanh(
@UdfParameter(
value = "value",
description = "The value in radians to get the hyperbolic tangent of."
) final Integer value
) {
return tanh(value == null ? null : val... | @Test
public void shouldHandleZero() {
assertThat(udf.tanh(0.0), closeTo(0.0, 0.000000000000001));
assertThat(udf.tanh(0), closeTo(0.0, 0.000000000000001));
assertThat(udf.tanh(0L), closeTo(0.0, 0.000000000000001));
} |
public IssueQuery create(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone());
Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules());
Collection<String> rule... | @Test
public void param_componentUuids_enables_search_by_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
SearchRequest request = new SearchRequest()
.setComponentUuids(asList(fi... |
public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry) {
return custom(metricRegistry, METHOD_ONLY);
} | @Test
public void registersExpectedMetricsGivenNameStrategy() throws Exception {
client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build();
client.start();
final SimpleHttpRequest request = SimpleRequestBuilder
.get("h... |
@Override
public <T> List<T> toList(DataTable dataTable, Type itemType) {
requireNonNull(dataTable, "dataTable may not be null");
requireNonNull(itemType, "itemType may not be null");
if (dataTable.isEmpty()) {
return emptyList();
}
ListOrProblems<T> result = to... | @Test
void to_list_of_unknown_type__throws_exception() {
DataTable table = parse("",
" | firstName | lastName | birthDate |",
" | Annie M. G. | Schmidt | 1911-03-20 |",
" | Roald | Dahl | 1916-09-13 |",
" | Astrid | Lindgren | 1907-11-14 |")... |
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_language_using_eq_operator_and_values() {
assertThatThrownBy(() -> {
newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(EQ).setValues(asList("java")).build()), emptySet());
})
.isInstanceOf(IllegalArgumentException.cl... |
@VisibleForTesting
WxMpService getWxMpService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMpService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MP.getType(), userType);
if (client != null && Objects.equals(client.getSta... | @Test
public void testGetWxMpService_clientNull() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 方法
// 调用
WxMpService result = socialClientService.getWxMpService(userType);
// 断言
assertSame(wxMpService, result);
} |
public static FullyQualifiedKotlinType convert(FullyQualifiedJavaType javaType) {
FullyQualifiedKotlinType kotlinType = convertBaseType(javaType);
for (FullyQualifiedJavaType argument : javaType.getTypeArguments()) {
kotlinType.addTypeArgument(convert(argument));
}
return k... | @Test
void testUnmappedType() {
FullyQualifiedJavaType jt = new FullyQualifiedJavaType("java.math.BigDecimal");
FullyQualifiedKotlinType kt = JavaToKotlinTypeConverter.convert(jt);
assertThat(kt.getShortNameWithTypeArguments()).isEqualTo("BigDecimal");
assertThat(kt.getImportList())... |
public static String parse(String version) {
if (startsWith(version, "1.")) {
Matcher m = JAVA_VERSION_1_X.matcher(version);
m.find();
return m.group();
} else {
Matcher m = JAVA_VERSION_X.matcher(version);
m.find();
return m.group(... | @Test
public void testParse() {
assertThat(JavaVersion.parse("1.8.0_362"), is("1.8"));
assertThat(JavaVersion.parse("11.0.18"), is("11"));
assertThat(JavaVersion.parse("9.0.4"), is("9"));
assertThat(JavaVersion.parse("10.0.1"), is("10"));
} |
public static String extractCharset(String line, String defaultValue) {
if (line == null) {
return defaultValue;
}
final String[] parts = line.split(" ");
String charsetInfo = "";
for (var part : parts) {
if (part.startsWith("charset")) {
... | @DisplayName("with more items than expected")
@Test
void testExtractCharsetWithMoreItems() {
assertEquals("UTF-8", TelegramAsyncHandler.extractCharset("Content-Type: text/plain; charset=UTF-8; name=\"some-name\"",
StandardCharsets.US_ASCII.name()));
} |
public static String findAddress(List<NodeAddress> addresses, NodeAddressType preferredAddressType) {
if (addresses == null) {
return null;
}
Map<String, String> addressMap = addresses.stream()
.collect(Collectors.toMap(NodeAddress::getType, NodeAddress::getAddres... | @Test
public void testFindAddressWithAddressType() {
String address = NodeUtils.findAddress(ADDRESSES, NodeAddressType.INTERNAL_DNS);
assertThat(address, is("my.internal.address"));
} |
public String map(AmountRequest request) {
if (request instanceof OffsetBasedPageRequest && ((OffsetBasedPageRequest) request).getOffset() > 0L) {
return sqlOffsetBasedPageRequestMapper.mapToSqlQuery((OffsetBasedPageRequest) request, jobTable);
} else {
return sqlAmountRequestMap... | @Test
void sqlJobPageRequestMapperMapsAmountBasedPageRequest() {
AmountRequest amountRequest = Paging.AmountBasedList.ascOnUpdatedAt(10);
String filter = jobPageRequestMapper.map(amountRequest);
assertThat(filter).isEqualTo(" ORDER BY updatedAt ASC LIMIT :limit");
} |
@Override
public Collection<ExecuteAwarePlugin> getExecuteAwarePluginList() {
return mainLock.applyWithReadLock(executeAwarePluginList::getPlugins);
} | @Test
public void testGetExecuteAwarePluginList() {
manager.register(new TestExecuteAwarePlugin());
Assert.assertEquals(1, manager.getExecuteAwarePluginList().size());
} |
public List<Map<String, Object>> toListMap(final String json) {
return GSON.fromJson(json, new TypeToken<List<Map<String, Object>>>() {
}.getType());
} | @Test
public void testToListMap() {
Map<String, Object> map = ImmutableMap.of("id", "123", "name", "test", "data", "测试");
List<Map<String, Object>> list = ImmutableList.of(ImmutableMap.copyOf(map), ImmutableMap.copyOf(map),
ImmutableMap.copyOf(map));
String json = "[{\"name\... |
@Override
public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication,
long blockSize, Progressable progress) throws IOException {
String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK);
Mode mode =... | @Test
public void initializeWithFullPrincipalUgi() throws Exception {
mockUserGroupInformation("testuser@ALLUXIO.COM");
final org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "host:1");
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// FileSystem.cre... |
@Override
public boolean ownDeletesAreVisible(final int type) {
return false;
} | @Test
void assertOwnDeletesAreVisible() {
assertFalse(metaData.ownDeletesAreVisible(0));
} |
@Override
public DefaultSchedulingPipelinedRegion getPipelinedRegionOfVertex(
final ExecutionVertexID vertexId) {
checkNotNull(pipelinedRegionsByVertex);
final DefaultSchedulingPipelinedRegion pipelinedRegion =
pipelinedRegionsByVertex.get(vertexId);
if (pipeline... | @Test
void testGetPipelinedRegionOfVertex() {
for (DefaultExecutionVertex vertex : adapter.getVertices()) {
final DefaultSchedulingPipelinedRegion pipelinedRegion =
adapter.getPipelinedRegionOfVertex(vertex.getId());
assertRegionContainsAllVertices(pipelinedRegion... |
Collection<AzureAddress> getAddresses() {
LOGGER.finest("Fetching OAuth Access Token");
final String accessToken = fetchAccessToken();
LOGGER.finest("Fetching instances for subscription '%s' and resourceGroup '%s'",
subscriptionId, resourceGroup);
Collection<AzureAddress>... | @Test
public void getAddressesWithConfiguredSettings() {
// given
String tenantId = "tenant-id";
String clientId = "client-id";
String clientSecret = "client-secret";
given(azureAuthenticator.refreshAccessToken(tenantId, clientId, clientSecret)).willReturn(ACCESS_TOKEN);
... |
public HtmlCreator addRowToTable(List<String> rowElements) {
html.append("<tr>");
rowElements.forEach((re) -> html.append("<td>").append(re).append("</td>"));
html.append("</tr>");
return this;
} | @Test
public void testAddRowToTable() {
htmlCreator.addRowToTable(Arrays.asList("name", "age"));
Assert.assertEquals(true, htmlCreator.html().contains("<td>name</td><td>age</td>"));
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema != null && schema.type() != Schema.Type.BYTES)
throw new DataException("Invalid schema type for ByteArrayConverter: " + schema.type().toString());
if (value != null && !(value instanceof byte... | @Test
public void testFromConnectSchemaless() {
assertArrayEquals(
SAMPLE_BYTES,
converter.fromConnectData(TOPIC, null, SAMPLE_BYTES)
);
} |
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
// Automatically detect the character encoding
try (AutoDetectReader reader = new AutoDetectReader(CloseShieldInpu... | @Test
public void testEmptyText() throws Exception {
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
parser.parse(new ByteArrayInputStream(new byte[0]), handler, metadata, new ParseContext());
assertEquals("text/plain; charset=UTF-8", metadata.g... |
@Override
public void updateSecurityGroup(KubevirtSecurityGroup sg) {
checkNotNull(sg, ERR_NULL_SG);
checkArgument(!Strings.isNullOrEmpty(sg.id()), ERR_NULL_SG_ID);
sgStore.updateSecurityGroup(sg);
} | @Test(expected = IllegalArgumentException.class)
public void testUpdateUnregisteredSecurityGroup() {
target.updateSecurityGroup(sg1);
} |
@VisibleForTesting
Map<String, List<Operation>> computeOperations(SegmentDirectory.Reader segmentReader)
throws Exception {
Map<String, List<Operation>> columnOperationsMap = new HashMap<>();
// Does not work for segment versions < V3.
if (_segmentDirectory.getSegmentMetadata().getVersion().compare... | @Test
public void testComputeOperationChangeCompression()
throws Exception {
// Setup
SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory);
SegmentDirectory segmentLocalFSDirectory =
new SegmentLocalFSDirectory(_segmentDirectory, existingSegmentMetadata, R... |
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为此时不知道 id 对应的 permission 是多少。直接清理,简单有效
public void deleteMenu(Long id) {
// 校验是否还有子菜单
if (menuMapper.selectCountByParent... | @Test
public void testDeleteMenu_existChildren() {
// mock 数据(构造父子菜单)
MenuDO sonMenu = createParentAndSonMenu();
// 准备参数
Long parentId = sonMenu.getParentId();
// 调用并断言异常
assertServiceException(() -> menuService.deleteMenu(parentId), MENU_EXISTS_CHILDREN);
} |
public static ScheduledFuture<?> scheduleLongPolling(Runnable runnable, long period, TimeUnit unit) {
return LONG_POLLING_EXECUTOR.schedule(runnable, period, unit);
} | @Test
public void scheduleLongPollingTest() {
ConfigExecutor.scheduleLongPolling(() -> log.info(Thread.currentThread().getName()), 5, TimeUnit.SECONDS);
} |
@Deprecated
public String resolveDefaultAddress() {
return this.resolveDefaultAddress(true);
} | @Test
public void testResolveDefaultAddress() {
AmazonInfo info = (AmazonInfo) instanceInfo.getDataCenterInfo();
config = createConfig(info);
assertThat(config.resolveDefaultAddress(false), is(info.get(publicHostname)));
info.getMetadata().remove(publicHostname.getName());
c... |
@Override
public Map<String, String> getRemoteRegionUrlsWithName() {
String propName = namespace + "remoteRegionUrlsWithName";
String remoteRegionUrlWithNameString = configInstance.getStringProperty(propName, null).get();
if (null == remoteRegionUrlWithNameString) {
return Collec... | @Test
public void testRemoteRegionUrlsWithName1Region() throws Exception {
String region1 = "myregion1";
String region1url = "http://local:888/eee";
ConfigurationManager.getConfigInstance().setProperty("eureka.remoteRegionUrlsWithName", region1
+ ';' + region1url);
De... |
@VisibleForTesting
static boolean validateArenaBlockSize(long arenaBlockSize, long mutableLimit) {
return arenaBlockSize <= mutableLimit;
} | @Test
public void testValidateArenaBlockSize() {
long arenaBlockSize = 8 * 1024 * 1024;
assertFalse(
RocksDBMemoryControllerUtils.validateArenaBlockSize(
arenaBlockSize, (long) (arenaBlockSize * 0.5)));
assertTrue(
RocksDBMemoryControll... |
@Udf(description = "Returns the inverse (arc) tangent of y / x")
public Double atan2(
@UdfParameter(
value = "y",
description = "The ordinate (y) coordinate."
) final Integer y,
@UdfParameter(
value = "x",
descriptio... | @Test
public void shouldHandleZeroYZeroX() {
assertThat(udf.atan2(0.0, 0.0), closeTo(0.0, 0.000000000000001));
assertThat(udf.atan2(0.0, 0.0), closeTo(0.0, 0.000000000000001));
assertThat(udf.atan2(0, 0), closeTo(0.0, 0.000000000000001));
assertThat(udf.atan2(0L, 0L), closeTo(0.0, 0.000000000000001));... |
private ResultUtil() {
} | @Test
public void testResultUtil() {
Assertions.assertNotNull(ResultUtil.ok());
Assertions.assertNotNull(ResultUtil.ok(new Object()));
Assertions.assertNotNull(ResultUtil.ok(new Object(), "success"));
} |
@Override
public void writeObject(Object object) throws IOException {
serializationService.writeObject(this, object);
} | @Test
public void testWriteObject() throws Exception {
dataOutputStream.writeObject("INPUT");
verify(mockSerializationService).writeObject(dataOutputStream, "INPUT");
} |
public void logResponse(Config config, HttpRequest request, Response response) {
long startTime = request.getStartTime();
long elapsedTime = request.getEndTime() - startTime;
response.setResponseTime(elapsedTime);
StringBuilder sb = new StringBuilder();
String uri = request.getUr... | @Test
void testResponseLoggingXmlPretty() {
config.configure("logPrettyResponse", new Variable(true));
setup("xml", "<hello>world</hello>", "application/xml");
httpRequestBuilder.path("/xml");
Response response = handle();
match(response.getBodyAsString(), "<hello>world</hell... |
@Override
public Cancellable schedule(final Duration interval, final PunctuationType type, final Punctuator callback) {
throw new UnsupportedOperationException("StateStores can't access schedule.");
} | @Test
public void shouldThrowOnScheduleWithDuration() {
assertThrows(UnsupportedOperationException.class, () -> context.schedule(Duration.ZERO, PunctuationType.WALL_CLOCK_TIME, punctuator));
} |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetName() {
assertEquals("Analyzer name wrong.", "Autoconf Analyzer",
analyzer.getName());
} |
@Override
public String toString() {
String text = this.text;
if (text == null) {
// E.g.: "1000 Bye", "1009 Message too big"
this.text = text = code() + " " + reasonText();
}
return text;
} | @Test
public void testToString() {
assertEquals("1000 Bye", NORMAL_CLOSURE.toString());
} |
public static Read read() {
return new Read(null, "", new Scan());
} | @Test
public void testReadingFailsTableDoesNotExist() {
final String table = tmpTable.getName();
// Exception will be thrown by read.expand() when read is applied.
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(String.format("Table %s does not exist", table));
runReadTest(
... |
@Override
public void setConfigAttributes(Object attributes) {
setConfigAttributes(attributes, null);
} | @Test
public void shouldAssignApprovalTypeOnFirstStageAsManual() {
Map<String, Object> approvalAttributes = Map.of(Approval.TYPE, Approval.MANUAL);
Map<String, Map<String, Object>> map = Map.of(StageConfig.APPROVAL, approvalAttributes);
PipelineConfig pipelineConfig = PipelineConfigMother.cr... |
public static <K, V> V removeKey(Map<K, V> map, K key, Predicate<V> removeJudge) {
return map.computeIfPresent(key, (k, v) -> removeJudge.test(v) ? null : v);
} | @Test
void testRemoveKey() {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
MapUtil.removeKey(map, "B", integer -> integer == 1);
assertEquals(3, map.size());
MapUtil.removeKey(map, "B", integer -> integ... |
public static void addBlockCacheUsageMetric(final StreamsMetricsImpl streamsMetrics,
final RocksDBMetricContext metricContext,
final Gauge<BigInteger> valueProvider) {
addMutableMetric(
streamsMetrics,
... | @Test
public void shouldAddBlockCacheUsageMetric() {
final String name = "block-cache-usage";
final String description = "Memory size of the entries residing in block cache in bytes";
runAndVerifyMutableMetric(
name,
description,
() -> RocksDBMetrics.addBl... |
public String normalize(final String name) {
if(StringUtils.equals(name, ".")) {
return finder.find().getAbsolute();
}
if(StringUtils.equals(name, "..")) {
return finder.find().getParent().getAbsolute();
}
if(!this.isAbsolute(name)) {
return St... | @Test
public void testCurrentDir() {
assertEquals(System.getProperty("user.dir"), new WorkdirPrefixer().normalize("."));
} |
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload,
final ConnectionSession connectionSession) {
switch (commandPacketType) {
case COM_QUIT:
return new MySQLCom... | @Test
void assertNewInstanceWithComRegisterSlavePacket() {
assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_REGISTER_SLAVE, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class));
} |
static Collection<String> findIssueKeys(String input, Pattern pattern) {
Matcher m = pattern.matcher(input);
Set<String> issues = new HashSet<>();
while (m.find()) {
if (m.groupCount() >= 1) {
String id = m.group(1);
issues.add(id);
}
... | @Test
public void findIssueKeys() throws MalformedURLException {
Pattern issuePattern = JiraSite.DEFAULT_ISSUE_PATTERN;
Assert.assertEquals(Collections.singleton("JENKINS-43400"), BlueJiraIssue.findIssueKeys( "[JENKINS-43400] Print the error to the build log rather than", issuePattern));
Ass... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
public void testNoOldTransformInRecentVersion() {
pipeline.enableAbandonedNodeEnforcement(false);
pipeline.getOptions().as(StreamingOptions.class).setUpdateCompatibilityVersion("2.54.0");
pipeline.apply(Create.of(KV.of("arbitrary", "kv"))).apply(Reshuffle.of());
OldTransformSeeker seeker = new ... |
public static HttpRespStatus valueOf(int code) {
HttpRespStatus status = valueOf0(code);
return status != null ? status : new HttpRespStatus(code);
} | @Test
public void testValueOf() {
Assert.assertEquals(CONTINUE, HttpRespStatus.valueOf(100));
Assert.assertEquals(OK, HttpRespStatus.valueOf(200));
Assert.assertEquals(MULTIPLE_CHOICES, HttpRespStatus.valueOf(300));
Assert.assertEquals(MOVED_PERMANENTLY, HttpRespStatus.valueOf(301));... |
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/21068)
})
/*
* Returns an iterables containing all distinct keys in this multimap.
*/
public PrefetchableIterable<K> keys() {
checkState(
!isClosed,
"Multimap user state is no longer usable because it is clo... | @Test
public void testGetKeysPrefetch() throws Exception {
FakeBeamFnStateClient fakeClient =
new FakeBeamFnStateClient(
ImmutableMap.of(
createMultimapKeyStateKey(),
KV.of(ByteArrayCoder.of(), singletonList(A1)),
createMultimapValueStateKey(A1),... |
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if (StringUtils.isBlank(msg)) {
ctx.writeAndFlush(QosProcessHandler.PROMPT);
} else {
CommandContext commandContext = TelnetCommandDecoder.decode(msg);
commandContext.... | @Test
void testUnknownCommand() throws Exception {
ChannelHandlerContext context = mock(ChannelHandlerContext.class);
TelnetProcessHandler handler = new TelnetProcessHandler(
FrameworkModel.defaultModel(), QosConfiguration.builder().build());
handler.channelRead0(context, "un... |
@Override protected void render(Block html) {
String jid = $(JOB_ID);
if (jid.isEmpty()) {
html.
p().__("Sorry, can't do anything without a JobID.").__();
return;
}
JobId jobID = MRApps.toJobID(jid);
Job j = appContext.getJob(jobID);
if (j == null) {
html.p().__("Sorry,... | @Test
public void testHsJobBlockForNormalSizeJobShouldNotDisplayWarningMessage() {
Configuration config = new Configuration();
config.setInt(JHAdminConfig.MR_HS_LOADED_JOBS_TASKS_MAX, -1);
JobHistory jobHistory = new JobHitoryStubWithAllNormalSizeJobs();
jobHistory.init(config);
HsJobBlock jobB... |
public static <K, V> MutableMultimap<K, V> groupBy(
Iterable<V> iterable,
Function<? super V, ? extends K> function)
{
return FJIterate.groupBy(iterable, function, FJIterate.DEFAULT_MIN_FORK_SIZE, FJIterate.FORK_JOIN_POOL);
} | @Test
public void groupByWithInterval()
{
LazyIterable<Integer> iterable = Interval.oneTo(1000).concatenate(Interval.oneTo(1000)).concatenate(Interval.oneTo(1000));
Multimap<String, Integer> expected = iterable.toBag().groupBy(Functions.getToString());
Multimap<String, Integer> expectedA... |
@ProtoFactory
public static MediaType fromString(String tree) {
if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType();
Matcher matcher = TREE_PATTERN.matcher(tree);
return parseSingleMediaType(tree, matcher, false);
} | @Test(expected = EncodingException.class)
public void testParsingWhitespaceInParamName() {
MediaType.fromString("application/json; charset =utf-8");
} |
public FEELFnResult<BigDecimal> invoke(@ParameterName( "n" ) BigDecimal n) {
return invoke(n, BigDecimal.ZERO);
} | @Test
void invokeOutRangeScale() {
FunctionTestUtil.assertResultError(floorFunction.invoke(BigDecimal.valueOf(1.5), BigDecimal.valueOf(6177)), InvalidParametersEvent.class);
FunctionTestUtil.assertResultError(floorFunction.invoke(BigDecimal.valueOf(1.5), BigDecimal.valueOf(-6122)), InvalidParameters... |
@Override
public void execute(final List<String> args, final PrintWriter terminal) {
CliCmdUtil.ensureArgCountBounds(args, 1, 1, HELP);
final String filePath = args.get(0);
final String content = loadScript(filePath);
requestExecutor.makeKsqlRequest(content);
} | @Test
public void shouldThrowIfFileDoesNotExist() {
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> cmd.execute(ImmutableList.of("you-will-not-find-me"), terminal)
);
// Then:
assertThat(e.getMessage(), containsString(
"Failed to read file: you-will-n... |
public static String encode(byte[] data) {
return Base58Codec.INSTANCE.encode(data);
} | @Test
public void encodeTest() {
String a = "hello world";
String encode = Base58.encode(a.getBytes(StandardCharsets.UTF_8));
assertEquals("StV1DL6CwTryKyV", encode);
} |
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) {
return Optional.ofNullable(HANDLERS.get(step.getClass()))
.map(h -> h.handle(this, schema, step))
.orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass()));
} | @Test
public void shouldResolveSchemaForTableSelectKey() {
// Given:
final UnqualifiedColumnReferenceExp keyExpression1 =
new UnqualifiedColumnReferenceExp(ColumnName.of("ORANGE"));
final UnqualifiedColumnReferenceExp keyExpression2 =
new UnqualifiedColumnReferenceExp(ColumnName.of("APPLE"... |
public static <T> PCollections<T> pCollections() {
return new PCollections<>();
} | @Test
@Category(ValidatesRunner.class)
public void testFlattenPCollectionsEmpty() {
PCollection<String> output =
PCollectionList.<String>empty(p)
.apply(Flatten.pCollections())
.setCoder(StringUtf8Coder.of());
PAssert.that(output).empty();
p.run();
} |
@Udf(description = "Returns the inverse (arc) sine of an INT value")
public Double asin(
@UdfParameter(
value = "value",
description = "The value to get the inverse sine of."
) final Integer value
) {
return asin(value == null ? null : value.doubleValue())... | @Test
public void shouldHandleZero() {
assertThat(udf.asin(0.0), closeTo(0.0, 0.000000000000001));
assertThat(udf.asin(0), closeTo(0.0, 0.000000000000001));
assertThat(udf.asin(0L), closeTo(0.0, 0.000000000000001));
} |
public static Table loadTable(Configuration conf) {
return loadTable(
conf,
conf.get(InputFormatConfig.TABLE_IDENTIFIER),
conf.get(InputFormatConfig.TABLE_LOCATION),
conf.get(InputFormatConfig.CATALOG_NAME));
} | @Test
public void testLoadTableFromLocation() throws IOException {
conf.set(CatalogUtil.ICEBERG_CATALOG_TYPE, Catalogs.LOCATION);
assertThatThrownBy(() -> Catalogs.loadTable(conf))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Table location not set");
HadoopTables tables = ... |
@SuppressWarnings("unchecked")
public String fileLink(String path) throws IOException, InvalidTokenException {
String url;
try {
url =
getUriBuilder()
.setPath(API_PATH_PREFIX + "/mounts/primary/files/download")
.setParameter("path", path)
.build()
... | @Test
public void testFileLink() throws Exception {
server.enqueue(
new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "application/json")
.setBody(
"{\"link\":\"https://app-1.koofr.net/content/files/get/Video+1.mp4?base=TESTBASE\"}"));
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.