focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void checkTopicAccess(
final KsqlSecurityContext securityContext,
final String topicName,
final AclOperation operation
) {
checkAccess(new CacheKey(securityContext,
AuthObjectType.TOPIC,
topicName,
operation));
} | @Test
public void shouldThrowExceptionWhenBackendValidatorThrowsAnException() {
// Given
doThrow(RuntimeException.class).when(backendValidator)
.checkTopicAccess(securityContext, TOPIC_1, AclOperation.READ);
// When:
assertThrows(
RuntimeException.class,
() -> cache.checkTopic... |
Spec getSpec() {
return spec;
} | @Test
void basic() {
ProxyServer proxy = createTestServer(new MockConfigSource());
Spec spec = new Spec("localhost", 12345);
ConfigProxyRpcServer server = new ConfigProxyRpcServer(proxy, new Supervisor(new Transport()), spec);
assertEquals(spec, server.getSpec());
} |
public boolean ping() {
String checkPath = Joiner.on(PATH_DELIMITER).join(location,
joinPrefix(prefixRepo, name));
Status st = storage.checkPathExist(checkPath);
if (!st.ok()) {
errMsg = TimeUtils.longToTimeString(System.currentTimeMillis()) + ": " + st.getErrMsg();
... | @Test
public void testPing() {
new Expectations() {
{
storage.checkPathExist(anyString);
minTimes = 0;
result = Status.OK;
}
};
repo = new Repository(10000, "repo", false, location, storage);
Assert.assertTrue(r... |
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
} | @Test
public void test_get_float() {
Settings settings = new MapSettings();
settings.setProperty("from_float", 3.14159f);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_float")).isEqualTo(3.14159f, Offset.offset(0.00001));
assertThat(settings.getDouble("from_st... |
public static ValueLabel formatBytes(long bytes) {
return new ValueLabel(bytes, BYTES_UNIT);
} | @Test
public void formatKiloBytes() {
vl = TopoUtils.formatBytes(2_000L);
assertEquals(AM_WM, TopoUtils.Magnitude.KILO, vl.magnitude());
assertEquals(AM_WL, "1.95 KB", vl.toString());
} |
@Override
public Stream<MappingField> resolveAndValidateFields(
boolean isKey,
List<MappingField> userFields,
Map<String, String> options,
InternalSerializationService serializationService
) {
Map<QueryPath, MappingField> fieldsByPath = extractFields(userF... | @Test
@Parameters({
"true, __key",
"false, this"
})
public void when_userDeclaresFields_then_fieldsNotAddedFromClassDefinition(boolean key, String prefix) {
InternalSerializationService ss = new DefaultSerializationServiceBuilder().build();
ClassDefinition classDefini... |
public static <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, DoFnSignatures::parseSignature);
} | @Test
public void testMismatchingElementType() throws Exception {
DoFnSignature sig =
DoFnSignatures.getSignature(
new DoFn<String, String>() {
@ProcessElement
public void process(@Element Integer element) {}
}.getClass());
assertThat(sig.processElem... |
@Override
public KeyValueIterator<Windowed<K>, V> all() {
return new KeyValueIteratorFacade<>(inner.all());
} | @Test
public void shouldReturnPlainKeyValuePairsOnAll() {
when(mockedKeyValueWindowTimestampIterator.next())
.thenReturn(KeyValue.pair(
new Windowed<>("key1", new TimeWindow(21L, 22L)),
ValueAndTimestamp.make("value1", 22L)))
.thenReturn(KeyValue.pair(... |
void generate(MessageSpec message) throws Exception {
if (message.struct().versions().contains(Short.MAX_VALUE)) {
throw new RuntimeException("Message " + message.name() + " does " +
"not specify a maximum version.");
}
structRegistry.register(message);
schema... | @Test
public void testInvalidNullDefaultForNullableStruct() throws Exception {
MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList(
"{",
" \"type\": \"request\",",
" \"name\": \"FooBar\",",
" \"validVersions\": ... |
@Override
public String toString() {
return "CSV Input ("
+ StringUtils.showControlCharacters(String.valueOf(getFieldDelimiter()))
+ ") "
+ Arrays.toString(getFilePaths());
} | @Test
void testPojoTypeWithMappingInformation() throws Exception {
File tempFile = File.createTempFile("CsvReaderPojoType", "tmp");
tempFile.deleteOnExit();
tempFile.setWritable(true);
OutputStreamWriter wrt = new OutputStreamWriter(new FileOutputStream(tempFile));
wrt.write... |
protected Timestamp convertBigNumberToTimestamp( BigDecimal bd ) {
if ( bd == null ) {
return null;
}
return convertIntegerToTimestamp( bd.longValue() );
} | @Test
public void testConvertBigNumberToTimestamp_DefaultMode() throws KettleValueException {
System.setProperty( Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE,
Const.KETTLE_TIMESTAMP_NUMBER_CONVERSION_MODE_LEGACY );
ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp();
Timestamp result ... |
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns... | @Test
void shouldCorsFilterDeactivatedForNullAllowedOrigins() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/... |
public static TableMetadata newTableMetadata(
Schema schema,
PartitionSpec spec,
SortOrder sortOrder,
String location,
Map<String, String> properties) {
int formatVersion =
PropertyUtil.propertyAsInt(
properties, TableProperties.FORMAT_VERSION, DEFAULT_TABLE_FORMAT_... | @Test
public void testNoReservedPropertyForTableMetadataCreation() {
Schema schema = new Schema(Types.NestedField.required(10, "x", Types.StringType.get()));
assertThatThrownBy(
() ->
TableMetadata.newTableMetadata(
schema,
PartitionSpec.unp... |
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {
zkClient.createOrUpdate(getNodePath(subscriberMetadataIdentifier), urls, false);
} | @Test
void testDoSaveSubscriberData() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-cons... |
public String getContext() {
return context;
} | @Test
public void testBuilderAppendIfAbsent() {
Configuration conf = new Configuration();
conf.set(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, "$");
CallerContext.Builder builder = new CallerContext.Builder(null, conf);
builder.append("key1", "value1");
Assert.assertEquals("key1:value1",
builder.... |
public void onPeriodicEmit() {
updateCombinedWatermark();
} | @Test
void deferredOutputDoesNotImmediatelyAdvanceWatermark() {
TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput();
WatermarkOutputMultiplexer multiplexer =
new WatermarkOutputMultiplexer(underlyingWatermarkOutput);
WatermarkOutput watermarkOut... |
@Override
public List<String> selectList(String text) {
List<String> results = new ArrayList<String>();
for (Selector selector : selectors) {
List<String> strings = selector.selectList(text);
results.addAll(strings);
}
return results;
} | @Test
public void testSelectList() {
String htmlContent = "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
... |
public static <T> T getProxy(Class<T> protocol,
long clientVersion,
InetSocketAddress addr, Configuration conf,
SocketFactory factory) throws IOException {
return getProtocolProxy(
protocol, clientVersion, addr, ... | @Test
public void testClientWithoutServer() throws Exception {
TestRpcService proxy;
short invalidPort = 20;
InetSocketAddress invalidAddress = new InetSocketAddress(ADDRESS,
invalidPort);
long invalidClientVersion = 1L;
try {
proxy = RPC.getProxy(TestRpcService.class,
inv... |
@NonNull
public String processShownotes() {
String shownotes = rawShownotes;
if (TextUtils.isEmpty(shownotes)) {
Log.d(TAG, "shownotesProvider contained no shownotes. Returning 'no shownotes' message");
shownotes = "<html><head></head><body><p id='apNoShownotes'>" + noShowno... | @Test
public void testProcessShownotesAddTimecodeMmssNoChapters() {
final String timeStr = "10:11";
final long time = 10 * 60 * 1000 + 11 * 1000;
String shownotes = "<p> Some test text with a timecode " + timeStr + " here.</p>";
ShownotesCleaner t = new ShownotesCleaner(context, sho... |
public static char[] asciiBytesToChar(byte[] bytes) {
char[] chars = new char[bytes.length];
for (int i = 0; i < bytes.length; i++) {
chars[i] = (char) bytes[i];
bytes[i] = '\0';
}
return chars;
} | @Test
public void testAsciiBytesToChar() {
byte[] asciiBytes = asciiString.getBytes(StandardCharsets.US_ASCII);
char[] asciiChars = SecretStoreUtil.asciiBytesToChar(asciiBytes);
assertThat(asciiChars).isEqualTo(asciiString.toCharArray());
assertThat(asciiBytes).containsOnly('\0');
... |
public static boolean equals(FlatRecordTraversalObjectNode left, FlatRecordTraversalObjectNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (!left.getSchema().getName().equals(right.ge... | @Test
public void differentSet() {
SimpleHollowDataset dataset = SimpleHollowDataset.fromClassDefinitions(Movie.class);
FakeHollowSchemaIdentifierMapper idMapper = new FakeHollowSchemaIdentifierMapper(dataset);
HollowObjectMapper objMapper = new HollowObjectMapper(HollowWriteStateCreator.cre... |
@Override
@CacheEvict(cacheNames = "ai:video:config", key = "#updateReqVO.type")
public void updateAiVideoConfig(AiVideoConfigUpdateReqVO updateReqVO) {
// 校验存在
validateAiVideoConfigExists(updateReqVO.getId());
// 更新
AiVideoConfigDO updateObj = AiVideoConfigConvert.INSTANCE.conve... | @Test
public void testUpdateAiVideoConfig_success() {
// mock 数据
AiVideoConfigDO dbAiVideoConfig = randomPojo(AiVideoConfigDO.class);
aiVideoConfigMapper.insert(dbAiVideoConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
AiVideoConfigUpdateReqVO reqVO = randomPojo(AiVideoConfigUpdateReqVO.... |
public boolean fence(HAServiceTarget fromSvc) {
return fence(fromSvc, null);
} | @Test
public void testMultipleFencers() throws BadFencingConfigurationException {
NodeFencer fencer = setupFencer(
AlwaysSucceedFencer.class.getName() + "(foo)\n" +
AlwaysSucceedFencer.class.getName() + "(bar)\n");
assertTrue(fencer.fence(MOCK_TARGET));
// Only one call, since the first fe... |
public static CustomWeighting.Parameters createWeightingParameters(CustomModel customModel, EncodedValueLookup lookup) {
String key = customModel.toString();
Class<?> clazz = customModel.isInternal() ? INTERNAL_CACHE.get(key) : null;
if (CACHE_SIZE > 0 && clazz == null)
clazz = CACHE... | @Test
void setPriorityForRoadClass() {
CustomModel customModel = new CustomModel();
customModel.addToPriority(If("road_class == PRIMARY", MULTIPLY, "0.5"));
customModel.addToSpeed(If("true", LIMIT, "100"));
CustomWeighting.EdgeToDoubleMapping priorityMapping = CustomModelParser.creat... |
public ProtocolBuilder threadpool(String threadpool) {
this.threadpool = threadpool;
return getThis();
} | @Test
void threadpool() {
ProtocolBuilder builder = new ProtocolBuilder();
builder.threadpool("mockthreadpool");
Assertions.assertEquals("mockthreadpool", builder.build().getThreadpool());
} |
public Properties getProperties()
{
return properties;
} | @Test
public void testUriWithSslEnabledPathOnly()
throws SQLException
{
PrestoDriverUri parameters = createDriverUri("presto://localhost:8080/blackhole?SSL=true&SSLTrustStorePath=truststore.jks");
assertUriPortScheme(parameters, 8080, "https");
Properties properties = parame... |
@Override
@MethodNotAvailable
public V replace(K key, V newValue) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testReplace() {
adapter.replace(23, "value");
} |
public boolean isEnabled() {
return enabled;
} | @Test
public void testWebsocketSyncPropertiesDefaultValue() {
assertThat(new WebsocketSyncProperties().isEnabled(), is(true));
} |
@VisibleForTesting
static void validateWorkerSettings(DataflowPipelineWorkerPoolOptions workerOptions) {
DataflowPipelineOptions dataflowOptions = workerOptions.as(DataflowPipelineOptions.class);
validateSdkContainerImageOptions(workerOptions);
GcpOptions gcpOptions = workerOptions.as(GcpOptions.class);... | @Test
public void testZoneAndWorkerRegionMutuallyExclusive() {
DataflowPipelineWorkerPoolOptions options =
PipelineOptionsFactory.as(DataflowPipelineWorkerPoolOptions.class);
options.setZone("us-east1-b");
options.setWorkerRegion("us-east1");
assertThrows(
IllegalArgumentException.clas... |
public FEELFnResult<List<Object>> invoke(@ParameterName("list") Object[] lists) {
if ( lists == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "lists", "cannot be null"));
}
final Set<Object> resultSet = new LinkedHashSet<>();
for ( final Obj... | @Test
void invokeMixedTypes() {
FunctionTestUtil.assertResultList(
unionFunction.invoke(new Object[]{"test", Arrays.asList(10, "test", 5), BigDecimal.TEN}),
Arrays.asList("test", 10, 5, BigDecimal.TEN));
} |
@Override
public void close() throws IOException {
InputFileBlockHolder.unset();
// close the current iterator
this.currentIterator.close();
// exhaust the task iterator
while (tasks.hasNext()) {
tasks.next();
}
} | @Test
public void testClosureWithoutAnyRead() throws IOException {
Integer totalTasks = 10;
Integer recordPerTask = 10;
List<FileScanTask> tasks = createFileScanTasks(totalTasks, recordPerTask);
ClosureTrackingReader reader = new ClosureTrackingReader(table, tasks);
reader.close();
tasks.fo... |
@POST
@Timed
@ApiOperation(
value = "Launch input on this node",
response = InputCreated.class
)
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No such input type registered"),
@ApiResponse(code = 400, message = "Missing or invalid configurati... | @Test
public void testCreateNotGlobalInputInCloud() {
when(configuration.isCloud()).thenReturn(true);
when(inputCreateRequest.global()).thenReturn(false);
assertThatThrownBy(() -> inputsResource.create(inputCreateRequest)).isInstanceOf(BadRequestException.class)
.hasMessageC... |
public void initialize(ConnectorContext ctx) {
context = ctx;
} | @Test
public void shouldInitializeContextWithTaskConfigs() {
List<Map<String, String>> taskConfigs = new ArrayList<>();
connector.initialize(context, taskConfigs);
assertableConnector.assertInitialized();
assertableConnector.assertContext(context);
assertableConnector.assertT... |
public static BadRequestException create(String... errorMessages) {
return create(asList(errorMessages));
} | @Test
public void text_error() {
BadRequestException exception = BadRequestException.create("error");
assertThat(exception.getMessage()).isEqualTo("error");
} |
public abstract Duration parse(String text); | @Test
public void testLongCombined() {
Assert.assertEquals(Duration.parse("P2DT3H4M5S"), DurationStyle.LONG.parse("2 days 3 Hours\t 4 minute 5 seconds"));
} |
@VisibleForTesting
Object evaluate(final GenericRow row) {
return term.getValue(new TermEvaluationContext(row));
} | @Test
public void shouldEvaluateLikePredicate() {
// Given:
final Expression expression1 = new LikePredicate(
new StringLiteral("catdog"), new StringLiteral("ca%og"), Optional.empty()
);
final Expression expression2 = new LikePredicate(
new StringLiteral("cat%og"), new StringLiteral("c... |
@Override
public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) {
return getDescriptionInHtml(rule)
.map(this::generateSections)
.orElse(emptySet());
} | @Test
public void parse_returns_all_empty_fields_when_empty_description() {
when(rule.htmlDescription()).thenReturn("");
Set<RuleDescriptionSectionDto> results = generator.generateSections(rule);
assertThat(results).isEmpty();
} |
@Deactivate
public void deactivate() {
deviceService.removeListener(deviceListener);
store.unsetDelegate(delegate);
eventDispatcher.removeSink(AlarmEvent.class);
log.info("Stopped");
} | @Test
public void deactivate() throws Exception {
providerService.updateAlarmList(DEVICE_ID, ImmutableSet.of(ALARM_B, ALARM_A));
verifyGettingSetsOfAlarms(manager, 2, 2);
alarmStore.deactivate();
manager.removeListener(listener);
manager.deactivate();
NetTestTools.inj... |
@Override
public ResourceReconcileResult tryReconcileClusterResources(
TaskManagerResourceInfoProvider taskManagerResourceInfoProvider) {
ResourceReconcileResult.Builder builder = ResourceReconcileResult.builder();
List<TaskManagerInfo> taskManagersIdleTimeout = new ArrayList<>();
... | @Test
void testIdlePendingTaskManagerShouldBeReleased() {
final PendingTaskManager pendingTaskManager =
new PendingTaskManager(DEFAULT_SLOT_RESOURCE, 1);
final TaskManagerResourceInfoProvider taskManagerResourceInfoProvider =
TestingTaskManagerResourceInfoProvider.new... |
static Collection<Method> getAllMethods(Class<?> owner, Predicate<? super Method> predicate) {
return getAll(owner, Class::getDeclaredMethods).filter(predicate).collect(toList());
} | @Test
public void getAllMethods() {
Collection<Method> methods = ReflectionUtils.getAllMethods(Child.class, named("overrideMe"));
assertThat(methods).containsOnly(
method(Child.class, "overrideMe"),
method(UpperMiddle.class, "overrideMe"),
method(Lowe... |
public Type type() {
return pir != null ? Type.trTCM :
ebs != null ? Type.srTCM : Type.sr2CM;
} | @Test
public void testType() {
BandwidthProfile.Builder bwProfileBuilder = BandwidthProfile.builder()
.name("profile")
.cir(Bandwidth.bps(ONE_M))
.cbs((int) ONE_K)
.greenAction(getBuilder(Action.PASS).build())
.redAction(getBuil... |
@Override
public int getPriority() {
// if server ability manager exist, you should choose the server one
return 0;
} | @Test
void testGetPriority() {
assertEquals(0, clientAbilityControlManager.getPriority());
} |
public String getString(String path) {
return ObjectConverter.convertObjectTo(get(path), String.class);
} | @Test
public void
parses_json_document_with_attribute_name_equal_to_properties() {
// Given
final String jsonWithPropertyAttribute = "[{\"properties\":\"test\"}]"; // properties is a reserved word in Groovy
// When
final String value = new JsonPath(jsonWithPropertyAttribute).get... |
public static Boolean judge(final ConditionData conditionData, final String realData) {
if (Objects.isNull(conditionData) || StringUtils.isBlank(conditionData.getOperator())) {
return false;
}
PredicateJudge predicateJudge = newInstance(conditionData.getOperator());
if (!(pre... | @Test
public void testPathPatternJudge() {
conditionData.setOperator(OperatorEnum.PATH_PATTERN.getAlias());
conditionData.setParamValue("/http/**");
assertTrue(PredicateJudgeFactory.judge(conditionData, "/http/**"));
assertTrue(PredicateJudgeFactory.judge(conditionData, "/http/test")... |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Add policies to all HTTP headers
for (String header : this.cspHeaders) {
((HttpServletResponse) response).setHeader(header, this.policies);
}
chain.doFil... | @Test
public void set_content_security_headers() throws Exception {
doInit();
HttpServletRequest request = newRequest("/");
underTest.doFilter(request, response, chain);
verify(response).setHeader("Content-Security-Policy", EXPECTED);
verify(response).setHeader("X-Content-Security-Policy", EXPECTE... |
public void getFields( RowMetaInterface row, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) {
// No values are added to the row in this type of step
// However, in case of Fixed length records,
// the field precisions and le... | @Test
public void testGetFields() throws Exception {
XMLOutputMeta xmlOutputMeta = new XMLOutputMeta();
xmlOutputMeta.setDefault();
XMLField xmlField = new XMLField();
xmlField.setFieldName( "aField" );
xmlField.setLength( 10 );
xmlField.setPrecision( 3 );
xmlOutputMeta.setOutputFields( ne... |
public static CommandExecutor newInstance(final CommandPacketType commandPacketType, final PostgreSQLCommandPacket commandPacket,
final ConnectionSession connectionSession, final PortalContext portalContext) throws SQLException {
if (commandPacket instanceof SQLRece... | @Test
void assertAggregatedPacketNotBatchedStatements() throws SQLException {
PostgreSQLComParsePacket parsePacket = mock(PostgreSQLComParsePacket.class);
when(parsePacket.getIdentifier()).thenReturn(PostgreSQLCommandPacketType.PARSE_COMMAND);
PostgreSQLComFlushPacket flushPacket = new Postg... |
public List<Node> readNodes() {
CachingCurator.Session session = db.getSession();
return session.getChildren(nodesPath).stream()
.flatMap(hostname -> readNode(session, hostname).stream())
.toList();
} | @Test
public void can_read_stored_host_information() throws Exception {
String zkline = "{\"hostname\":\"host1\",\"state\":\"ready\",\"ipAddresses\":[\"127.0.0.1\"],\"additionalIpAddresses\":[\"127.0.0.2\"],\"openStackId\":\"7951bb9d-3989-4a60-a21c-13690637c8ea\",\"flavor\":\"default\",\"created\":142105442... |
@Override
public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
final NodeId myId = clusterService.getLocalNode().id();
NodeId master = mastershipService.getMasterFor(deviceId);
// if there exist a master, forward
// if there is no master, try to become one and process
... | @Test
public final void testRemoveDevice() {
putDevice(DID1, SW1, A1);
List<PortDescription> pds = Arrays.asList(
DefaultPortDescription.builder().withPortNumber(P1).isEnabled(true).annotations(A2).build()
);
deviceStore.updatePorts(PID, DID1, pds);
pu... |
public <T extends BuildableManifestTemplate> ManifestTemplate getManifestListTemplate(
Class<T> manifestTemplateClass) throws IOException {
Preconditions.checkArgument(
manifestTemplateClass == V22ManifestTemplate.class,
"Build an OCI image index is not yet supported");
Preconditions.check... | @Test
public void testGetManifestListTemplate_emptyImagesList() throws IOException {
try {
new ManifestListGenerator(Collections.emptyList())
.getManifestListTemplate(V22ManifestTemplate.class);
Assert.fail();
} catch (IllegalStateException ex) {
Assert.assertEquals("no images give... |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullNamedOnFlatTransform() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransform(flatTransformerSupplier, (Named) null));
assertThat(exception.getM... |
@Override
public boolean test(final String resourceName) {
return resourceName.matches(blackList);
} | @Test
public void shouldIgnoreBlankLines() throws IOException {
writeBlacklist(ImmutableList.<String>builder().add("", "java.util", "").build());
final Blacklist blacklist = new Blacklist(this.blacklistFile);
assertFalse(blacklist.test("java.lang.Process"));
assertTrue(blacklist.test("java.util.List")... |
public static InternalLogger getInstance(Class<?> clazz) {
return getInstance(clazz.getName());
} | @Test
public void testTrace() {
final InternalLogger logger = InternalLoggerFactory.getInstance("mock");
logger.trace("a");
verify(mockLogger).trace("a");
} |
@Override
public void itemSet(String itemType, String itemId, JSONObject properties) {
} | @Test
public void itemSet() {
mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() {
@Override
public boolean onTrackEvent(String eventName, JSONObject eventProperties) {
Assert.fail();
return false;
}
});
m... |
public static ResourceCalculatorProcessTree getResourceCalculatorProcessTree(
String pid, Class<? extends ResourceCalculatorProcessTree> clazz, Configuration conf) {
if (clazz != null) {
try {
Constructor <? extends ResourceCalculatorProcessTree> c = clazz.getConstructor(String.class);
Res... | @Test
void testCreatedInstanceConfigured() {
ResourceCalculatorProcessTree tree;
Configuration conf = new Configuration();
tree = ResourceCalculatorProcessTree.getResourceCalculatorProcessTree("1", EmptyProcessTree.class, conf);
assertNotNull(tree);
assertThat(tree.getConf(), sameInstance(conf));
... |
public void execute() {
execute(LOG);
} | @Test
public void should_not_fail_if_default_profile_used_at_least_once() {
store.put("foo", new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
QProfileVerifier profileLogger = new QProfileVerifier(store, profiles);
profileLogger.execute();
} |
@Udf
public <T> List<T> remove(
@UdfParameter(description = "Array of values") final List<T> array,
@UdfParameter(description = "Value to remove") final T victim) {
if (array == null) {
return null;
}
return array.stream()
.filter(el -> !Objects.equals(el, victim))
.coll... | @Test
public void shouldReturnAllElementsIfNoMatches() {
final List<String> input1 = Arrays.asList("foo");
final String input2 = "bar";
final List<String> result = udf.remove(input1, input2);
assertThat(result, contains("foo"));
} |
@Override
public void createOrUpdate(final String path, final Object data) {
zkClient.createOrUpdate(path, data, CreateMode.PERSISTENT);
} | @Test
public void testOnMetaDataChangedCreate() throws UnsupportedEncodingException {
MetaData metaData = MetaData.builder().id(MOCK_ID).path(MOCK_PATH).appName(MOCK_APP_NAME).build();
String metaDataPath = DefaultPathConstants.buildMetaDataPath(URLEncoder.encode(metaData.getPath(), StandardCharsets... |
void executeMergeConfigTask(List<ConfigInfoChanged> configInfoList, int pageSize) {
for (ConfigInfoChanged configInfo : configInfoList) {
String dataId = configInfo.getDataId();
String group = configInfo.getGroup();
String tenant = configInfo.getTenant();
try {
... | @Test
void executeMergeConfigTask() {
envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("nacos.config.retention.days"))).thenReturn("10");
ConfigInfoChanged hasDatum = new ConfigInfoChanged();
hasDatum.setDataId("hasDatumdataId1");
hasDatum.setTenant("tenant1");
hasDatum.... |
@Override
public void dealSeckill(long seckillId, String userPhone, String note, String taskId) {
try {
InetAddress localHost = InetAddress.getLocalHost();
SuccessKilledDTO successKilled = new SuccessKilledDTO();
successKilled.setSeckillId(seckillId);
successK... | @Test
void dealSeckill() {
long seckillId = 1001L;
Seckill seckill = new Seckill();
seckill.setNumber(0);
when(seckillMapper.selectById(seckillId)).thenReturn(seckill);
seckillProcedureExecutor.dealSeckill(seckillId, "123", "test", "1");
Seckill updateSeckill = new Se... |
@Override
public String toString() {
return GsonUtils.getInstance().toJson(this);
} | @Test
public void testToString() {
ConfigData<Object> configData = new ConfigData<>();
configData.setLastModifyTime(LAST_MODIFY_TIME);
configData.setMd5(MD5);
configData.setData(Collections.emptyList());
assertNotNull(configData.toString());
} |
public static InetSocketAddress getLocalSocketAddress(String host, int port) {
return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);
} | @Test
void testGetLocalSocketAddress() {
InetSocketAddress address = NetUtils.getLocalSocketAddress("localhost", 12345);
assertTrue(address.getAddress().isAnyLocalAddress());
assertEquals(address.getPort(), 12345);
address = NetUtils.getLocalSocketAddress("dubbo-addr", 12345);
... |
public static String randomCreditCode() {
final StringBuilder buf = new StringBuilder(18);
//
for (int i = 0; i < 2; i++) {
int num = RandomUtil.randomInt(BASE_CODE_ARRAY.length - 1);
buf.append(Character.toUpperCase(BASE_CODE_ARRAY[num]));
}
for (int i = 2; i < 8; i++) {
int num = RandomUtil.rando... | @Test
public void randomCreditCode() {
final String s = CreditCodeUtil.randomCreditCode();
assertTrue(CreditCodeUtil.isCreditCode(s));
} |
@Override
public String normalise(String text) {
if (Objects.isNull(text) || text.isEmpty()) {
throw new IllegalArgumentException("Text cannot be null or empty");
}
return text.trim()
.toLowerCase()
.replaceAll("\\p{Punct}", "")
.replaceAll("\\s+", " ");
} | @Description("Normalise, when text has multiple spaces between words, then return lowercased text with spaces minimised to one")
@Test
void normalise_WhenTextHasMultipleSpacesBetweenWords_ThenReturnLowercasedTextWithOneSpace() {
// When
var result = textNormaliser.normalise("Hello World");
// Then
... |
@Override
public ResourceId resolve(String other, ResolveOptions resolveOptions) {
checkState(isDirectory(), "Expected this resource to be a directory, but was [%s]", toString());
if (resolveOptions == ResolveOptions.StandardResolveOptions.RESOLVE_DIRECTORY) {
if ("..".equals(other)) {
if ("/".... | @Test
public void testResolve() {
for (TestCase testCase : PATH_TEST_CASES) {
ResourceId resourceId = S3ResourceId.fromUri(testCase.baseUri);
ResourceId resolved = resourceId.resolve(testCase.relativePath, testCase.resolveOptions);
assertEquals(testCase.expectedResult, resolved.toString());
... |
public static <K, V> Reshuffle<K, V> of() {
return new Reshuffle<>();
} | @Test
@Category(ValidatesRunner.class)
public void testReshuffleAfterFixedWindowsAndGroupByKey() {
PCollection<KV<String, Iterable<Integer>>> input =
pipeline
.apply(
Create.of(GBK_TESTABLE_KVS)
.withCoder(KvCoder.of(StringUtf8Coder.of(), VarIntCoder.of()... |
public EmptyRow() {
// No-op.
} | @Test
public void testEmptyRow() {
EmptyRow row = EmptyRow.INSTANCE;
assertEquals(0, row.getColumnCount());
} |
public CheckpointProperties(
boolean forced,
SnapshotType checkpointType,
boolean discardSubsumed,
boolean discardFinished,
boolean discardCancelled,
boolean discardFailed,
boolean discardSuspended,
boolean unclaimed) {
... | @Test
void testCheckpointProperties() {
CheckpointProperties props =
CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_FAILURE);
assertThat(props.forceCheckpoint()).isFalse();
assertThat(props.discardOnSubsumed()).isTrue();
assertThat(props.disca... |
@Override
public ClientRequest transformRequest(ClientRequest request, ServiceInstance instance) {
if (instance != null) {
MetadataContextHolder.get().setLoadbalancer(LOAD_BALANCER_SERVICE_INSTANCE, instance);
}
return request;
} | @Test
public void test() throws Throwable {
transformer.transformRequest(clientRequest, serviceInstance);
assertThat(MetadataContextHolder.get().getLoadbalancerMetadata().get(LOAD_BALANCER_SERVICE_INSTANCE)).isEqualTo(serviceInstance);
} |
static <T> CheckedSupplier<T> decorateCheckedSupplier(Observation observation,
CheckedSupplier<T> supplier) {
return () -> observation.observeChecked(supplier::get);
} | @Test
public void shouldDecorateCheckedSupplier() throws Throwable {
given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world");
CheckedSupplier<String> timedSupplier = Observations
.decorateCheckedSupplier(observation, helloWorldService::returnHelloWorldWithExcep... |
public static SerializableFunction<Row, Mutation> beamRowToMutationFn(
Mutation.Op operation, String table) {
return (row -> {
switch (operation) {
case INSERT:
return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row);
case DELETE:
return... | @Test
public void testCreateInsertOrUpdateMutationFromRowWithNulls() {
Mutation expectedMutation = createMutationNulls(Mutation.Op.INSERT_OR_UPDATE);
Mutation mutation =
beamRowToMutationFn(Mutation.Op.INSERT_OR_UPDATE, TABLE).apply(WRITE_ROW_NULLS);
assertEquals(expectedMutation, mutation);
} |
public ProjectList searchProjects(String gitlabUrl, String personalAccessToken, @Nullable String projectName,
@Nullable Integer pageNumber, @Nullable Integer pageSize) {
String url = format("%s/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=%s%s%s",
gitlabUrl,
proj... | @Test
public void search_projects_dont_fail_if_no_x_total() throws InterruptedException {
MockResponse projects = new MockResponse()
.setResponseCode(200)
.setBody("[\n"
+ " {\n"
+ " \"id\": 1,\n"
+ " \"name\": \"SonarQube example 1\",\n"
+ " \"name_with_names... |
@Override
public String getUnderFSType() {
return "obs";
} | @Test
public void getUnderFSType() {
Assert.assertEquals("obs", mOBSUnderFileSystem.getUnderFSType());
} |
public void addValueProviders(final String segmentName,
final RocksDB db,
final Cache cache,
final Statistics statistics) {
if (storeToValueProviders.isEmpty()) {
logger.debug("Adding metrics record... | @Test
public void shouldSetStatsLevelToExceptDetailedTimersWhenValueProvidersWithStatisticsAreAdded() {
recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1);
verify(statisticsToAdd1).setStatsLevel(StatsLevel.EXCEPT_DETAILED_TIMERS);
} |
@VisibleForTesting
static String generateMigrationFile(QualifiedVersion version, String template, List<ChangelogEntry> entries) throws IOException {
final Map<Boolean, Map<String, List<ChangelogEntry.Deprecation>>> deprecationsByNotabilityByArea = entries.stream()
.map(ChangelogEntry::getDepreca... | @Test
public void generateIndexFile_rendersCorrectMarkup() throws Exception {
// given:
final String template = getResource("/templates/breaking-changes.asciidoc");
final String expectedOutput = getResource(
"/org/elasticsearch/gradle/internal/release/BreakingChangesGeneratorTest... |
@Override
public List<AdminUserDO> getUserListByNickname(String nickname) {
return userMapper.selectListByNickname(nickname);
} | @Test
public void testGetUserListByNickname() {
// mock 数据
AdminUserDO user = randomAdminUserDO(o -> o.setNickname("芋头"));
userMapper.insert(user);
// 测试 nickname 不匹配
userMapper.insert(randomAdminUserDO(o -> o.setNickname("源码")));
// 准备参数
String nickname = "芋"... |
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext ctx) {
log.fine(() -> String.format("retryRequest(exception='%s', executionCount='%d', ctx='%s'",
exception.getClass().getName(), executionCount, ctx));
HttpClientContext... | @SuppressWarnings("unchecked")
@Test
void retry_consumers_are_invoked() {
RetryConsumer<IOException> retryConsumer = (RetryConsumer<IOException>) mock(RetryConsumer.class);
RetryFailedConsumer<IOException> retryFailedConsumer = (RetryFailedConsumer<IOException>) mock(RetryFailedConsumer.class);
... |
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (!requestContext.getUriInfo().getPath().endsWith(targetPath)) {
return;
}
final List<MediaType> acceptedFormats = requestContext.getAcceptableMediaTypes();
final Map<MediaType, E... | @Test
void doesNothingIfRequestPathDoesNotMatch() throws Exception {
final ContainerRequestFilter filter = new MessageExportFormatFilter(Collections.emptySet());
final ContainerRequestContext requestContext = mockRequestContextForNonMatchingPath();
filter.filter(requestContext);
ve... |
public void clearForTask() {
MDC.remove(MDC_CE_TASK_UUID);
} | @Test
public void clearForTask_removes_task_uuid_from_MDC() {
MDC.put(MDC_CE_TASK_UUID, "some_value");
underTest.clearForTask();
assertThat(MDC.get(MDC_CE_TASK_UUID)).isNull();
} |
protected static void checkNormalWithComma(String configKey, String configValue) throws SofaRpcRuntimeException {
checkPattern(configKey, configValue, NORMAL_COMMA, "only allow a-zA-Z0-9 '-' '_' '.' ','");
} | @Test
public void checkNormalWithComma() {
ConfigValueHelper.checkNormalWithComma("aaa", "123abc-_.,");
try {
ConfigValueHelper.checkNormalWithComma("aaa", "123abc-_.,!");
Assert.fail();
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("aa... |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldGetCorrectSchemaForSearchedCaseWhenStruct() {
// Given:
final Expression expression = new SearchedCaseExpression(
ImmutableList.of(
new WhenClause(
new ComparisonExpression(Type.EQUAL, TestExpressions.COL0, new IntegerLiteral(10)),
AD... |
static MinMax findMinMax(MinMax minMax, List<Statement> statements, EncodedValueLookup lookup) {
List<List<Statement>> groups = CustomModelParser.splitIntoGroup(statements);
for (List<Statement> group : groups) findMinMaxForGroup(minMax, group, lookup);
return minMax;
} | @Test
public void testFindMax() {
List<Statement> statements = new ArrayList<>();
statements.add(If("true", LIMIT, "100"));
assertEquals(100, findMinMax(new MinMax(0, 120), statements, lookup).max);
statements.add(Else(LIMIT, "20"));
assertEquals(100, findMinMax(new MinMax(0... |
@Override
public void writeMetrics(MetricQueryResults metricQueryResults) throws Exception {
final long metricTimestamp = System.currentTimeMillis() / 1000L;
Socket socket = new Socket(InetAddress.getByName(address), port);
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(socket.g... | @Test
public void testWriteMetricsWithCommittedSupported() throws Exception {
MetricQueryResults metricQueryResults = new CustomMetricQueryResults(true);
MetricsOptions pipelineOptions = PipelineOptionsFactory.create().as(MetricsOptions.class);
pipelineOptions.setMetricsGraphitePort(port);
pipelineOpt... |
public static AuditManagerS3A createAndStartAuditManager(
Configuration conf,
IOStatisticsStore iostatistics) {
AuditManagerS3A auditManager;
if (conf.getBoolean(AUDIT_ENABLED, AUDIT_ENABLED_DEFAULT)) {
auditManager = new ActiveAuditManagerS3A(
requireNonNull(iostatistics));
} el... | @Test
public void testLoggingAuditorBinding() throws Throwable {
AuditManagerS3A manager = AuditIntegration.createAndStartAuditManager(
AuditTestSupport.loggingAuditConfig(),
ioStatistics);
OperationAuditor auditor = manager.getAuditor();
assertServiceStateStarted(auditor);
manager.clo... |
@Override
public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication,
long blockSize, Progressable progress) throws IOException {
String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK);
Mode mode =... | @Test
public void concurrentInitialize() throws Exception {
List<Thread> threads = new ArrayList<>();
final org.apache.hadoop.conf.Configuration conf = getConf();
for (int i = 0; i < 100; i++) {
Thread t = new Thread(() -> {
URI uri = URI.create(Constants.HEADER + "randomhost:410/");
... |
Optional<ImageMetadataTemplate> retrieveMetadata(ImageReference imageReference)
throws IOException, CacheCorruptedException {
Path imageDirectory = cacheStorageFiles.getImageDirectory(imageReference);
Path metadataPath = imageDirectory.resolve("manifests_configs.json");
if (!Files.exists(metadataPath)... | @Test
public void testRetrieveMetadata_ociSingleManifest()
throws IOException, URISyntaxException, CacheCorruptedException {
setupCachedMetadataOci(cacheDirectory);
ImageMetadataTemplate metadata =
cacheStorageReader.retrieveMetadata(ImageReference.of("test", "image", "tag")).get();
Assert.... |
public static List<String> splitToWhiteSpaceSeparatedTokens(String input) {
if (input == null) {
return new ArrayList<>();
}
StringTokenizer tokenizer = new StringTokenizer(input.trim(), QUOTE_CHAR + WHITESPACE, true);
List<String> tokens = new ArrayList<>();
StringB... | @Test
public void testTwoDoubleQuotes() {
List<String> args = splitToWhiteSpaceSeparatedTokens("\"\"arg0\"\" \"\"arg1\"\"");
assertEquals("\"arg0\"", args.get(0));
assertEquals("\"arg1\"", args.get(1));
} |
@Override
public Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor(
List<ExecutionAttemptID> executionAttemptIds) {
final Map<ExecutionVertexID, ExecutionAttemptID> vertexIdToExecutionId = new HashMap<>();
executionAttemptIds.forEach(
executionId ->
... | @Test
void testSlotRequestProfileFromExecutionSlotSharingGroup() {
final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10);
final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20);
final AllocationContext context =
AllocationContext... |
public static String getHostAddress()
throws SocketException, UnknownHostException {
boolean isIPv6Preferred = Boolean.parseBoolean(System.getProperty("java.net.preferIPv6Addresses"));
DatagramSocket ds = new DatagramSocket();
try {
ds.connect(isIPv6Preferred ? Inet6Address.getByName(DUMMY_OUT_I... | @Test(description = "Test getHostAddress with preferIPv6Addresses=true in IPv6 only environment")
public void testGetHostAddressIPv6EnvIPv6Preferred() {
System.setProperty("java.net.preferIPv6Addresses", "true");
InetAddress mockInetAddress = mock(InetAddress.class);
when(mockInetAddress.isAnyLocalAddres... |
public static String identifyDriver(String nameContainsProductInfo) {
return identifyDriver(nameContainsProductInfo, null);
} | @Test
public void identifyDriverTest(){
Map<String,String> map = new HashMap<>(25);
map.put("mysql",DRIVER_MYSQL_V6);
map.put("cobar",DRIVER_MYSQL_V6);
map.put("oracle",DRIVER_ORACLE);
map.put("postgresql",DRIVER_POSTGRESQL);
map.put("sqlite",DRIVER_SQLLITE3);
map.put("sqlserver",DRIVER_SQLSERVER);
ma... |
@Override
public void store(Measure newMeasure) {
saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure);
} | @Test
public void shouldIgnoreMeasuresOnFolders() {
underTest.store(new DefaultMeasure()
.on(new DefaultInputDir("foo", "bar"))
.forMetric(CoreMetrics.LINES)
.withValue(10));
verifyNoMoreInteractions(reportPublisher);
} |
@GetMapping("/login")
public ShenyuAdminResult loginDashboardUser(final String userName, final String password, @RequestParam(required = false) final String clientId) {
LoginDashboardUserVO loginVO = dashboardUserService.login(userName, password, clientId);
return Optional.ofNullable(loginVO)
... | @Test
public void testLoginDashboardUser() throws Exception {
final String loginUri = "/platform/login?userName=admin&password=123456";
LoginDashboardUserVO loginDashboardUserVO = LoginDashboardUserVO.buildLoginDashboardUserVO(dashboardUserVO);
given(this.dashboardUserService.login(eq("admi... |
public boolean isSymmetric() {
if (!isSquare()) {
return false;
} else {
for (int i = 0; i < dim1; i++) {
for (int j = i + 1; j < dim1; j++) {
if (Double.compare(get(i,j),get(j,i)) != 0) {
return false;
... | @Test
public void symmetricTest() {
assertFalse(generateA().isSymmetric());
assertFalse(generateB().isSymmetric());
assertTrue(generateSymmetric().isSymmetric());
} |
protected boolean isNodeEmpty(JsonNode json) {
if (json.isArray()) {
return isListEmpty((ArrayNode) json);
} else if (json.isObject()) {
return isObjectEmpty((ObjectNode) json);
} else {
return isEmptyText(json);
}
} | @Test
public void isNodeEmpty_textNode() {
assertThat(expressionEvaluator.isNodeEmpty(new TextNode(""))).isTrue();
assertThat(expressionEvaluator.isNodeEmpty(new TextNode(null))).isTrue();
assertThat(expressionEvaluator.isNodeEmpty(new TextNode(VALUE))).isFalse();
} |
@Override
public void registerRemote(final RemoteInstance remoteInstance) throws ServiceRegisterException {
try {
this.port = remoteInstance.getAddress().getPort();
healthChecker.health();
} catch (Throwable e) {
healthChecker.unHealth(e);
throw new Se... | @Test
public void registerRemote() throws Exception {
RemoteInstance instance = new RemoteInstance(addressA);
withEnvironmentVariable(SELF_UID, SELF_UID).execute(() -> {
providerA = createProvider(SELF_UID);
coordinatorA = getClusterCoordinator(providerA);
coordin... |
@Override
public PostgreSQLTypeUnspecifiedSQLParameter parse(final String value) {
return new PostgreSQLTypeUnspecifiedSQLParameter(value);
} | @Test
void assertParse() {
assertThat(new PostgreSQLUnspecifiedValueParser().parse("1").toString(), is("1"));
} |
@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 testUpdate() throws IOException {
DataflowPipelineOptions options = buildPipelineOptions();
options.setUpdate(true);
options.setJobName("oldJobName");
Pipeline p = buildDataflowPipeline(options);
DataflowPipelineJob job = (DataflowPipelineJob) p.run();
assertEquals("newid", j... |
public static String from(Query query) {
AbstractProducedQuery abstractProducedQuery = query.unwrap(AbstractProducedQuery.class);
String[] sqls = abstractProducedQuery
.getProducer()
.getFactory()
.getQueryPlanCache()
.getHQLQueryPlan(abstractProducedQuery... | @Test
public void testCriteriaAPI() {
doInJPA(entityManager -> {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class);
Root<PostComment> postComment = criteria.from(PostComment.class);... |
public Span nextSpan(TraceContextOrSamplingFlags extracted) {
if (extracted == null) throw new NullPointerException("extracted == null");
TraceContext context = extracted.context();
if (context != null) return newChild(context);
TraceIdContext traceIdContext = extracted.traceIdContext();
if (traceI... | @Test void nextSpan_extractedTraceContext_extra() {
TraceContextOrSamplingFlags extracted = TraceContextOrSamplingFlags.newBuilder(context)
.addExtra(1L).build();
assertThat(tracer.nextSpan(extracted).context().extra())
.contains(1L);
} |
@Override
public void onKey(
int primaryCode, Keyboard.Key key, int multiTapIndex, int[] nearByKeyCodes, boolean fromUI) {
mParentListener.listener().onKey(primaryCode, key, multiTapIndex, nearByKeyCodes, fromUI);
if ((mInOneShot && primaryCode != KeyCodes.DELETE) || primaryCode == KeyCodes.ENTER) {
... | @Test
public void testOnKey() {
final AnyKeyboard.AnyKey key = Mockito.mock(AnyKeyboard.AnyKey.class);
final int[] nearByKeyCodes = {3};
mUnderTest.onKey(1, key, 2, nearByKeyCodes, true);
final InOrder inOrder = Mockito.inOrder(mMockParentListener, mMockKeyboardDismissAction);
inOrder
.ver... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.