focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
protected GelfMessage toGELFMessage(final Message message) {
final DateTime timestamp;
final Object fieldTimeStamp = message.getField(Message.FIELD_TIMESTAMP);
if (fieldTimeStamp instanceof DateTime) {
timestamp = (DateTime) fieldTimeStamp;
} else {
timestamp = To... | @Test
public void testToGELFMessageWithInvalidTypeLevel() throws Exception {
final GelfTransport transport = mock(GelfTransport.class);
final GelfOutput gelfOutput = new GelfOutput(transport);
final DateTime now = DateTime.now(DateTimeZone.UTC);
final Message message = messageFactory... |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void bootstrapFailed() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/logs/bootstrap.txt")),
CrashReportAnalyzer.Rule.BOOTSTRAP_FAILED);
assertEquals("prefab", result.getMatcher().group("id... |
@Override
public Object[] toArray() {
return rawList.toArray();
} | @Test
public void toArrayTest() {
String jsonStr = FileUtil.readString("exam_test.json", CharsetUtil.CHARSET_UTF_8);
JSONArray array = JSONUtil.parseArray(jsonStr);
//noinspection SuspiciousToArrayCall
Exam[] list = array.toArray(new Exam[0]);
assertNotEquals(0, list.length);
assertSame(Exam.class, list[0... |
@Override
public Result apply(PathData item, int depth) throws IOException {
String name = getPath(item).getName();
if (!caseSensitive) {
name = StringUtils.toLowerCase(name);
}
if (globPattern.matches(name)) {
return Result.PASS;
} else {
return Result.FAIL;
}
} | @Test
public void applyGlobNotMatch() throws IOException {
setup("n*e");
PathData item = new PathData("/directory/path/notmatch", mockFs.getConf());
assertEquals(Result.FAIL, name.apply(item, -1));
} |
@Override
public FilterRegistration.Dynamic addFilter(String name, String filterClass) {
try {
Class<?> newFilterClass = getClassLoader().loadClass(filterClass);
if (!Filter.class.isAssignableFrom(newFilterClass)) {
throw new IllegalArgumentException(filterClass + " d... | @Test
void addFilter_doesNotImplementFilter_expectException() {
AwsServletContext ctx = new AwsServletContext(null);
try {
ctx.addFilter("filter", this.getClass().getName());
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().startsWith(this.getClass().g... |
static String convertEnvVars(String input){
// check for any non-alphanumeric chars and convert to underscore
// convert to upper case
if (input == null) {
return null;
}
return input.replaceAll("[^A-Za-z0-9]", "_").toUpperCase();
} | @Test
public void testConvertEnvVarsUsingDotInValueWithCamelCasing() {
String testInput = ConfigInjection.convertEnvVars("server.ENVIRONMENT");
Assert.assertEquals("SERVER_ENVIRONMENT", testInput);
} |
public static Coder<SdkHttpMetadata> sdkHttpMetadataWithoutHeaders() {
return new SdkHttpMetadataCoder(false);
} | @Test
public void testSdkHttpMetadataWithoutHeadersDecodeEncodeEquals() throws Exception {
SdkHttpMetadata value = buildSdkHttpMetadata();
SdkHttpMetadata clone = CoderUtils.clone(AwsCoders.sdkHttpMetadataWithoutHeaders(), value);
assertThat(clone.getHttpStatusCode(), equalTo(value.getHttpStatusCode()));
... |
@Udf(description = "Converts the number of days since 1970-01-01 00:00:00 UTC/GMT to a date "
+ "string using the given format pattern. The format pattern should be in the format"
+ " expected by java.time.format.DateTimeFormatter")
public String dateToString(
@UdfParameter(
description = ... | @Test
public void shouldSupportEmbeddedChars() {
// When:
final Object result = udf.dateToString(12345, "yyyy-dd-MM'Fred'");
// Then:
assertThat(result, is("2003-20-10Fred"));
} |
public static long fingerprint64(Schema schema) {
long fingerPrint = fingerprint64(INIT, schema.getTypeName());
fingerPrint = fingerprint64(fingerPrint, schema.getFieldCount());
for (FieldDescriptor descriptor : schema.getFields()) {
fingerPrint = fingerprint64(fingerPrint, descripto... | @Test
public void testRabinFingerprintIsConsistentWithWrittenData() throws IOException {
SchemaWriter writer = new SchemaWriter("typeName");
writer.addField(new FieldDescriptor("a", FieldKind.BOOLEAN));
writer.addField(new FieldDescriptor("b", FieldKind.ARRAY_OF_BOOLEAN));
writer.add... |
@Override
public ChannelFuture writePing(ChannelHandlerContext ctx, boolean ack, long data, ChannelPromise promise) {
return frameWriter.writePing(ctx, ack, data, promise);
} | @Test
public void pingWriteAfterGoAwayShouldSucceed() throws Exception {
ChannelPromise promise = newPromise();
goAwayReceived(0);
encoder.writePing(ctx, false, 0L, promise);
verify(writer).writePing(eq(ctx), eq(false), eq(0L), eq(promise));
} |
public static boolean isUnanimousCandidate(
final ClusterMember[] clusterMembers, final ClusterMember candidate, final int gracefulClosedLeaderId)
{
int possibleVotes = 0;
for (final ClusterMember member : clusterMembers)
{
if (member.id == gracefulClosedLeaderId)
... | @Test
void isUnanimousCandidateReturnTrueIfTheCandidateHasTheMostUpToDateLog()
{
final int gracefulClosedLeaderId = Aeron.NULL_VALUE;
final ClusterMember candidate = newMember(2, 10, 800);
final ClusterMember[] members = new ClusterMember[]
{
newMember(10, 2, 100),
... |
@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);
} |
@Override
public void addDestinationInfo(ConnectionContext context, DestinationInfo info) throws Exception {
DestinationAction action = new DestinationAction(context, info.getDestination(), "create");
assertAuthorized(action);
super.addDestinationInfo(context, info);
} | @Test(expected=UnauthorizedException.class)
public void testAddDestinationInfoNotAuthorized() throws Exception {
String name = "myTopic";
ActiveMQDestination dest = new ActiveMQTopic(name);
DestinationInfo info = new DestinationInfo(null, DestinationInfo.ADD_OPERATION_TYPE, dest);
S... |
public <T> SideInput<T> fetchSideInput(
PCollectionView<T> view,
BoundedWindow sideWindow,
String stateFamily,
SideInputState state,
Supplier<Closeable> scopedReadStateSupplier) {
Callable<SideInput<T>> loadSideInputFromWindmill =
() -> loadSideInputFromWindmill(view, sideWindo... | @Test
public void testEmptyFetchGlobalData() {
SideInputStateFetcherFactory factory =
SideInputStateFetcherFactory.fromOptions(
PipelineOptionsFactory.as(DataflowStreamingPipelineOptions.class));
SideInputStateFetcher fetcher = factory.createSideInputStateFetcher(server::getSideInputData);... |
@Udf(description = "Converts a TIME value into the"
+ " string representation of the time in the given format."
+ " The format pattern should be in the format expected"
+ " by java.time.format.DateTimeFormatter")
public String formatTime(
@UdfParameter(
description = "TIME value.") f... | @Test
public void shouldReturnNullOnNullTime() {
// When:
final String result = udf.formatTime(null, "HHmmss");
// Then:
assertThat(result, is(nullValue()));
} |
@Override
public GetAllResourceProfilesResponse getResourceProfiles(
GetAllResourceProfilesRequest request) throws YarnException, IOException {
if (request == null) {
routerMetrics.incrGetResourceProfilesFailedRetrieved();
String msg = "Missing getResourceProfiles request.";
RouterAuditLog... | @Test
public void testGetResourceProfiles() throws Exception {
LOG.info("Test FederationClientInterceptor : Get Resource Profiles request.");
// null request
LambdaTestUtils.intercept(YarnException.class, "Missing getResourceProfiles request.",
() -> interceptor.getResourceProfiles(null));
/... |
public static String encodeBase64Zipped( byte[] src ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 );
try ( Base64OutputStream base64OutputStream = new Base64OutputStream( baos );
GZIPOutputStream gzos = new GZIPOutputStream( base64OutputStream ) ) {
gzos.wri... | @Test
public void testEncodeBase64Zipped() throws Exception {
TestClass testClass = new TestClass();
testClass.setTestProp1( "testPropValue1" );
testClass.setTestProp2( "testPropValue2" );
String base64ZippedString = this.encode( testClass );
Assert.assertNotNull( base64ZippedString );
Asser... |
public void subscribeNewReplyReasonForComment(Comment comment) {
subscribeReply(identityFrom(comment.getSpec().getOwner()));
} | @Test
void subscribeNewReplyReasonForCommentTest() {
var comment = createComment();
var spyNotificationSubscriptionHelper = spy(notificationSubscriptionHelper);
doNothing().when(spyNotificationSubscriptionHelper).subscribeReply(any(UserIdentity.class));
spyNotificationSubscriptionH... |
@Override
public <VR> KStream<K, VR> mapValues(final ValueMapper<? super V, ? extends VR> valueMapper) {
return mapValues(withKey(valueMapper));
} | @Test
public void shouldNotAllowNullMapperOnMapValuesWithKeyWithNamed() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.mapValues(
(ValueMapperWithKey<Object, Object, Object>) null,
Named.as("valueMap... |
public static Optional<VariableDeclarator> getVariableDeclarator(final MethodDeclaration methodDeclaration,
final String variableName) {
final BlockStmt body = methodDeclaration.getBody()
.orElseThrow(() -> new KiePMMLException... | @Test
void getVariableDeclarator() {
final String variableName = "variableName";
final BlockStmt body = new BlockStmt();
assertThat(CommonCodegenUtils.getVariableDeclarator(body, variableName)).isNotPresent();
final VariableDeclarationExpr variableDeclarationExpr = new VariableDeclar... |
public synchronized int requestUpdate(final boolean resetEquivalentResponseBackoff) {
this.needFullUpdate = true;
if (resetEquivalentResponseBackoff) {
this.equivalentResponseCount = 0;
}
return this.updateVersion;
} | @Test
public void testRequestUpdate() {
assertFalse(metadata.updateRequested());
int[] epochs = {42, 42, 41, 41, 42, 43, 43, 42, 41, 44};
boolean[] updateResult = {true, false, false, false, false, true, false, false, false, true};
TopicPartition t... |
public static <T> NavigableSet<Point<T>> fastKNearestPoints(SortedSet<Point<T>> points, Instant time, int k) {
checkNotNull(points, "The input SortedSet of Points cannot be null");
checkNotNull(time, "The input time cannot be null");
checkArgument(k >= 0, "k (" + k + ") must be non-negative");
... | @Test
public void testFastKNearestPoints_6() {
NavigableSet<Point<String>> knn = fastKNearestPoints(points, EPOCH.plusSeconds(5), 100);
assertEquals(points.size(), knn.size());
assertFalse(knn == points, "The datasets are different");
knn.pollFirst();
assertEquals(points.size... |
public void onProcessingTime(long timestamp) throws Exception {
for (Bucket<IN, BucketID> bucket : activeBuckets.values()) {
bucket.onProcessingTime(timestamp);
}
} | @Test
void testOnProcessingTime() throws Exception {
final File outDir = TempDirUtils.newFolder(tempFolder);
final Path path = new Path(outDir.toURI());
final OnProcessingTimePolicy<String, String> rollOnProcessingTimeCountingPolicy =
new OnProcessingTimePolicy<>(2L);
... |
public COM verifyCom(byte[] data, Class<? extends COM> type) throws RdaException {
final COM com = read(data, type);
if (!com.getDataGroups().containsAll(com.getRdaDataGroups())) {
throw new RdaException(
RdaError.COM, String.format("Not all data groups are available: %s"... | @Test
public void shouldThrowErrorIfBasicDataGroupsAreMissingFromTravelDocument() throws Exception {
final CardVerifier verifier = verifier(null, null);
final byte[] com = readFixture("nik2014/efCom");
com[20] += 2;
Exception exception = assertThrows(RdaException.class, () -> {
... |
public static FusedPipeline fuse(Pipeline p) {
return new GreedyPipelineFuser(p).fusedPipeline;
} | @Test
public void statefulParDoRootsStage() {
// (impulse.out) -> parDo -> (parDo.out)
// (parDo.out) -> stateful -> stateful.out
// stateful has a state spec which prevents it from fusing with an upstream ParDo
PTransform parDoTransform =
PTransform.newBuilder()
.setUniqueName("Pa... |
@Override
public boolean canReadView(ViewLike view) {
final String viewId = view.id();
// If a resolved view id is provided, delegate the permissions check to the resolver.
final ViewResolverDecoder decoder = new ViewResolverDecoder(viewId);
if (decoder.isResolverViewId()) {
... | @Test
void testViewReadAccess() {
// Verify that all combinations of permission and view ids test successfully.
assertThat(searchUserRequiringPermission("missing-permission", "bad-id")
.canReadView(new TestView("do-not-match-id"))).isFalse();
assertThat(searchUserRequiringPer... |
@Override
public ManifestIdentifier identify(Config config) {
Path manifestFile = getFileFromProperty("android_merged_manifest");
Path resourcesDir = getFileFromProperty("android_merged_resources");
Path assetsDir = getFileFromProperty("android_merged_assets");
Path apkFile = getFileFromProperty("andr... | @Test
public void identify() {
Properties properties = new Properties();
properties.put("android_merged_manifest", "gradle/AndroidManifest.xml");
properties.put("android_merged_resources", "gradle/res");
properties.put("android_merged_assets", "gradle/assets");
DefaultManifestFactory factory = new... |
@ScalarOperator(INDETERMINATE)
@SqlType(StandardTypes.BOOLEAN)
public static boolean indeterminate(@SqlType(StandardTypes.DOUBLE) double value, @IsNull boolean isNull)
{
return isNull;
} | @Test
public void testIndeterminate()
{
assertOperator(INDETERMINATE, "cast(null as double)", BOOLEAN, true);
assertOperator(INDETERMINATE, "1.2", BOOLEAN, false);
assertOperator(INDETERMINATE, "cast(1.2 as double)", BOOLEAN, false);
assertOperator(INDETERMINATE, "cast(1 as doubl... |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetIntegerSchemaForIntPrimitiveClassVariadic() {
assertThat(
UdfUtil.getVarArgsSchemaFromType(int.class),
equalTo(ParamTypes.INTEGER)
);
} |
@VisibleForTesting
protected void copyResourcesFromJar(JarFile inputJar) throws IOException {
Enumeration<JarEntry> inputJarEntries = inputJar.entries();
// The zip spec allows multiple files with the same name; the Java zip libraries do not.
// Keep track of the files we've already written to filter out ... | @Test
public void testCopyResourcesFromJar_ignoresDuplicates() throws IOException {
List<JarEntry> duplicateEntries = ImmutableList.of(new JarEntry("foo"), new JarEntry("foo"));
when(inputJar.entries()).thenReturn(Collections.enumeration(duplicateEntries));
jarCreator.copyResourcesFromJar(inputJar);
v... |
@Override
public int hashCode() {
return Objects.hash(memberId, groupInstanceId, clientId, host, assignment, targetAssignment);
} | @Test
public void testEqualsWithoutGroupInstanceId() {
MemberDescription dynamicMemberDescription = new MemberDescription(MEMBER_ID,
CLIENT_ID,
HOST,
... |
void generateAndEnrichToken(Consumer consumer, ConsumerToken consumerToken) {
Preconditions.checkArgument(consumer != null);
if (consumerToken.getDataChangeCreatedTime() == null) {
consumerToken.setDataChangeCreatedTime(new Date());
}
consumerToken.setToken(generateToken(consumer.getAppId(), con... | @Test
public void testGenerateAndEnrichConsumerTokenWithConsumerNotFound() throws Exception {
long someConsumerIdNotExist = 1;
ConsumerToken consumerToken = new ConsumerToken();
consumerToken.setConsumerId(someConsumerIdNotExist);
assertThrows(IllegalArgumentException.class,
() -> consumerSe... |
@Override
public boolean supportsGetGeneratedKeys() {
return false;
} | @Test
void assertSupportsGetGeneratedKeys() {
assertFalse(metaData.supportsGetGeneratedKeys());
} |
@Override
public UnboundFunction loadFunction(Identifier ident) throws NoSuchFunctionException {
try {
return super.loadFunction(ident);
} catch (NoSuchFunctionException e) {
return getSessionCatalog().loadFunction(ident);
}
} | @Test
public void testLoadFunction() {
String functionClass = "org.apache.hadoop.hive.ql.udf.generic.GenericUDFUpper";
// load permanent UDF in Hive via FunctionCatalog
spark.sql(String.format("CREATE FUNCTION perm_upper AS '%s'", functionClass));
Assert.assertEquals("Load permanent UDF in Hive", "XY... |
public abstract boolean isTopicAllowed(String topic, boolean excludeInternalTopics); | @Test
public void testIncludeLists() {
IncludeList topicFilter1 = new TopicFilter.IncludeList("yes1,yes2");
assertTrue(topicFilter1.isTopicAllowed("yes2", true));
assertTrue(topicFilter1.isTopicAllowed("yes2", false));
assertFalse(topicFilter1.isTopicAllowed("no1", true));
as... |
@Override
public Enumeration<URL> getResources(String name) throws IOException {
List<URL> resources = new ArrayList<>();
ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name);
log.trace("Received request to load resources '{}'", name);
for (ClassLoadingStrategy.Source... | @Test
void parentFirstGetResourcesExistsInBothParentAndPlugin() throws URISyntaxException, IOException {
Enumeration<URL> resources = parentFirstPluginClassLoader.getResources("META-INF/file-in-both-parent-and-plugin");
assertNumberOfResourcesAndFirstLineOfFirstElement(2, "parent", resources);
} |
@Override
public void evictAll() {
map.evictAll();
} | @Test
public void testEvictAll() {
mapWithLoader.put(23, "value-23");
mapWithLoader.put(42, "value-42");
mapWithLoader.put(65, "value-65");
adapterWithLoader.evictAll();
assertEquals(0, mapWithLoader.size());
assertFalse(mapWithLoader.containsKey(23));
asser... |
public static boolean test(byte[] bloomBytes, byte[]... topics) {
Bloom bloom = new Bloom(bloomBytes);
if (topics == null) {
throw new IllegalArgumentException("topics can not be null");
}
for (byte[] topic : topics) {
if (!bloom.test(topic)) {
ret... | @Test
public void testStaticMethodTestWhenOneTopicIsNotInBloom() {
boolean result =
Bloom.test(
ethereumSampleLogsBloom,
ethereumSampleLogs.get(0),
ethereumSampleLogs.get(100),
"0xff");
as... |
@GetMapping
public RestResult<List<Namespace>> getNamespaces() {
return RestResultUtils.success(namespaceOperationService.getNamespaceList());
} | @Test
void testGetNamespaces() throws Exception {
Namespace namespace = new Namespace("", "public");
when(namespaceOperationService.getNamespaceList()).thenReturn(Collections.singletonList(namespace));
RestResult<List<Namespace>> actual = namespaceController.getNamespaces();
assertTr... |
@Override
@SuppressWarnings("unchecked")
public void onApplicationEvent(@NotNull final DataChangedEvent event) {
for (DataChangedListener listener : listeners) {
if ((!(listener instanceof AbstractDataChangedListener))
&& clusterProperties.isEnabled()
... | @Test
public void onApplicationEventWithPluginConfigGroupTest() {
when(clusterProperties.isEnabled()).thenReturn(true);
when(shenyuClusterSelectMasterService.isMaster()).thenReturn(true);
ConfigGroupEnum configGroupEnum = ConfigGroupEnum.PLUGIN;
DataChangedEvent dataChangedEvent = ne... |
@Override
protected TableRecords getUndoRows() {
return sqlUndoLog.getBeforeImage();
} | @Test
public void getUndoRows() {
OracleUndoDeleteExecutor executor = upperCase();
Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage());
} |
public KsqlGenericRecord build(
final List<ColumnName> columnNames,
final List<Expression> expressions,
final LogicalSchema schema,
final DataSourceType dataSourceType
) {
final List<ColumnName> columns = columnNames.isEmpty()
? implicitColumns(schema)
: columnNames;
i... | @Test
public void shouldThrowOnUnknownColumn() {
// Given:
final LogicalSchema schema = LogicalSchema.builder()
.keyColumn(KEY, SqlTypes.STRING)
.valueColumn(COL0, SqlTypes.STRING)
.build();
final List<ColumnName> names = ImmutableList.of(KEY, COL1);
final Expression exp = new... |
public static double validateLongitude(double longitude) {
if (Double.isNaN(longitude) || longitude < LONGITUDE_MIN || longitude > LONGITUDE_MAX) {
throw new IllegalArgumentException("invalid longitude: " + longitude);
}
return longitude;
} | @Test
public void validateLongitudeTest() {
LatLongUtils.validateLongitude(LatLongUtils.LONGITUDE_MAX);
LatLongUtils.validateLongitude(LatLongUtils.LONGITUDE_MIN);
verifyInvalidLongitude(Double.NaN);
verifyInvalidLongitude(Math.nextAfter(LatLongUtils.LONGITUDE_MAX, Double.POSITIVE_I... |
@Udf
public <T> Boolean contains(
@UdfParameter final String jsonArray,
@UdfParameter final T val
) {
try (JsonParser parser = PARSER_FACTORY.createParser(jsonArray)) {
if (parser.nextToken() != START_ARRAY) {
return false;
}
while (parser.nextToken() != null) {
fi... | @Test
public void shouldHandleNullsInJsonArray() {
assertEquals(false, jsonUdf.contains("[false, false, true, false]", null));
} |
@Override
public boolean wasNull() throws SQLException {
return queryResult.wasNull();
} | @Test
void assertWasNull() throws SQLException {
assertFalse(createMergedEncryptColumnsMergedResult(queryResult, mock(EncryptRule.class)).wasNull());
} |
public FileInputStream openInputStream(File file) {
try {
return openInputStreamOrThrowIOE(file);
} catch (IOException e) {
throw new IllegalStateException("Can not open file " + file, e);
}
} | @Test
public void openInputStream_throws_ISE_if_file_does_not_exist() throws Exception {
final File file = temp.newFile();
assertThat(file.delete()).isTrue();
assertThatThrownBy(() -> underTest.openInputStream(file))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Can not open file " ... |
@Nullable
@Override
public Message decode(@Nonnull final RawMessage rawMessage) {
final GELFMessage gelfMessage = new GELFMessage(rawMessage.getPayload(), rawMessage.getRemoteAddress());
final String json = gelfMessage.getJSON(decompressSizeLimit, charset);
final JsonNode node;
... | @Test
public void decodeFailsWithWrongTypeForMessage() throws Exception {
final String json = "{"
+ "\"version\": \"1.1\","
+ "\"host\": \"example.org\","
+ "\"message\": 42"
+ "}";
final RawMessage rawMessage = new RawMessage(json.get... |
public T divide(BigDecimal by) {
return create(value.divide(by, MAX_VALUE_SCALE, RoundingMode.DOWN));
} | @Test
void testDivideNegative() {
final Resource resource = new TestResource(1.2);
final BigDecimal by = BigDecimal.valueOf(-0.5);
assertThatThrownBy(() -> resource.divide(by)).isInstanceOf(IllegalArgumentException.class);
} |
public static Deserializer<RouterAdvertisement> deserializer() {
return (data, offset, length) -> {
checkInput(data, offset, length, HEADER_LENGTH);
RouterAdvertisement routerAdvertisement = new RouterAdvertisement();
ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
... | @Test
public void testDeserializeBadInput() throws Exception {
PacketTestUtils.testDeserializeBadInput(RouterAdvertisement.deserializer());
} |
@VisibleForTesting
/**
* This initializes the caches in SharedCache by getting the objects from Metastore DB via
* ObjectStore and populating the respective caches
*/
static void prewarm(RawStore rawStore) {
if (isCachePrewarmed.get()) {
return;
}
long startTime = System.nanoTime();
L... | @Test public void testPrewarm() throws Exception {
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true);
MetastoreConf.setVar(conf, MetastoreConf.ConfVars.CACHED_RAW_STORE_MAX_CACHE_MEMORY, "-1Kb");
MetaStoreTestUtils.setConfFor... |
static int[] shiftLeftMultiPrecision(int[] number, int length, int shifts)
{
if (shifts == 0) {
return number;
}
// wordShifts = shifts / 32
int wordShifts = shifts >>> 5;
// we don't want to lose any leading bits
for (int i = 0; i < wordShifts; i++) {
... | @Test
public void testShiftLeftMultiPrecision()
{
assertEquals(shiftLeftMultiPrecision(
new int[] {0b10100001010001011010000101000101, 0b01010110100101101011010101010101, 0b01010010111110001111100010101010,
0b11111111000000011010101010101011, 0b0000000000000000000... |
public ManagedProcess launch(AbstractCommand command) {
EsInstallation esInstallation = command.getEsInstallation();
if (esInstallation != null) {
cleanupOutdatedEsData(esInstallation);
writeConfFiles(esInstallation);
}
Process process;
if (command instanceof JavaCommand<?> javaCommand)... | @Test
public void clean_up_old_es_data() throws Exception {
File tempDir = temp.newFolder();
File homeDir = temp.newFolder();
File dataDir = temp.newFolder();
File logDir = temp.newFolder();
ProcessLauncher underTest = new ProcessLauncherImpl(tempDir, commands, TestProcessBuilder::new);
JavaCo... |
public static byte[] toArray(ByteBuffer buffer) {
return toArray(buffer, 0, buffer.remaining());
} | @Test
public void toArray() {
byte[] input = {0, 1, 2, 3, 4};
ByteBuffer buffer = ByteBuffer.wrap(input);
assertArrayEquals(input, Utils.toArray(buffer));
assertEquals(0, buffer.position());
assertArrayEquals(new byte[] {1, 2}, Utils.toArray(buffer, 1, 2));
assertEqu... |
public static String getLatestCheckJobIdPath(final String jobId) {
return String.join("/", getJobRootPath(jobId), "check", "latest_job_id");
} | @Test
void assertGetLatestCheckJobIdPath() {
assertThat(PipelineMetaDataNode.getLatestCheckJobIdPath(jobId), is(jobCheckRootPath + "/latest_job_id"));
} |
public static ParamType getVarArgsSchemaFromType(final Type type) {
return getSchemaFromType(type, VARARGS_JAVA_TO_ARG_TYPE);
} | @Test
public void shouldGetPartialGenericBiFunctionVariadic() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("partialGenericBiFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getVarArgsSchemaFromType(genericType);
// The... |
@Override
public List<Node> sniff(List<Node> nodes) {
if (attribute == null || value == null) {
return nodes;
}
return nodes.stream()
.filter(node -> nodeMatchesFilter(node, attribute, value))
.collect(Collectors.toList());
} | @Test
void returnsNoNodesIfFilterDoesNotMatch() throws Exception {
final List<Node> nodes = mockNodes();
final NodesSniffer nodesSniffer = new FilteredOpenSearchNodesSniffer("location", "alaska");
assertThat(nodesSniffer.sniff(nodes)).isEmpty();
} |
@Override
public void fromPB(EncryptionKeyPB pb, KeyMgr mgr) {
super.fromPB(pb, mgr);
if (pb.algorithm == null) {
throw new IllegalArgumentException("no algorithm in EncryptionKeyPB for NormalKey id:" + id);
}
algorithm = pb.algorithm;
if (pb.plainKey != null) {
... | @Test
public void testFromPB_NoAlgorithm() {
NormalKey key = new NormalKey();
EncryptionKeyPB pb = new EncryptionKeyPB();
pb.encryptedKey = new byte[16];
KeyMgr mgr = new KeyMgr();
assertThrows(IllegalArgumentException.class, () -> {
key.fromPB(pb, mgr);
}... |
static Map<String, String> fromSystemProperties()
{
final HashMap<String, String> result = new HashMap<>();
final Properties properties = System.getProperties();
for (final Map.Entry<Object, Object> entry : properties.entrySet())
{
result.put((String)entry.getKey(), (Stri... | @Test
void shouldReadSystemProperties()
{
final Map<String, String> expectedValues = new HashMap<>();
try
{
expectedValues.put(DISABLED_ARCHIVE_EVENT_CODES, "abc");
expectedValues.put(LOG_FILENAME, "");
expectedValues.put(ENABLED_CLUSTER_EVENT_CODES, "... |
public static String byteCountToDisplaySize(long size) {
if (size < 1024L) {
return String.valueOf(size) + (size > 1 ? " bytes" : " byte");
}
long exp = (long) (Math.log(size) / Math.log((long) 1024));
double value = size / Math.pow((long) 1024, exp);
char unit = "KMG... | @Test
public void shouldConvertBytesToPB() {
long twoGiga = 2L * 1024 * 1024 * 1024 * 1024 * 1024 + 512L * 1024 * 1024 * 1024 * 1024;
assertThat(FileSizeUtils.byteCountToDisplaySize(twoGiga), is("2.5 PB"));
} |
static int getEncryptedPacketLength(ByteBuf buffer, int offset) {
int packetLength = 0;
// SSLv3 or TLS - Check ContentType
boolean tls;
switch (buffer.getUnsignedByte(offset)) {
case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
case SSL_CONTENT_TYPE_ALERT:
c... | @SuppressWarnings("deprecation")
@Test
public void testPacketLength() throws SSLException, NoSuchAlgorithmException {
SSLEngine engineLE = newEngine();
SSLEngine engineBE = newEngine();
ByteBuffer empty = ByteBuffer.allocate(0);
ByteBuffer cTOsLE = ByteBuffer.allocate(17 * 1024)... |
int parseAndConvert(String[] args) throws Exception {
Options opts = createOptions();
int retVal = 0;
try {
if (args.length == 0) {
LOG.info("Missing command line arguments");
printHelp(opts);
return 0;
}
CommandLine cliParser = new GnuParser().parse(opts, args);
... | @Test
public void testFairSchedulerXmlIsNotDefinedIfItsDefinedInYarnSiteXml()
throws Exception {
setupFSConfigConversionFiles(true);
FSConfigToCSConfigArgumentHandler argumentHandler =
createArgumentHandler();
argumentHandler.parseAndConvert(getDefaultArgumentsAsArray());
} |
@Override
public Object read(final PostgreSQLPacketPayload payload, final int parameterValueLength) {
byte[] result = new byte[parameterValueLength];
payload.getByteBuf().readBytes(result);
return new UUID(ByteConverter.int8(result, 0), ByteConverter.int8(result, 8));
} | @Test
void assertRead() {
UUID uuid = UUID.fromString("00000000-000-0000-0000-000000000001");
byte[] expected = new byte[16];
ByteBuffer buffer = ByteBuffer.wrap(expected);
buffer.putLong(uuid.getMostSignificantBits());
buffer.putLong(uuid.getLeastSignificantBits());
... |
public void isNull() {
standardIsEqualTo(null);
} | @Test
public void isNullWhenSubjectForbidsIsEqualTo() {
assertAbout(objectsForbiddingEqualityCheck()).that(null).isNull();
} |
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
} | @Test
public void kTableAnonymousMaterializedMapValuesShouldPreserveTopologyStructure() {
final StreamsBuilder builder = new StreamsBuilder();
final KTable<Object, Object> table = builder.table("input-topic");
table.mapValues(
(readOnlyKey, value) -> null,
Materialize... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseAssertTopic() {
// Given:
final String assertTopics = "assert topic abc; assert not exists topic 'abcd' with (foo=2, bar=3) timeout 4 minutes;"
+ "assert topic ${topic} with (replicas=${replicas}, partitions=${partitions}) timeout 10 seconds;";
// When:
List<Comma... |
public static KeyFormat sanitizeKeyFormat(
final KeyFormat keyFormat,
final List<SqlType> newKeyColumnSqlTypes,
final boolean allowKeyFormatChangeToSupportNewKeySchema
) {
return sanitizeKeyFormatWrapping(
!allowKeyFormatChangeToSupportNewKeySchema ? keyFormat :
sanitizeKeyFormat... | @Test
public void shouldNotConvertDelimitedFormatForMulticolKeysWithPrimitiveTypes() {
// Given:
final KeyFormat format = KeyFormat.nonWindowed(
FormatInfo.of(DelimitedFormat.NAME),
SerdeFeatures.of());
// When:
final KeyFormat sanitized = SerdeFeaturesFactory.sanitizeKeyFormat(format... |
@Override
public void readFully(long position, byte[] buffer, int offset, int length)
throws IOException
{
int totalBytesRead = 0;
while (totalBytesRead < length) {
int bytesRead = read(
position + totalBytesRead,
buffer,
... | @Test
public void testValidateDataEnabledWithDataMatched()
throws IOException
{
byte[] inputData = new byte[] {1, 2, 3};
FSDataInputStream dataTierInputStream = new TestFSDataInputStream(inputData);
FSDataInputStream fileInStream = new TestFSDataInputStream(inputData);
... |
@Override
public String getDriverVersion() {
return null;
} | @Test
void assertGetDriverVersion() {
assertNull(metaData.getDriverVersion());
} |
@Override
public DataflowPipelineJob run(Pipeline pipeline) {
// Multi-language pipelines and pipelines that include upgrades should automatically be upgraded
// to Runner v2.
if (DataflowRunner.isMultiLanguagePipeline(pipeline) || includesTransformUpgrades(pipeline)) {
List<String> experiments = fi... | @Test
public void testStreamingOnCreateMatcher() throws Exception {
options.setStreaming(true);
Pipeline p = TestPipeline.create(options);
PCollection<Integer> pc = p.apply(Create.of(1, 2, 3));
PAssert.that(pc).containsInAnyOrder(1, 2, 3);
final DataflowPipelineJob mockJob = Mockito.mock(Dataflow... |
@Udf
public String extractQuery(
@UdfParameter(description = "a valid URL to extract a query from") final String input) {
return UrlParser.extract(input, URI::getQuery);
} | @Test
public void shouldThrowExceptionForMalformedURL() {
// When:
final KsqlException e = assertThrows(
KsqlException.class,
() -> extractUdf.extractQuery("http://257.1/bogus/[url")
);
// Given:
assertThat(e.getMessage(), containsString("URL input has invalid syntax: http://257.1... |
public ReliableTopicConfig setTopicOverloadPolicy(TopicOverloadPolicy topicOverloadPolicy) {
this.topicOverloadPolicy = checkNotNull(topicOverloadPolicy, "topicOverloadPolicy can't be null");
return this;
} | @Test(expected = NullPointerException.class)
public void setTopicOverloadPolicy_whenNull() {
ReliableTopicConfig config = new ReliableTopicConfig("foo");
config.setTopicOverloadPolicy(null);
} |
@Override
public Path copy(final Path source, final Path target, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException {
try {
// Copies file
// If segmented file, copies manifest (creating a link between new object ... | @Test
public void testCopyToExistingFile() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path folder = new Path(container, new AlphanumericRandomStringService().random... |
public static String sanitizeStreamName(String streamName) {
Matcher problemCharacterMatcher = Pattern.compile("(?![A-Za-z_\\-\\.]).").matcher(streamName);
if (streamName.length() > 0 && Character.isLetter(streamName.charAt(0))) {
return problemCharacterMatcher.replaceAll("_");
} els... | @Test
public void testSanitizeStreamName() {
// replaces the expected characters with underscores (everything except A-Z, a-z, dot, dash, and underscore)
assertEquals("my-stream_with.all_characterClasses____",
UIHelpers.sanitizeStreamName("my-stream:with.all_characterClasses1/\\2"));... |
@Override
public String getName() {
return this.name;
} | @Test
public void shouldReturnTheCorrectName() {
assertThat(circuitBreaker.getName()).isEqualTo("testName");
} |
public static IcebergTableName from(String name)
{
Matcher match = TABLE_PATTERN.matcher(name);
if (!match.matches()) {
throw new PrestoException(NOT_SUPPORTED, "Invalid Iceberg table name: " + name);
}
String table = match.group("table");
String typeString = mat... | @Test
public void testFrom()
{
assertFrom("abc", "abc", IcebergTableType.DATA);
assertFrom("abc@123", "abc", IcebergTableType.DATA, Optional.of(123L));
assertFrom("abc$data", "abc", IcebergTableType.DATA);
assertFrom("xyz@456", "xyz", IcebergTableType.DATA, Optional.of(456L));
... |
public StrBuilder del(int start, int end) throws StringIndexOutOfBoundsException {
if (start < 0) {
start = 0;
}
if (end >= this.position) {
// end在边界及以外,相当于删除后半部分
this.position = start;
return this;
} else if (end < 0) {
// start和end都为0的情况下表示删除全部
end = 0;
}
int len = end - start;
// 截... | @Test
public void delTest() {
// 删除全部测试
StrBuilder strBuilder = new StrBuilder("ABCDEFG");
int length = strBuilder.length();
StrBuilder builder = strBuilder.del(0, length);
assertEquals("", builder.toString());
} |
@Override
public boolean eval(Object arg) {
QueryableEntry entry = (QueryableEntry) arg;
Data keyData = entry.getKeyData();
return (key == null || key.equals(keyData)) && predicate.apply((Map.Entry) arg);
} | @Test
public void testEval_givenFilterDoesNotContainKey_whenPredicateIsNotMatching_thenReturnFalse() {
//given
Predicate<Object, Object> predicate = Predicates.alwaysFalse();
QueryEventFilter filter = new QueryEventFilter(null, predicate, true);
//when
Data key2 = serializat... |
@Override
public void updateHealthStatusForPersistentInstance(String namespace, String fullServiceName, String clusterName,
String ip, int port, boolean healthy) throws NacosException {
String groupName = NamingUtils.getGroupName(fullServiceName);
String serviceName = NamingUtils.getServ... | @Test
void testUpdateHealthStatusForPersistentInstance() {
try {
ServiceMetadata metadata = new ServiceMetadata();
Map<String, ClusterMetadata> clusterMap = new HashMap<>(2);
ClusterMetadata cluster = Mockito.mock(ClusterMetadata.class);
clusterMap.put("C", cl... |
@Override
public void processElement(WindowedValue<InputT> compressedElem) {
if (observesWindow) {
for (WindowedValue<InputT> elem : compressedElem.explodeWindows()) {
invokeProcessElement(elem);
}
} else {
invokeProcessElement(compressedElem);
}
} | @Test
public void testTimerSet() {
WindowFn<?, ?> windowFn = new GlobalWindows();
DoFnWithTimers<GlobalWindow> fn = new DoFnWithTimers(windowFn.windowCoder());
DoFnRunner<String, String> runner =
new SimpleDoFnRunner<>(
null,
fn,
NullSideInputReader.empty(),
... |
public boolean quoteReservedWords() {
return databaseInterface.quoteReservedWords();
} | @Test
public void testQuoteReservedWords() {
DatabaseMeta databaseMeta = mock( DatabaseMeta.class );
doCallRealMethod().when( databaseMeta ).quoteReservedWords( any( RowMetaInterface.class ) );
doCallRealMethod().when( databaseMeta ).quoteField( anyString() );
doCallRealMethod().when( databaseMeta ).s... |
public static AwsCredentialsProvider create(boolean isCloud,
@Nullable String stsRegion,
@Nullable String accessKey,
@Nullable String secretKey,
... | @Test
public void testAutomaticAuth() {
assertThat(AWSAuthFactory.create(false, null, null, null, null))
.isExactlyInstanceOf(DefaultCredentialsProvider.class);
} |
@Override
public SubClusterId getHomeSubcluster(
ApplicationSubmissionContext appSubmissionContext,
List<SubClusterId> blackListSubClusters) throws YarnException {
// null checks and default-queue behavior
validate(appSubmissionContext);
List<ResourceRequest> rrList =
appSubmissionCo... | @Test
public void testNodeNotInPolicy() throws YarnException {
// Blacklist SubCluster3
String subClusterToBlacklist = "subcluster3";
// Remember the current value of subcluster3
Float value =
getPolicyInfo().getRouterPolicyWeights().get(subClusterToBlacklist);
getPolicyInfo().getRouterPol... |
public String abbreviate(String fqClassName) {
StringBuilder buf = new StringBuilder(targetLength);
if (fqClassName == null) {
throw new IllegalArgumentException("Class name may not be null");
}
int inLen = fqClassName.length();
if (inLen < targetLength) {
return fqClassName;
}
... | @Test
public void testOneDot() {
{
TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1);
String name = "hello.world";
assertEquals("h.world", abbreviator.abbreviate(name));
}
{
TargetLengthBasedClassNameAbbreviator abbreviator = new Targ... |
@Override
public boolean contains(Object o) {
if (!(o instanceof Integer))
return false;
int i = (int) o;
return contains(i);
} | @Test
public void contains() throws Exception {
RangeSet rs = new RangeSet(4);
assertFalse(rs.contains(5));
assertTrue(rs.contains(1));
} |
@Override
public int readUnsignedByte()
throws EOFException {
if (availableLong() < 1) {
throw new EOFException();
}
return _dataBuffer.getByte(_currentOffset++) & 0xFF;
} | @Test
void testReadUnsignedByte()
throws EOFException {
int read = _dataBufferPinotInputStream.readUnsignedByte();
assertEquals(read, _byteBuffer.get(0) & 0xFF);
assertEquals(_dataBufferPinotInputStream.getCurrentOffset(), 1);
} |
public static <K, V> Read<K, V> read() {
return new AutoValue_KafkaIO_Read.Builder<K, V>()
.setTopics(new ArrayList<>())
.setTopicPartitions(new ArrayList<>())
.setConsumerFactoryFn(KafkaIOUtils.KAFKA_CONSUMER_FACTORY_FN)
.setConsumerConfig(KafkaIOUtils.DEFAULT_CONSUMER_PROPERTIES)
... | @Test
public void testWithValidConsumerPollingTimeout() {
KafkaIO.Read<Integer, Long> reader =
KafkaIO.<Integer, Long>read().withConsumerPollingTimeout(15L);
assertEquals(15, reader.getConsumerPollingTimeout());
} |
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
throws IOException
{
return createFromImage(document, image, 0.75f);
} | @Test
void testCreateFromImage256() throws IOException
{
PDDocument document = new PDDocument();
BufferedImage image = ImageIO.read(JPEGFactoryTest.class.getResourceAsStream("jpeg256.jpg"));
assertEquals(1, image.getColorModel().getNumComponents());
PDImageXObject ximage = JPEGFa... |
public static SSLHandlerFactory createRestClientSSLEngineFactory(final Configuration config)
throws Exception {
ClientAuth clientAuth =
SecurityOptions.isRestSSLAuthenticationEnabled(config)
? ClientAuth.REQUIRE
: ClientAuth.NONE;
... | @Test
void testRESTClientSSLMissingPassword() {
Configuration config = new Configuration();
config.set(SecurityOptions.SSL_REST_ENABLED, true);
config.set(SecurityOptions.SSL_REST_TRUSTSTORE, TRUST_STORE_PATH);
assertThatThrownBy(() -> SSLUtils.createRestClientSSLEngineFactory(confi... |
public void importCounters(String[] counterNames, String[] counterKinds, long[] counterDeltas) {
final int length = counterNames.length;
if (counterKinds.length != length || counterDeltas.length != length) {
throw new AssertionError("array lengths do not match");
}
for (int i = 0; i < length; ++i)... | @Test
public void testSingleCounter() throws Exception {
String[] names = {"sum_counter"};
String[] kinds = {"sum"};
long[] deltas = {122};
counters.importCounters(names, kinds, deltas);
counterSet.extractUpdates(false, mockUpdateExtractor);
verify(mockUpdateExtractor)
.longSum(named(... |
public StepExpression createExpression(StepDefinition stepDefinition) {
List<ParameterInfo> parameterInfos = stepDefinition.parameterInfos();
if (parameterInfos.isEmpty()) {
return createExpression(
stepDefinition.getPattern(),
stepDefinitionDoesNotTakeAnyPar... | @Test
void docstring_expression_transform_doc_string_to_string() {
String docString = "A rather long and boring string of documentation";
StepDefinition stepDefinition = new StubStepDefinition("Given some stuff:", String.class);
StepExpression expression = stepExpressionFactory.createExpress... |
@CanIgnoreReturnValue
public final Ordered containsExactlyElementsIn(@Nullable Iterable<?> expected) {
return containsExactlyElementsIn(expected, false);
} | @Test
@SuppressWarnings("ContainsExactlyNone")
public void iterableContainsExactlyElementsInWithEmptyExpected() {
expectFailureWhenTestingThat(asList("foo")).containsExactlyElementsIn(ImmutableList.of());
assertFailureKeys("expected to be empty", "but was");
} |
protected AbstractContainerCollector(NodeEngine nodeEngine) {
this.operationExecutor = ((OperationServiceImpl) nodeEngine.getOperationService()).getOperationExecutor();
this.partitionService = nodeEngine.getPartitionService();
this.mergePolicyProvider = nodeEngine.getSplitBrainMergePolicyProvide... | @Test
public void testAbstractContainerCollector() {
TestContainerCollector collector = new TestContainerCollector(nodeEngine, true, true);
assertEqualsStringFormat("Expected the to have %d containers, but found %d", 1, collector.containers.size());
collector.run();
assertEqualsStr... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String tableNameSuffix = String.valueOf(doSharding(parseDa... | @Test
void assertRangeDoShardingWithoutLowerBound() {
List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3");
Collection<String> actual = shardingAlgorithm.doSharding(availableTargetNames,
new RangeShardingValue<>("t_order", "create_time... |
public FileMetadata fileMetadata() throws IOException {
if (knownFileMetadata == null) {
int footerSize = footerSize();
byte[] footer = readInput(fileSize - footerSize, footerSize);
checkMagic(footer, PuffinFormat.FOOTER_START_MAGIC_OFFSET);
int footerStructOffset = footerSize - PuffinForma... | @Test
public void testValidateFooterSizeValue() throws Exception {
// Ensure the definition of SAMPLE_METRIC_DATA_COMPRESSED_ZSTD_FOOTER_SIZE remains accurate
InMemoryInputFile inputFile =
new InMemoryInputFile(readTestResource("v1/sample-metric-data-compressed-zstd.bin"));
try (PuffinReader reade... |
@JsonProperty(FIELD_SCOPE)
public abstract String scope(); | @Test
void testExplicitScope() {
final TestScopedEntity scopedEntity = TestScopedEntity.builder().title(TITLE).scope(ARBITRARY_SCOPE).build();
assertEquals(ARBITRARY_SCOPE, scopedEntity.scope());
assertEquals(TITLE, scopedEntity.title());
} |
@ScalarFunction
@SqlType(ColorType.NAME)
public static long rgb(@SqlType(StandardTypes.BIGINT) long red, @SqlType(StandardTypes.BIGINT) long green, @SqlType(StandardTypes.BIGINT) long blue)
{
checkCondition(red >= 0 && red <= 255, INVALID_FUNCTION_ARGUMENT, "red must be between 0 and 255");
... | @Test
public void testToRgb()
{
assertEquals(rgb(0xFF, 0, 0), 0xFF_00_00);
assertEquals(rgb(0, 0xFF, 0), 0x00_FF_00);
assertEquals(rgb(0, 0, 0xFF), 0x00_00_FF);
} |
public ProjectStatusResponse.ProjectStatus format() {
if (!optionalMeasureData.isPresent()) {
return newResponseWithoutQualityGateDetails();
}
JsonObject json = JsonParser.parseString(optionalMeasureData.get()).getAsJsonObject();
ProjectStatusResponse.Status qualityGateStatus = measureLevelToQua... | @Test
public void fail_when_measure_level_is_unknown() {
String measureData = "{\n" +
" \"level\": \"UNKNOWN\",\n" +
" \"conditions\": [\n" +
" {\n" +
" \"metric\": \"new_coverage\",\n" +
" \"op\": \"LT\",\n" +
" \"period\": 1,\n" +
" \"warning\":... |
@VisibleForTesting
void validateMenu(Long parentId, String name, Long id) {
MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name);
if (menu == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的菜单
if (id == null) {
throw exception(MENU_NAME_DUPLI... | @Test
public void testValidateMenu_success() {
// mock 父子菜单
MenuDO sonMenu = createParentAndSonMenu();
// 准备参数
Long parentId = sonMenu.getParentId();
Long otherSonMenuId = randomLongId();
String otherSonMenuName = randomString();
// 调用,无需断言
menuServic... |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 1) {
if ("withZone".equals(methodName)) {
return new SelJodaDateTimeFormatter(
val.withZone(((SelJodaDateTimeZone) args[0]).getInternalVal()));
} else if ("parseDateTime".equals(methodName)) {
... | @Test(expected = UnsupportedOperationException.class)
public void testInvalidCallMethod() {
one.call("invalid", new SelType[] {});
} |
public CreateTableBuilder addPkColumn(ColumnDef columnDef, ColumnFlag... flags) {
pkColumnDefs.add(requireNonNull(columnDef, "column def can't be null"));
addFlags(columnDef, flags);
return this;
} | @Test
public void addPkColumn_throws_NPE_if_ColumnDef_is_null() {
assertThatThrownBy(() -> underTest.addPkColumn(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("column def can't be null");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.