focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static void checkValidTableId(String idToCheck) {
if (idToCheck.length() < MIN_TABLE_ID_LENGTH) {
throw new IllegalArgumentException("Table ID cannot be empty. ");
}
if (idToCheck.length() > MAX_TABLE_ID_LENGTH) {
throw new IllegalArgumentException(
"Table ID "
+ idToChec... | @Test
public void testCheckValidTableIdWhenIdContainsIllegalCharacter() {
assertThrows(IllegalArgumentException.class, () -> checkValidTableId("table-id%"));
assertThrows(IllegalArgumentException.class, () -> checkValidTableId("ta#ble-id"));
} |
@Override
public Collection<ResourceRequirement> getResourceRequirements() {
final Collection<ResourceRequirement> currentResourceRequirements = new ArrayList<>();
for (Map.Entry<ResourceProfile, Integer> resourceRequirement :
totalResourceRequirements.getResourcesWithCount()) {
... | @TestTemplate
void testGetResourceRequirements() {
final DefaultDeclarativeSlotPool slotPool = createDefaultDeclarativeSlotPool();
assertThat(slotPool.getResourceRequirements()).isEmpty();
final ResourceCounter resourceRequirements = createResourceRequirements();
slotPool.increase... |
public ClientAuth getClientAuth() {
String clientAuth = getString(SSL_CLIENT_AUTHENTICATION_CONFIG);
if (originals().containsKey(SSL_CLIENT_AUTH_CONFIG)) {
if (originals().containsKey(SSL_CLIENT_AUTHENTICATION_CONFIG)) {
log.warn(
"The {} configuration is deprecated. Since a value has... | @Test
public void shouldUseClientAuthenticationIfClientAuthProvidedNone() {
// Given:
final KsqlRestConfig config = new KsqlRestConfig(ImmutableMap.<String, Object>builder()
.put(KsqlRestConfig.SSL_CLIENT_AUTH_CONFIG, true)
.put(KsqlRestConfig.SSL_CLIENT_AUTHENTICATION_CONFIG,
Ksql... |
public static RDA fit(double[][] x, int[] y, Properties params) {
double alpha = Double.parseDouble(params.getProperty("smile.rda.alpha", "0.9"));
double[] priori = Strings.parseDoubleArray(params.getProperty("smile.rda.priori"));
double tol = Double.parseDouble(params.getProperty("smile.rda.tol... | @Test
public void testUSPS() throws Exception {
System.out.println("USPS");
RDA model = RDA.fit(USPS.x, USPS.y, 0.7);
int[] prediction = model.predict(USPS.testx);
int error = Error.of(USPS.testy, prediction);
System.out.println("Error = " + error);
assertEquals(23... |
@Override
public ExecuteContext before(ExecuteContext context) {
Object[] arguments = context.getArguments();
if (arguments != null && arguments.length > 0) {
Object obj = arguments[0];
Object serviceName = ReflectUtils.getFieldValue(obj, "serviceName").orElse(null);
... | @Test
public void testBefore() {
interceptor.before(context);
Assert.assertEquals("foo", AppCache.INSTANCE.getAppName());
Map<String, String> metadata = ((TestObject) context.getArguments()[0]).getMetadata();
Assert.assertEquals("bar1", metadata.get("bar"));
Assert.assertEqua... |
@SuppressWarnings("NPathComplexity")
@Override
public final int hashCode() {
int result = (name != null ? name.hashCode() : 0);
result = 31 * result + backupCount;
result = 31 * result + asyncBackupCount;
result = 31 * result + timeToLiveSeconds;
result = 31 * result + ma... | @Test
@SuppressWarnings("ResultOfMethodCallIgnored")
public void testDefaultHashCode() {
MapConfig mapConfig = new MapConfig();
mapConfig.hashCode();
} |
public int getNumberOfEntriesAffected() {
return numberOfEntriesAffected;
} | @Test
public void testGetNumberOfEntriesAffected() {
assertEquals(42, localCacheWideEventData.getNumberOfEntriesAffected());
} |
@Override
public void filter(final ContainerRequestContext request,
final ContainerResponseContext response) throws IOException {
final MediaType type = response.getMediaType();
if (type != null && !type.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) {
final Media... | @Test
void testSetsCharsetEncoding() throws Exception {
when(response.getMediaType()).thenReturn(MediaType.APPLICATION_JSON_TYPE);
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE);
when(respons... |
public static SortDir sortDir(String s) {
return !DESC.equals(s) ? SortDir.ASC : SortDir.DESC;
} | @Test
public void sortDirAsc() {
assertEquals("asc sort dir", SortDir.ASC, TableModel.sortDir("asc"));
} |
@Override
public void addFirst(DirectoryDiff diff) {
final int nodeLevel = DirectoryDiffListFactory.randomLevel();
final SkipListNode[] nodePath = new SkipListNode[nodeLevel + 1];
Arrays.fill(nodePath, head);
final SkipListNode newNode = new SkipListNode(diff, nodeLevel);
for (int level = 0; leve... | @Test
public void testAddFirst() throws Exception {
testAddFirst(NUM_SNAPSHOTS);
} |
public void formatSource(CharSource input, CharSink output)
throws FormatterException, IOException {
// TODO(cushon): proper support for streaming input/output. Input may
// not be feasible (parsing) but output should be easier.
output.write(formatSource(input.read()));
} | @Test
public void voidMethod() throws FormatterException {
String input = "class X { void Y() {} }";
String output = new Formatter().formatSource(input);
String expect = "class X {\n void Y() {}\n}\n";
assertThat(output).isEqualTo(expect);
} |
@Override
public void initialize(ServiceConfiguration config) throws IOException, IllegalArgumentException {
String prefix = (String) config.getProperty(CONF_TOKEN_SETTING_PREFIX);
if (null == prefix) {
prefix = "";
}
this.confTokenSecretKeySettingName = prefix + CONF_TOK... | @Test(expectedExceptions = IllegalArgumentException.class)
public void testInitializeWhenSecretKeyFilePathIfNotExist() throws IOException {
File secretKeyFile = File.createTempFile("secret_key_file_not_exist", ".key");
assertTrue(secretKeyFile.delete());
assertFalse(secretKeyFile.exists());
... |
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception {
return fromXmlPartial(toInputStream(partial, UTF_8), o);
} | @Test
void shouldLoadBuildPlanFromXmlPartial() throws Exception {
String buildXmlPartial =
"""
<job name="functional">
<artifacts>
<artifact type="build" src="artifact1.xml" dest="cruise-output" />
... |
@Override
public Double getDouble(K name) {
return null;
} | @Test
public void testGetDoubleDefault() {
assertEquals(1, HEADERS.getDouble("name1", 1), 0);
} |
private boolean autoscale(ApplicationId applicationId, ClusterSpec.Id clusterId) {
boolean redeploy = false;
boolean enabled = enabledFlag.with(Dimension.INSTANCE_ID, applicationId.serializedForm()).value();
boolean logDetails = enableDetailedLoggingFlag.with(Dimension.INSTANCE_ID, applicationId... | @Test
public void test_cd_autoscaling_test() {
ApplicationId app1 = AutoscalingMaintainerTester.makeApplicationId("app1");
ClusterSpec cluster1 = AutoscalingMaintainerTester.containerClusterSpec();
NodeResources resources = new NodeResources(1, 4, 50, 1);
ClusterResources min = new C... |
@Nullable
public Object get(PropertyKey key) {
if (mUserProps.containsKey(key)) {
return mUserProps.get(key).orElse(null);
}
// In case key is not the reference to the original key
return PropertyKey.fromString(key.toString()).getDefaultValue();
} | @Test
public void get() {
assertEquals("value", mProperties.get(mKeyWithValue));
assertEquals(null, mProperties.get(mKeyWithoutValue));
mProperties.put(mKeyWithoutValue, "newValue1", Source.RUNTIME);
assertEquals("newValue1", mProperties.get(mKeyWithoutValue));
} |
public static UTypeApply create(UExpression type, List<UExpression> typeArguments) {
return new AutoValue_UTypeApply(type, ImmutableList.copyOf(typeArguments));
} | @Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UTypeApply.create(
UClassIdent.create("java.util.List"), UClassIdent.create("java.lang.String")));
} |
public TolerantFloatComparison isWithin(float tolerance) {
return new TolerantFloatComparison() {
@Override
public void of(float expected) {
Float actual = FloatSubject.this.actual;
checkNotNull(
actual, "actual value cannot be null. tolerance=%s expected=%s", tolerance, expe... | @Test
public void isWithinOf() {
assertThat(2.0f).isWithin(0.0f).of(2.0f);
assertThat(2.0f).isWithin(0.00001f).of(2.0f);
assertThat(2.0f).isWithin(1000.0f).of(2.0f);
assertThat(2.0f).isWithin(1.00001f).of(3.0f);
assertThatIsWithinFails(2.0f, 0.99999f, 3.0f);
assertThatIsWithinFails(2.0f, 1000.... |
@Override
@Deprecated
public <KR, VR> KStream<KR, VR> transform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, KeyValue<KR, VR>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNull(transformerSuppl... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullNamedOnTransformWithStoreName() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.transform(transformerSupplier, (Named) null, "storeName"));
assertThat(... |
@Override
public long remainTimeToLive(K key) {
return get(remainTimeToLiveAsync(key));
} | @Test
public void testRemainTimeToLive() {
RMapCacheNative<String, String> map = redisson.getMapCacheNative("test");
map.put("1", "2", Duration.ofSeconds(2));
assertThat(map.remainTimeToLive("1")).isBetween(1900L, 2000L);
map.put("3", "4");
assertThat(map.remainTimeToLive("3"... |
public void add(Task task) {
tasks.put('/' + task.getName(), task);
TaskExecutor taskExecutor = new TaskExecutor(task);
try {
final Method executeMethod = task.getClass().getMethod("execute",
Map.class, PrintWriter.class);
if (executeMethod.isAnnotat... | @Test
void testRunsExceptionMeteredTask() throws Exception {
final ServletInputStream bodyStream = new TestServletInputStream(
new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)));
final Task exceptionMeteredTask = new Task("exception-metered-task") {
@Override
... |
public static ClassLoader createNewClassLoader() throws KettleException {
try {
// Nothing really in URL, everything is in scope.
URL[] urls = new URL[] {};
URLClassLoader ucl = new URLClassLoader( urls );
return ucl;
} catch ( Exception e ) {
throw new KettleException( "Unexpecte... | @Test
public void testCreateNewClassLoader() throws KettleException {
ClassLoader cl = Const.createNewClassLoader();
assertTrue( cl instanceof URLClassLoader && ( (URLClassLoader) cl ).getURLs().length == 0 );
} |
@Override
public OutputT expand(InputT input) {
OutputT res = delegate().expand(input);
if (res instanceof PCollection) {
PCollection pc = (PCollection) res;
try {
pc.setCoder(delegate().getDefaultOutputCoder(input, pc));
} catch (CannotProvideCoderException e) {
// Let coder... | @Test
public void applyDelegates() {
@SuppressWarnings("unchecked")
PCollection<Integer> collection = mock(PCollection.class);
@SuppressWarnings("unchecked")
PCollection<String> output = mock(PCollection.class);
when(delegate.expand(collection)).thenReturn(output);
PCollection<String> result =... |
public static <C> AsyncBuilder<C> builder() {
return new AsyncBuilder<>();
} | @SuppressWarnings("resource")
@Test
void decodeLogicSupportsByteArray() throws Throwable {
byte[] expectedResponse = {12, 34, 56};
server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse)));
OtherTestInterfaceAsync api = AsyncFeign.builder().target(OtherTestInterfaceAsync.class,
... |
public List<Object> getData() {
List<Object> result = new ArrayList<>(cells.size());
for (QueryResponseCell cell : cells) {
result.add(cell.getData());
}
return result;
} | @Test
void assertGetDataWhenQueryResponseCellsPresent() {
QueryResponseCell queryResponseCell1 = new QueryResponseCell(Types.INTEGER, 1);
QueryResponseCell queryResponseCell2 = new QueryResponseCell(Types.VARCHAR, "column");
QueryResponseRow queryResponseRow = new QueryResponseRow(Arrays.asL... |
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = RedisKeyConstants.ROLE, key = "#id")
@LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_DELETE_SUB_TYPE, bizNo = "{{#id}}",
success = SYSTEM_ROLE_DELETE_SUCCESS)
public void deleteRole(Long id) {
// 1.... | @Test
public void testDeleteRole() {
// mock 数据
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType()));
roleMapper.insert(roleDO);
// 参数准备
Long id = roleDO.getId();
// 调用
roleService.deleteRole(id);
// 断言
asser... |
public Optional<File> getFile(FileReference reference) {
ensureRootExist();
File dir = new File(getPath(reference));
if (!dir.exists()) {
// This is common when config server has not yet received the file from one the server the app was deployed on
log.log(FINE, "File ref... | @Test
public void requireThatFileReferenceWithFilesWorks() throws IOException {
FileReference foo = createFile("foo");
FileReference bar = createFile("bar");
assertTrue(fileDirectory.getFile(foo).get().exists());
assertEquals("ea315b7acac56246", foo.value());
assertTrue(file... |
public static Tuple2<String, String> getNameAndNamespaceFromString(String nameDotNamespace) {
if (!nameDotNamespace.contains(".")) {
return new Tuple2<>(nameDotNamespace, "");
}
String name = nameDotNamespace.substring(nameDotNamespace.lastIndexOf(".") + 1);
String namespace ... | @Test
public void testNamespaceDotNames() {
String namespaceDotName = "foo.bar";
Tuple2<String, String> tuple = ConfigUtils.getNameAndNamespaceFromString(namespaceDotName);
assertEquals("bar", tuple.first);
assertEquals("foo", tuple.second);
namespaceDotName = "foo.baz.bar";... |
@Override
public ListenableFuture<HttpResponse> sendAsync(HttpRequest httpRequest) {
return sendAsync(httpRequest, null);
} | @Test
public void sendAsync_whenPostRequest_returnsExpectedHttpResponse()
throws IOException, ExecutionException, InterruptedException {
String responseBody = "{ \"test\": \"json\" }";
mockWebServer.enqueue(
new MockResponse()
.setResponseCode(HttpStatus.OK.code())
.setHe... |
@VisibleForTesting
static final String hostKey(String host) {
try {
final Matcher m = HOST_PATTERN.matcher(host);
// I know which type of host matched by the number of the group that is non-null
// I use a different replacement string per host type to make the Epic stats... | @Test
void createsNormalizedHostKey() {
assertEquals("host_EC2.amazonaws.com", StatsManager.hostKey("ec2-174-129-179-89.compute-1.amazonaws.com"));
assertEquals("host_IP", StatsManager.hostKey("12.345.6.789"));
assertEquals("host_IP", StatsManager.hostKey("ip-10-86-83-168"));
assertE... |
public GrpcChannel acquireChannel(GrpcNetworkGroup networkGroup,
GrpcServerAddress serverAddress, AlluxioConfiguration conf, boolean alwaysEnableTLS) {
GrpcChannelKey channelKey = getChannelKey(networkGroup, serverAddress, conf);
CountingReference<ManagedChannel> channelRef =
mChannels.compute(cha... | @Test
public void testEqualKeys() throws Exception {
try (CloseableTestServer server = createServer()) {
GrpcChannel conn1 = GrpcChannelPool.INSTANCE.acquireChannel(
GrpcNetworkGroup.RPC, server.getConnectAddress(), sConf, false);
GrpcChannel conn2 = GrpcChannelPool.INSTANCE.acquireChannel(
... |
static Collection<String> getMandatoryJvmOptions(int javaMajorVersion){
return Arrays.stream(MANDATORY_JVM_OPTIONS)
.map(option -> jvmOptionFromLine(javaMajorVersion, option))
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableList());
} | @Test
public void testMandatoryJvmOptionNonApplicableJvmNotPresent() throws IOException{
assertFalse("Does not contains add-exports value for Java 11",
JvmOptionsParser.getMandatoryJvmOptions(11).contains("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED"));
} |
public static boolean parse(final String str, ResTable_config out) {
return parse(str, out, true);
} | @Test
public void parse_layoutDirection_any() {
ResTable_config config = new ResTable_config();
ConfigDescription.parse("any", config);
assertThat(config.screenLayout).isEqualTo(LAYOUTDIR_ANY);
} |
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final Map<Path, List<String>> containers = new HashMap<>();
for(Path file : files.keySet()) {
if(containerService.isContainer(file)) {
... | @Test(expected = NotfoundException.class)
@Ignore
public void testDeleteNotFoundKey() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
new SwiftMultipleDeleteFeature(session).delete(Arrays.asList(
new Path... |
@Override
void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException {
// PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology)
// must be verified.
expectUtf8AsDefault(connection);
if (state == DatabaseCharse... | @Test
public void regular_startup_verifies_that_default_charset_and_columns_are_utf8() throws Exception {
answerDefaultCharset("utf8");
answerColumns(asList(
new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"},
new String[] {TABLE_PROJECTS, COLUMN_NAME, "utf8"}));
underTest.handle(connection, Dat... |
@VisibleForTesting
ImmutableList<EventWithContext> eventsFromAggregationResult(EventFactory eventFactory, AggregationEventProcessorParameters parameters, AggregationResult result)
throws EventProcessorException {
final ImmutableList.Builder<EventWithContext> eventsWithContext = ImmutableList.bui... | @Test
public void testEventsFromAggregationResult() throws EventProcessorException {
final DateTime now = DateTime.now(DateTimeZone.UTC);
final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.minusHours(1).plusMillis(SEARCH_WINDOW_MS));
// We expect to get the end of t... |
public final E submitterGoneItem() {
return submitterGoneItem;
} | @Test
public void submitterGoneItem() {
assertSame(doneItem, conveyor.submitterGoneItem());
} |
@Override
public double score(int[] truth, int[] prediction) {
return of(truth, prediction, strategy);
} | @Test
public void test() {
System.out.println("Precision");
int[] truth = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... |
@Override
public boolean accept(final Path file) {
if(!super.accept(file)) {
return false;
}
return proxy.accept(file);
} | @Test
public void testAccept() {
assertTrue(new DownloadGlobFilter("*.css").accept(new Path("/dir/f.css", EnumSet.of(Path.Type.file))));
assertFalse(new DownloadGlobFilter("*.css").accept(new Path("/dir/f.png", EnumSet.of(Path.Type.file))));
} |
@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Upload a content pack")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Missing or invalid content pack"),
@ApiResponse(code = 500, message = "Error while saving content pack")
})
@Audit... | @Test
public void uploadContentPack() throws Exception {
final ContentPack contentPack = objectMapper.readValue(CONTENT_PACK, ContentPack.class);
when(contentPackPersistenceService.filterMissingResourcesAndInsert(contentPack)).thenReturn(Optional.ofNullable(contentPack));
final Response res... |
@Override
public String resolve(Method method, Object[] arguments, String spelExpression) {
if (StringUtils.isEmpty(spelExpression)) {
return spelExpression;
}
if (spelExpression.matches(PLACEHOLDER_SPEL_REGEX) && stringValueResolver != null) {
return stringValueReso... | @Test
public void atTest() throws Exception {
DefaultSpelResolverTest target = new DefaultSpelResolverTest();
Method testMethod = target.getClass().getMethod("testMethod", String.class);
String result = sut.resolve(testMethod, new Object[]{}, "@");
assertThat(result).isEqualTo("@")... |
@Override
protected EnumDeclaration create(CompilationUnit compilationUnit) {
EnumDeclaration lambdaClass = super.create(compilationUnit);
boolean hasDroolsParameter = lambdaParameters.stream().anyMatch(this::isDroolsParameter);
if (hasDroolsParameter) {
bitMaskVariables.forEach... | @Test
public void createConsequence() {
CreatedClass aClass = new MaterializedLambdaConsequence("org.drools.modelcompiler.util.lambdareplace", "rulename", new ArrayList<>())
.create("(org.drools.model.codegen.execmodel.domain.Person p1, org.drools.model.codegen.execmodel.domain.Person p2) ->... |
@Override
public void createDataStream(String dataStreamName, String timestampField, Map<String, Map<String, String>> mappings,
Policy ismPolicy) {
updateDataStreamTemplate(dataStreamName, timestampField, mappings);
dataStreamAdapter.createDataStream(dataStreamName);... | @Test
public void createDataStreamPerformsFunctions() {
final String name = "teststream";
final String ts = "ts";
final Map<String, Map<String, String>> mappings = new HashMap<>();
final Policy policy = mock(Policy.class);
dataStreamService.createDataStream(name, ts, mappings... |
public Map<String, Object> offsetStorageTopicSettings() {
return topicSettings(OFFSET_STORAGE_PREFIX);
} | @Test
public void shouldRemoveCompactionFromOffsetTopicSettings() {
Map<String, String> expectedTopicSettings = new HashMap<>();
expectedTopicSettings.put("foo", "foo value");
expectedTopicSettings.put("bar", "bar value");
expectedTopicSettings.put("baz.bim", "100");
Map<Stri... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test
public void doesNotThrowNullPointerExceptionForEmptyVariable() throws JoranException {
context.putProperty("var", "");
OptionHelper.substVars("${var}", context);
} |
@Override
public <T> T unwrap(Class<T> clazz) {
if (clazz.isInstance(cache)) {
return clazz.cast(cache);
} else if (clazz.isInstance(this)) {
return clazz.cast(this);
}
throw new IllegalArgumentException("Unwrapping to " + clazz
+ " is not supported by this implementation");
} | @Test
public void unwrap_fail() {
assertThrows(IllegalArgumentException.class, () -> jcache.unwrap(CaffeineConfiguration.class));
} |
@Override
public void close() throws IOException {
GZIPOutputStream zos = (GZIPOutputStream) delegate;
zos.close();
} | @Test
public void testClose() throws IOException {
CompressionProvider provider = outStream.getCompressionProvider();
ByteArrayOutputStream out = new ByteArrayOutputStream();
outStream = new GZIPCompressionOutputStream( out, provider ) {
};
outStream.close();
try {
outStream.write( "This... |
public AccessTokenResponse createAccesToken(AccessTokenRequest request) throws NoSuchAlgorithmException, DienstencatalogusException {
var openIdSession = openIdRepository.findByCode(request.getCode()).orElseThrow(()
-> new OpenIdSessionNotFoundException("OpenIdSession not found"));
var ... | @Test
void createValidAccesTokenTest() throws NoSuchAlgorithmException, DienstencatalogusException, InvalidSignatureException, IOException, ParseException, JOSEException {
mockDcMetadataResponse();
AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
accessTokenRequest.setCode(... |
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) {
// Set of Visited Schemas
IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>();
// Stack that contains the Schams to process and afterVisitNonTerminal
// functions.
// Deque<Either<Schema, Supplier<SchemaVis... | @Test
void visit8() {
assertThrows(UnsupportedOperationException.class, () -> {
String s8 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": ["
+ "{\"name\": \"f1\", \"type\": {\"type\": \"record\", \"name\": \"cst2\", \"fields\": "
+ "[{\"name\": \"f11\", \"type\": \"int\"}]}}," + ... |
@NonNull
@Override
public Object configure(CNode config, ConfigurationContext context) throws ConfiguratorException {
return Stapler.lookupConverter(target)
.convert(
target,
context.getSecretSourceResolver()
... | @Test
public void _string_env() throws Exception {
environment.set("ENV_FOR_TEST", "abc");
Configurator c = registry.lookupOrFail(String.class);
final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context);
assertEquals("abc", value);
} |
@Udf
public <T> List<T> except(
@UdfParameter(description = "Array of values") final List<T> left,
@UdfParameter(description = "Array of exceptions") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> distinctRightValues = new HashSet<>(right);
fi... | @Test
public void shouldExceptFromArrayContainingNulls() {
final List<String> input1 = Arrays.asList("foo", null, "foo", "bar");
final List<String> input2 = Arrays.asList("foo");
final List<String> result = udf.except(input1, input2);
assertThat(result, contains(null, "bar"));
} |
@ConstantFunction(name = "seconds_add", argTypes = {DATETIME, INT}, returnType = DATETIME, isMonotonic = true)
public static ConstantOperator secondsAdd(ConstantOperator date, ConstantOperator second) {
return ConstantOperator.createDatetimeOrNull(date.getDatetime().plusSeconds(second.getInt()));
} | @Test
public void secondsAdd() {
assertEquals("2015-03-23T09:24:05",
ScalarOperatorFunctions.secondsAdd(O_DT_20150323_092355, O_INT_10).getDatetime().toString());
} |
@ExecuteOn(TaskExecutors.IO)
@Get(uri = "{namespace}/files/search")
@Operation(tags = {"Files"}, summary = "Find files which path contain the given string in their URI")
public List<String> search(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(descri... | @SuppressWarnings("unchecked")
@Test
void search() throws IOException {
storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/file.txt")), new ByteArrayInputStream(new byte[0]));
storageInterface.put(null, toNamespacedStorageUri(NAMESPACE, URI.create("/another_file.json")), n... |
public static boolean listRecording(
final File archiveDir, final long recordingId, final RecordingDescriptorConsumer consumer)
{
try (Catalog catalog = new Catalog(archiveDir, System::currentTimeMillis))
{
return catalog.forEntry(recordingId, new RecordingDescriptorConsumerAdapt... | @Test
void shouldListRecordingByRecordingId()
{
final boolean found = CatalogView.listRecording(archiveDir, recordingTwoId, mockRecordingDescriptorConsumer);
assertTrue(found);
verify(mockRecordingDescriptorConsumer).onRecordingDescriptor(
Aeron.NULL_VALUE, Aeron.NULL_VALUE,... |
protected boolean isFinalLeaf(final Node node) {
return node instanceof LeafNode || node.getNodes() == null || node.getNodes().isEmpty();
} | @Test
void isFinalLeaf() {
Node node = new LeafNode();
DATA_TYPE targetType = DATA_TYPE.STRING;
KiePMMLTreeModelNodeASTFactory.factory(new HashMap<>(), Collections.emptyList(), TreeModel.NoTrueChildStrategy.RETURN_NULL_PREDICTION, targetType).isFinalLeaf(node);
assertThat(KiePMMLTree... |
public static Optional<Cookie> findCookie(String cookieName, HttpRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return Optional.empty();
}
return Arrays.stream(cookies)
.filter(cookie -> cookieName.equals(cookie.getName()))
.findFirst();
} | @Test
public void does_not_fail_to_find_cookie_when_no_cookie() {
assertThat(findCookie("unknown", request)).isEmpty();
} |
public String generatePrimitiveTypeColumnTask(long tableId, long dbId, String tableName, String dbName,
List<ColumnStats> primitiveTypeStats,
TabletSampleManager manager) {
String prefix = "INSERT INTO " + STATIS... | @Test
public void generateSubFieldTypeColumnTask() {
SampleInfo sampleInfo = tabletSampleManager.generateSampleInfo("test", "t_struct");
List<String> columnNames = Lists.newArrayList("c1", "c4.b", "c6.c.b");
List<Type> columnTypes = Lists.newArrayList(Type.DATE, new ArrayType(Type.ANY_STRUCT... |
@Override
public KeyVersion createKey(final String name, final byte[] material,
final Options options) throws IOException {
return doOp(new ProviderCallable<KeyVersion>() {
@Override
public KeyVersion call(KMSClientProvider provider) throws IOException {
return provider.createKey(name, m... | @Test
public void testClientRetriesSpecifiedNumberOfTimes() throws Exception {
Configuration conf = new Configuration();
conf.setInt(
CommonConfigurationKeysPublic.KMS_CLIENT_FAILOVER_MAX_RETRIES_KEY, 10);
KMSClientProvider p1 = mock(KMSClientProvider.class);
when(p1.createKey(Mockito.anyStrin... |
public static String configKey(Class targetType, Method method) {
StringBuilder builder = new StringBuilder();
builder.append(targetType.getSimpleName());
builder.append('#').append(method.getName()).append('(');
for (Type param : method.getGenericParameterTypes()) {
param = Types.resolve(targetTy... | @Test
void configKeyUsesChildType() throws Exception {
assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator")))
.isEqualTo("List#iterator()");
} |
@Override
public JavaKeyStore load(SecureConfig config) {
if (!exists(config)) {
throw new SecretStoreException.LoadException(
String.format("Can not find Logstash keystore at %s. Please verify this file exists and is a valid Logstash keystore.",
c... | @Test
public void notLogstashKeystoreNoMarker() throws Exception {
withDefinedPassConfig.add("keystore.file", Paths.get(this.getClass().getClassLoader().getResource("not.a.logstash.keystore").toURI()).toString().toCharArray().clone());
assertThrows(SecretStoreException.LoadException.class, () -> {
... |
public void asyncDestroy() {
if (!(dataSource instanceof AutoCloseable)) {
return;
}
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(this::graceDestroy);
executor.shutdown();
} | @Test
void assertAsyncDestroyWithoutAutoCloseableDataSource() {
assertDoesNotThrow(() -> new DataSourcePoolDestroyer(new MockedDataSource()).asyncDestroy());
} |
@Override
public DescribeConsumerGroupsResult describeConsumerGroups(final Collection<String> groupIds,
final DescribeConsumerGroupsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, ConsumerGroupDescription> future =
Descri... | @Test
public void testDescribeMultipleConsumerGroups() {
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
env.kafkaClient().prepareResponse(prepareFindCoordinatorResponse(Errors.NONE, e... |
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
} | @Test
public void testIncrementalFromSnapshotTimestamp() throws Exception {
appendTwoSnapshots();
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_SNAPSHOT_TIMESTAMP)
.startSnapshotTimestamp(snapshot2.timestampMillis(... |
@Override
@DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换
public void updateTenantPackage(TenantPackageSaveReqVO updateReqVO) {
// 校验存在
TenantPackageDO tenantPackage = validateTenantPackageExists(updateReqVO.getId());
// 更新
TenantPackageDO updateObj = BeanUtils.toBea... | @Test
public void testUpdateTenantPackage_success() {
// mock 数据
TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class,
o -> o.setStatus(randomCommonStatus()));
tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据
// 准备参数
TenantPackage... |
@SafeVarargs
public static <T> List<T> newLists(T... values) {
if(null == values || values.length == 0){
Assert.notNull(values, "values not is null.");
}
return Arrays.asList(values);
} | @Test
public void newLists() {
final Object[] values = {};
Assert.assertEquals(new ArrayList(), CollectionKit.newLists(values));
} |
public static <FROM, TO> MappedCondition<FROM, TO> mappedCondition(Function<FROM, TO> mapping, Condition<TO> condition,
String mappingDescription, Object... args) {
requireNonNull(mappingDescription, "The given mappingDescription should not be nul... | @Test
void mappedCondition_without_description_and_null_condition_should_throw_NPE() {
// GIVEN
Condition<String> nullCondition = null;
// WHEN/THEN
thenNullPointerException().isThrownBy(() -> mappedCondition(StringBuilder::toString, nullCondition))
.withMessage("The give... |
@Override
public Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Optional<ResourceNameAndAction> resourceMapping =
requestResourceMapper.getResourceNameAndAction(request);
log.log(Level.FINE, () -> String.format("Resource mapping for '%s': %s", r... | @Test
void accepts_request_with_role_token() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
DiscFilterRequest request = createRequest(ROLE_TOKEN, null, null);
filter.filter(request, re... |
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
return usage(args);
}
String action = args[0];
String name = args[1];
int result;
if (A_LOAD.equals(action)) {
result = loadClass(name);
} else if (A_CREATE.equals(action)) {
//first load t... | @Test
public void testFindsResource() throws Throwable {
run(FindClass.SUCCESS,
FindClass.A_RESOURCE, "org/apache/hadoop/util/TestFindClass.class");
} |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultQueryCacheEventData that = (DefaultQueryCacheEventData) o;
if (sequence != that.sequence) {
... | @Test
public void testEquals() {
assertEquals(queryCacheEventData, queryCacheEventData);
assertEquals(queryCacheEventData, queryCacheEventDataSameAttributes);
assertNotEquals(null, queryCacheEventData);
assertNotEquals(new Object(), queryCacheEventData);
assertNotEquals(que... |
public CoercedExpressionResult coerce() {
final Class<?> leftClass = left.getRawClass();
final Class<?> nonPrimitiveLeftClass = toNonPrimitiveType(leftClass);
final Class<?> rightClass = right.getRawClass();
final Class<?> nonPrimitiveRightClass = toNonPrimitiveType(rightClass);
... | @Test
public void avoidCoercing2() {
final TypedExpression left = expr("$pr.compareTo(new BigDecimal(\"0.0\"))", int.class);
final TypedExpression right = expr("0", int.class);
final CoercedExpression.CoercedExpressionResult coerce = new CoercedExpression(left, right, false).coerce();
... |
@Override
public void close() {
if (_executionFuture != null) {
_executionFuture.cancel(true);
}
} | @Test
public void shouldReturnDataBlockThenMetadataBlock() {
// Given:
QueryContext queryContext = QueryContextConverterUtils.getQueryContext("SELECT strCol, intCol FROM tbl");
DataSchema schema = new DataSchema(new String[]{"strCol", "intCol"},
new DataSchema.ColumnDataType[]{DataSchema.ColumnDat... |
@SafeVarargs
public static <T> Set<T> intersectionDistinct(Collection<T> coll1, Collection<T> coll2, Collection<T>... otherColls) {
final Set<T> result;
if (isEmpty(coll1) || isEmpty(coll2)) {
// 有一个空集合就直接返回空
return new LinkedHashSet<>();
} else {
result = new LinkedHashSet<>(coll1);
}
if (ArrayUti... | @Test
public void intersectionDistinctNullTest() {
final List<String> list1 = new ArrayList<>();
list1.add("aa");
final List<String> list2 = null;
// list2.add("aa");
final List<String> list3 = null;
final Collection<String> collection = CollUtil.intersectionDistinct(list1, list2, list3);
assertNotNull(c... |
@Override
public boolean find(Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
try {
final boolean found;
if(containerService.isContainer(file)) {
... | @Test
public void testFindFile() throws Exception {
final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
new AzureTouchFeature(sessio... |
public static void onServiceStart(Service service, Intent intent, int startId) {
onBroadcastServiceIntent(intent);
} | @Test
public void onServiceStart() {
Service service = new Service() {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
};
PushAutoTrackHelper.onServiceStart(service, null, 100);
} |
static JavaType constructType(Type type) {
try {
return constructTypeInner(type);
} catch (Exception e) {
throw new InvalidDataTableTypeException(type, e);
}
} | @Test
void upper_bound_of_wild_card_parameterized_type_replaces_wild_card_type() {
JavaType javaType = TypeFactory.constructType(SUPPLIER_WILD_CARD_NUMBER);
TypeFactory.Parameterized parameterized = (TypeFactory.Parameterized) javaType;
JavaType elementType = parameterized.getElementTypes()[... |
@Override
public boolean readBoolean(@Nonnull String fieldName) throws IOException {
FieldDefinition fd = cd.getField(fieldName);
if (fd == null) {
return false;
}
validateTypeCompatibility(fd, BOOLEAN);
return super.readBoolean(fieldName);
} | @Test
public void testReadBoolean() throws Exception {
boolean aBoolean = reader.readBoolean("boolean");
assertTrue(aBoolean);
assertFalse(reader.readBoolean("NO SUCH FIELD"));
} |
public Collection<QualifiedTable> getSingleTables(final Collection<QualifiedTable> qualifiedTables) {
Collection<QualifiedTable> result = new LinkedList<>();
for (QualifiedTable each : qualifiedTables) {
Collection<DataNode> dataNodes = singleTableDataNodes.getOrDefault(each.getTableName().t... | @Test
void assertRemove() {
SingleRule singleRule = new SingleRule(ruleConfig, DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), dataSourceMap, Collections.singleton(mock(ShardingSphereRule.class, RETURNS_DEEP_STUBS)));
String tableName = "employee";
singleRule.getAttributes().getAttribute(M... |
@Cacheable(value = "metadata-response", key = "#samlMetadataRequest.cacheableKey()")
public SamlMetadataResponse resolveSamlMetadata(SamlMetadataRequest samlMetadataRequest) {
LOGGER.info("Cache not found for saml-metadata {}", samlMetadataRequest.hashCode());
Connection connection = connectionServ... | @Test
void connectionInactiveTest() {
Connection connection = newConnection(SAML_COMBICONNECT, false, true, true);
when(connectionServiceMock.getConnectionByEntityId(anyString())).thenReturn(connection);
SamlMetadataResponse response = metadataRetrieverServiceMock.resolveSamlMetadata(newMeta... |
@Override
protected double maintain() {
if (!nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0;
NodeList candidates = nodeRepository().nodes().list()
.parents()
.not().deprovisioning();
... | @Test
public void retire_hosts() {
NodeFlavors flavors = FlavorConfigBuilder.createDummies("default");
MockHostProvisioner hostProvisioner = new MockHostProvisioner(flavors.getFlavors());
ProvisioningTester tester = new ProvisioningTester.Builder().hostProvisioner(hostProvisioner)
... |
public static Options options() {
final Options options = new Options();
final OptionGroup actionGroup = new OptionGroup();
actionGroup.addOption(Option.builder()
.longOpt(TerminalAction.upload.name())
.desc("Upload file or folder recursively")
.h... | @Test
public void testOptions() {
assertNotNull(TerminalOptionsBuilder.options());
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetBalance() throws Exception {
web3j.ethGetBalance(
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
DefaultBlockParameterName.LATEST)
.send();
verifyResult(
"{\"jsonrpc\":\"2.0\",\"method\":\"eth... |
@Override
public List<URIStatus> listStatus(AlluxioURI path, ListStatusPOptions options)
throws FileDoesNotExistException, IOException, AlluxioException {
if (options.getRecursive()) {
// Do not cache results of recursive list status,
// because some results might be cached multiple times.
... | @Test
public void listStatusRecursive() throws Exception {
mFs.listStatus(DIR, LIST_STATUS_OPTIONS.toBuilder().setRecursive(true).build());
assertEquals(1, mRpcCountingFs.listStatusRpcCount(DIR));
mFs.listStatus(DIR, LIST_STATUS_OPTIONS.toBuilder().setRecursive(true).build());
assertEquals(2, mRpcCoun... |
public String getDropTableIfExistsStatement( String tableName ) {
if ( databaseInterface instanceof DatabaseInterfaceExtended ) {
return ( (DatabaseInterfaceExtended) databaseInterface ).getDropTableIfExistsStatement( tableName );
}
// A fallback statement in case somehow databaseInterface is of an ol... | @Test
public void shouldFallBackWhenDatabaseInterfaceIsOfAnOldType() {
String statement = databaseMeta.getDropTableIfExistsStatement( TABLE_NAME );
assertEquals( DROP_STATEMENT_FALLBACK, statement );
} |
@Override
public ConfigData get(String path) {
return get(path, null);
} | @Test
void testGetMultipleKeysAndCompare() {
ConfigData properties = envVarConfigProvider.get("");
assertNotEquals(0, properties.data().size());
assertEquals("value1", properties.data().get("test_var1"));
assertEquals("value2", properties.data().get("secret_var2"));
assertEqu... |
@Override
public String getName() {
return ANALYZER_NAME;
} | @Test
public void testGetAnalyzerName() {
assertEquals("Nuspec Analyzer", instance.getName());
} |
public void setStringIfNotNull(@NotNull final String key, @Nullable final String value) {
if (null != value) {
setString(key, value);
}
} | @Test
public void testSetStringIfNotNull() {
String key = "nullableProperty";
String value = "someValue";
getSettings().setString(key, value);
getSettings().setStringIfNotNull(key, null); // NO-OP
String expResults = getSettings().getString(key);
Assert.assertEquals(e... |
char[] decode(final ByteBuf in)
{
final CharBuffer charBuffer = CharBuffer.allocate(in.capacity());
encoder.reset();
final ByteBuffer nioBuffer = in.nioBuffer();
encoder.decode(nioBuffer, charBuffer, false);
final char[] buf = new char[charBuffer.position()];
charBuff... | @Test
public void testDecodeFirstByteOfMultibyteChar() throws Exception
{
// Setup test fixture.
final byte[] multibyteCharacter = "\u3053".getBytes(StandardCharsets.UTF_8); // 3-byte character.
final XMLLightweightParser parser = new XMLLightweightParser();
final ByteBuf in = By... |
synchronized O init(final E e) {
if (o != null) {
return o;
}
O res = function.apply(e);
o = res;
return res;
} | @Test
public void testInit() {
Function<String, String> function = Function.identity();
FreshBeanHolder<String, String> freshBeanHolder = new FreshBeanHolder<>(function);
freshBeanHolder.init("hello world");
assertEquals("hello world", freshBeanHolder.init("hello"));
} |
public void smoke() {
tobacco.smoke(this);
} | @Test
void testSmoke() {
final var simpleWizard = new SimpleWizard();
simpleWizard.smoke();
assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage());
assertEquals(1, appender.getLogSize());
} |
public static String getPropsVersionNode(final String version) {
return String.join("/", getPropsVersionsNode(), version);
} | @Test
void assertGetPropsVersionNode() {
assertThat(GlobalNode.getPropsVersionNode("0"), is("/props/versions/0"));
} |
@Override public String toString() {
return path();
} | @Test
public void shouldReturnPath_asToString() {//this is important because its used in xml fragment that is spit out on job-console
assertThat(new PathFromAncestor(new CaseInsensitiveString("grand-parent/parent/child")).toString(), is("grand-parent/parent/child"));
} |
@Override
public Topology currentTopology() {
Iterable<Device> devices = manager.getVirtualDevices(networkId())
.stream()
.collect(Collectors.toSet());
Iterable<Link> links = manager.getVirtualLinks(networkId())
.stream()
.collect(Colle... | @Test
public void testCurrentTopology() {
VirtualNetwork virtualNetwork = setupVirtualNetworkTopology();
TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class);
Topology topology = topologyService.currentTopology();
assertNotNull("The topology shou... |
public NonClosedTracking<RAW, BASE> trackNonClosed(Input<RAW> rawInput, Input<BASE> baseInput) {
NonClosedTracking<RAW, BASE> tracking = NonClosedTracking.of(rawInput, baseInput);
// 1. match by rule, line, line hash and message
match(tracking, LineAndLineHashAndMessage::new);
// 2. match issues with ... | @Test
public void line_hash_has_greater_priority_than_line() {
FakeInput baseInput = new FakeInput("H1", "H2", "H3");
Issue base1 = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
Issue base2 = baseInput.createIssueOnLine(3, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("a",... |
@VisibleForTesting
public long getTimeout() {
return timeout;
} | @Test
public void testUserUpdateSetting() throws IOException {
ShellBasedIdMapping iug = new ShellBasedIdMapping(new Configuration());
assertThat(iug.getTimeout()).isEqualTo(
IdMappingConstant.USERGROUPID_UPDATE_MILLIS_DEFAULT);
Configuration conf = new Configuration();
conf.setLong(IdMapping... |
public BranchesList getBranches(String serverUrl, String token, String projectSlug, String repositorySlug) {
HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s/branches", projectSlug, repositorySlug));
return doGet(token, url, body -> buildGson().fromJson(body, BranchesList.class));
... | @Test
public void getBranches_given2Branches_returnListWithTwoBranches() {
String bodyWith2Branches = "{\n" +
" \"size\": 2,\n" +
" \"limit\": 25,\n" +
" \"isLastPage\": true,\n" +
" \"values\": [{\n" +
" \"id\": \"refs/heads/demo\",\n" +
" \"displayId\": \"demo\",\n"... |
public void setDataId(String dataId) {
this.dataId = dataId;
} | @Test
void setDataId() {
ConfigFuture configFuture = new ConfigFuture("file.conf", "defaultValue", ConfigFuture.ConfigOperation.GET);
Assertions.assertEquals("file.conf", configFuture.getDataId());
configFuture.setDataId("file-test.conf");
Assertions.assertEquals("file-test.conf", co... |
public void unlockBatchMQ(
final String addr,
final UnlockBatchRequestBody requestBody,
final long timeoutMillis,
final boolean oneway
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestC... | @Test
public void testUnlockBatchMQ() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
UnlockBatchRequestBody unlockBatchRequestBody = new UnlockBatchRequestBody();
mqClientAPI.unlockBatchMQ(defaultBrokerAddr, unlockBatchRequestBody, defaultTimeout, false... |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QProfile qProfile = (QProfile) o;
return key.equals(qProfile.key);
} | @Test
public void testEquals() {
QProfile q1 = new QProfile("k1", "name1", null, null);
QProfile q2 = new QProfile("k1", "name2", null, null);
QProfile q3 = new QProfile("k3", "name3", null, null);
assertThat(q1)
.isEqualTo(q2)
.isNotEqualTo(q3)
.isNotNull()
.isNotEqualTo("str... |
public void expand(String key, long value, RangeHandler rangeHandler, EdgeHandler edgeHandler) {
if (value < lowerBound || value > upperBound) {
// Value outside bounds -> expand to nothing.
return;
}
int maxLevels = value > 0 ? maxPositiveLevels : maxNegativeLevels;
... | @Test
void requireThatMaxRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
expander.expand("key", 9223372036854775807L, range -> fail(),
(edge, value) -> {
assertEquals(PredicateHash.hash64("key=9223372036854775800"), ed... |
public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException {
UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream)));
return parser.parse();
} | @Test
public void testParseIssue33() throws IOException {
UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(
UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue33.diff"));
assertThat(diff.getFiles().size()).isEqualTo(1);
UnifiedDiffFile file1 = diff.getF... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.