focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public void replay(
long offset,
long producerId,
short producerEpoch,
CoordinatorRecord record
) throws RuntimeException {
ApiMessageAndVersion key = record.key();
ApiMessageAndVersion value = record.value();
switch (key.version()) {
... | @Test
public void testReplayShareGroupMetadataWithNullValue() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class... |
@Override
public Set<EntityExcerpt> listEntityExcerpts() {
return grokPatternService.loadAll().stream()
.map(this::createExcerpt)
.collect(Collectors.toSet());
} | @Test
public void listEntityExcerpts() throws ValidationException {
grokPatternService.save(GrokPattern.create("Test1", "[a-z]+"));
grokPatternService.save(GrokPattern.create("Test2", "[a-z]+"));
final EntityExcerpt expectedEntityExcerpt1 = EntityExcerpt.builder()
.id(ModelI... |
@Override
public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) {
return getDescriptionInHtml(rule)
.map(this::generateSections)
.orElse(emptySet());
} | @Test
public void parse_md_rule_description() {
String ruleDescription = "This is the custom rule description";
String exceptionsContent = "This the exceptions section content";
String askContent = "This is the ask section content";
String recommendedContent = "This is the recommended section content"... |
@Override
public int read() throws IOException
{
checkClosed();
if (pointer >= this.size)
{
return -1;
}
if (currentBufferPointer >= chunkSize)
{
if (bufferListIndex >= bufferListMaxIndex)
{
return -1;
... | @Test
void testPDFBOX5764() throws IOException
{
int bufferSize = 4096;
int limit = 2048;
ByteBuffer buffer = ByteBuffer.wrap(new byte[bufferSize]);
buffer.limit(limit);
try (RandomAccessRead rar = new RandomAccessReadBuffer(buffer))
{
byte[] buf = new... |
public boolean eval(ContentFile<?> file) {
// TODO: detect the case where a column is missing from the file using file's max field id.
return new MetricsEvalVisitor().eval(file);
} | @Test
public void testIntegerNotEqRewritten() {
boolean shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, not(equal("id", INT_MIN_VALUE - 25))).eval(FILE);
assertThat(shouldRead).as("Should read: id below lower bound").isTrue();
shouldRead =
new InclusiveMetricsEvaluator(SCHEMA, not(equa... |
@Override
public boolean isWarProject() {
String packaging = project.getPackaging();
return "war".equals(packaging) || "gwt-app".equals(packaging);
} | @Test
public void testIsWarProject_jarPackagingIsNotWar() {
when(mockMavenProject.getPackaging()).thenReturn("jar");
assertThat(mavenProjectProperties.isWarProject()).isFalse();
} |
@Override
public CompletableFuture<Acknowledge> notifyNewBlockedNodes(Collection<BlockedNode> newNodes) {
blocklistHandler.addNewBlockedNodes(newNodes);
return CompletableFuture.completedFuture(Acknowledge.get());
} | @Test
void testUnblockResourcesWillTriggerResourceRequirementsCheck() throws Exception {
final CompletableFuture<Void> triggerRequirementsCheckFuture = new CompletableFuture<>();
final SlotManager slotManager =
new TestingSlotManagerBuilder()
.setTriggerRequ... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, String.valueOf(Path.DELIMITER));
} | @Test
public void testListPlaceholderTilde() throws Exception {
final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
final S3AccessControlListFeature acl = new S3AccessControlListFeature(session);
final Path placeholderTildeEnd = ... |
@PUT
@Path("{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateNetwork(@PathParam("id") String id, InputStream input) throws IOException {
log.trace(String.format(MESSAGE, "UPDATE " + id));
String inputStr = IOUtils.toString(input, R... | @Test
public void testUpdateNetworkWithUpdatingOperation() {
mockOpenstackNetworkAdminService.updateNetwork(anyObject());
replay(mockOpenstackNetworkAdminService);
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
final Web... |
public Properties getProperties() {
return properties;
} | @Test
public void testHibernateTypesOverrideProperties() {
assertEquals("ghi", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.def"));
} |
public static void rethrowIOException(Throwable cause)
throws IOException {
if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
... | @Test
public void testRethrowErrorAsIOException() throws IOException {
Error error = new Error("test");
try {
rethrowIOException(error);
fail("Should rethrow Error");
} catch (Error e) {
assertSame(error, e);
}
} |
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
} | @Test
void tesToObjForTypeWithException() {
assertThrows(NacosDeserializationException.class, () -> {
JacksonUtils.toObj("aaa", TypeUtils.parameterize(JsonNode.class));
});
} |
@Override
public WhitelistedSite update(WhitelistedSite oldWhitelistedSite, WhitelistedSite whitelistedSite) {
if (oldWhitelistedSite == null || whitelistedSite == null) {
throw new IllegalArgumentException("Neither the old or new sites may be null");
}
return repository.update(oldWhitelistedSite, whitelisted... | @Test
public void update_success() {
WhitelistedSite oldSite = Mockito.mock(WhitelistedSite.class);
WhitelistedSite newSite = Mockito.mock(WhitelistedSite.class);
service.update(oldSite, newSite);
Mockito.verify(repository).update(oldSite, newSite);
} |
public boolean writable(final SelectableChannel channel)
{
return writable((Object) channel);
} | @Test(timeout = 5000)
public void testWritable()
{
ZContext ctx = new ZContext();
ZPoller poller = new ZPoller(ctx);
try {
Socket socket = ctx.createSocket(SocketType.XPUB);
poller.register(socket, ZPoller.OUT);
boolean rc = poller.writable(socket);
... |
public void updateSchema( PartitionSchema schema ) {
if ( schema != null && schema.getName() != null ) {
stepMeta.getStepPartitioningMeta().setPartitionSchema( schema );
}
} | @Test
public void metaIsNotUpdatedWithNameless() {
PartitionSchema schema = new PartitionSchema( null, Collections.<String>emptyList() );
StepPartitioningMeta meta = mock( StepPartitioningMeta.class );
when( stepMeta.getStepPartitioningMeta() ).thenReturn( meta );
settings.updateSchema( null );
... |
@Override
void toPdf() throws DocumentException {
final List<CounterError> errors = counter.getErrors();
if (errors.isEmpty()) {
addToDocument(new Phrase(getString("Aucune_erreur"), normalFont));
} else {
writeErrors(errors);
}
} | @Test
public void testCounterError() throws IOException {
final Counter errorCounter = new Counter(Counter.ERROR_COUNTER_NAME, null);
final Collector collector = new Collector("test", Collections.singletonList(errorCounter));
final JavaInformations javaInformations = new JavaInformations(null, true);
final Byt... |
public static String lastElement(List<String> strings) {
checkArgument(!strings.isEmpty(), "empty list");
return strings.get(strings.size() - 1);
} | @Test
public void testLastElementSingle() {
assertEquals("first", lastElement(l("first")));
} |
@Override
public void updateIndices(SegmentDirectory.Writer segmentWriter)
throws Exception {
Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter);
if (columnOperationsMap.isEmpty()) {
return;
}
for (Map.Entry<String, List<Operation>> entry : columnOperation... | @Test
public void testDisableDictionaryForMultipleColumns()
throws Exception {
IndexLoadingConfig indexLoadingConfig = new IndexLoadingConfig(null, _tableConfig);
SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segmentDirectory);
SegmentDirectory segmentLocalFSDirectory =
... |
@Override
public <R> R eval(Mode mode, String luaScript, ReturnType returnType) {
return eval(mode, luaScript, returnType, Collections.emptyList());
} | @Test
public void testEval() {
RScript script = redisson.getScript(StringCodec.INSTANCE);
List<Object> res = script.eval(RScript.Mode.READ_ONLY, "return {'1','2','3.3333','foo',nil,'bar'}", RScript.ReturnType.MULTI, Collections.emptyList());
assertThat(res).containsExactly("1", "2", "3.3333"... |
@Override
public DescriptiveUrlBag toUrl(final Path file) {
final DescriptiveUrlBag list = new DescriptiveUrlBag();
if(new HostPreferences(session.getHost()).getBoolean("s3.bucket.virtualhost.disable")) {
list.addAll(new DefaultUrlProvider(session.getHost()).toUrl(file));
}
... | @Test
public void testToSignedUrlThirdparty() throws Exception {
final S3Session session = new S3Session(new Host(new S3Protocol(), "s.greenqloud.com",
new Credentials("k", "s"))) {
@Override
public RequestEntityRestStorageService getClient() {
try {
... |
@Override
public Object merge(T mergingValue, T existingValue) {
if (existingValue == null) {
return null;
}
return existingValue.getRawValue();
} | @Test
@SuppressWarnings("ConstantConditions")
public void merge_mergingNull() {
MapMergeTypes existing = mergingValueWithGivenValue(EXISTING);
MapMergeTypes merging = null;
assertEquals(EXISTING, mergePolicy.merge(merging, existing));
} |
public static void validateSourceConfig(SourceConfig sourceConfig, ValidatableFunctionPackage sourceFunction) {
try {
ConnectorDefinition defn = sourceFunction.getFunctionMetaData(ConnectorDefinition.class);
if (defn != null && defn.getSourceConfigClass() != null) {
Class... | @Test
public void testValidateConfig() {
SourceConfig sourceConfig = createSourceConfig();
// Good config
sourceConfig.getConfigs().put("configParameter", "Test");
SourceConfigUtils.validateSourceConfig(sourceConfig, SourceConfigUtilsTest.TestSourceConfig.class);
// Bad con... |
public static Stream<Vertex> depthFirst(Graph g) {
return depthFirst(g.getRoots());
} | @Test
public void testDFSVertex() {
DepthFirst.depthFirst(g.getRoots()).forEach(v -> visitCount.incrementAndGet());
assertEquals("It should visit each node once", visitCount.get(), 3);
} |
static void handleUpgrade(Namespace namespace, Admin adminClient) throws TerseException {
handleUpgradeOrDowngrade("upgrade", namespace, adminClient, FeatureUpdate.UpgradeType.UPGRADE);
} | @Test
public void testHandleUpgrade() {
Map<String, Object> namespace = new HashMap<>();
namespace.put("metadata", "3.3-IV1");
namespace.put("feature", Collections.singletonList("foo.bar=6"));
namespace.put("dry_run", false);
String upgradeOutput = ToolsTestUtils.captureStand... |
protected void initializePipeline(DeviceId deviceId) {
// for inbound table transition
connectTables(deviceId, Constants.STAT_INBOUND_TABLE, Constants.VTAP_INBOUND_TABLE);
connectTables(deviceId, Constants.VTAP_INBOUND_TABLE, Constants.DHCP_TABLE);
// for DHCP and vTag table transition
... | @Test
public void testInitializePipeline() {
fros = Sets.newConcurrentHashSet();
target.initializePipeline(DEVICE_ID);
assertEquals("Flow Rule size was not match", 12, fros.size());
Map<Integer, Integer> fromToTableMap = Maps.newConcurrentMap();
fromToTableMap.put(STAT_INB... |
@Override
protected void runTask() {
LOGGER.debug("Updating currently processed jobs... ");
convertAndProcessJobs(new ArrayList<>(backgroundJobServer.getJobSteward().getJobsInProgress()), this::updateCurrentlyProcessingJob);
} | @Test
void noExceptionIsThrownIfAJobHasSucceededWhileUpdateProcessingIsCalled() {
// GIVEN
final Job job = anEnqueuedJob().withId().build();
startProcessingJob(job);
// WHEN
job.succeeded();
runTask(task);
// THEN
assertThat(logger).hasNoWarnLogMessa... |
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getData();
switch (metric.getType().getValueType()) {
case ... | @Test
public void toMeasure_returns_no_value_if_dto_has_no_data_for_Level_Metric() {
Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LEVEL_METRIC);
assertThat(measure).isPresent();
assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE);
} |
public static Socket acceptWithoutTimeout(ServerSocket serverSocket) throws IOException {
Preconditions.checkArgument(
serverSocket.getSoTimeout() == 0, "serverSocket SO_TIMEOUT option must be 0");
while (true) {
try {
return serverSocket.accept();
... | @Test
void testAcceptWithoutTimeoutDefaultTimeout() throws IOException {
// Default timeout (should be zero)
final Socket expected = new Socket();
try (final ServerSocket serverSocket =
new ServerSocket(0) {
@Override
public Socket acce... |
@Override
public Optional<GaugeMetricFamilyMetricsCollector> export(final String pluginType) {
if (null == ProxyContext.getInstance().getContextManager()) {
return Optional.empty();
}
GaugeMetricFamilyMetricsCollector result = MetricsCollectorRegistry.get(config, pluginType);
... | @Test
void assertExportWithoutContextManager() {
when(ProxyContext.getInstance().getContextManager()).thenReturn(null);
assertFalse(new ProxyMetaDataInfoExporter().export("FIXTURE").isPresent());
} |
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
long datetime = readDatetimeV2FromPayload(payload);
return 0L == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDatetime(columnDef, datetime, payload);
} | @Test
void assertReadWithoutFraction1() {
columnDef.setColumnMeta(1);
when(payload.readInt1()).thenReturn(0xfe, 0xf3, 0xff, 0x7e, 0xfb, 0x00);
LocalDateTime expected = LocalDateTime.of(9999, 12, 31, 23, 59, 59, 0);
assertThat(new MySQLDatetime2BinlogProtocolValue().read(columnDef, pa... |
@Override
public KeyValueIterator<Windowed<K>, V> backwardFindSessions(final K key,
final long earliestSessionEndTime,
final long latestSessionStartTime) {
Objects.requireNonNull... | @Test
public void shouldThrowNullPointerOnBackwardFindSessionsRangeIfToIsNull() {
setUpWithoutContext();
assertThrows(NullPointerException.class, () -> store.backwardFindSessions("a", null, 0, 0));
} |
static String encodeBytes(BytesType bytesType) {
byte[] value = bytesType.getValue();
int length = value.length;
int mod = length % MAX_BYTE_LENGTH;
byte[] dest;
if (mod != 0) {
int padding = MAX_BYTE_LENGTH - mod;
dest = new byte[length + padding];
... | @Test
public void testStaticBytes() {
Bytes staticBytes = new Bytes6(new byte[] {0, 1, 2, 3, 4, 5});
assertEquals(
TypeEncoder.encodeBytes(staticBytes),
("0001020304050000000000000000000000000000000000000000000000000000"));
Bytes empty = new Bytes1(new byte[]... |
protected boolean databaseForBothDbInterfacesIsTheSame( DatabaseInterface primary, DatabaseInterface secondary ) {
if ( primary == null || secondary == null ) {
throw new IllegalArgumentException( "DatabaseInterface shouldn't be null!" );
}
if ( primary.getPluginId() == null || secondary.getPluginId(... | @Test
public void databases_WithDifferentDbConnTypes_AreTheSame_IfOneConnTypeIsSubsetOfAnother_2LevelHierarchy() {
DatabaseInterface mssqlServerDatabaseMeta = new MSSQLServerDatabaseMeta();
mssqlServerDatabaseMeta.setPluginId( "MSSQL" );
DatabaseInterface mssqlServerNativeDatabaseMeta = new MSSQLServerNat... |
@Override
public PMML_MODEL getPMMLModelType() {
return PMML_MODEL.SCORECARD_MODEL;
} | @Test
void getPMMLModelType() {
assertThat(evaluator.getPMMLModelType()).isEqualTo(PMML_MODEL.SCORECARD_MODEL);
} |
@GetMapping("/name/{name}")
public ShenyuAdminResult queryByName(@PathVariable("name") @Valid final String name) {
List<TagVO> tagVO = tagService.findByQuery(name);
return ShenyuAdminResult.success(ShenyuResultMessage.DETAIL_SUCCESS, tagVO);
} | @Test
public void testQueryByName() throws Exception {
List<TagVO> list = new ArrayList<>();
list.add(buildTagVO());
given(tagService.findByQuery(anyString())).willReturn(list);
this.mockMvc.perform(MockMvcRequestBuilders.get("/tag/name/{name}", "123"))
.andExpect(sta... |
@Override
public void accept(final MeterEntity entity, final DataTable value) {
setEntityId(entity.id());
setServiceId(entity.serviceId());
this.value.setMinValue(value);
} | @Test
public void testAccept() {
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_1);
assertThat(function.getValue()).isEqualTo(HTTP_CODE_COUNT_1);
function.accept(MeterEntity.newService("service-test", Layer.GENERAL), HTTP_CODE_COUNT_2);
assert... |
@Audit
@Operation(summary = "command", description = "Command for component by [host,component,service,cluster]")
@PostMapping
public ResponseEntity<CommandVO> command(@RequestBody @Validated CommandReq commandReq) {
CommandDTO commandDTO = CommandConverter.INSTANCE.fromReq2DTO(commandReq);
... | @Test
void commandExecutesSuccessfully() {
CommandReq commandReq = new CommandReq();
CommandVO commandVO = new CommandVO();
when(commandService.command(any(CommandDTO.class))).thenReturn(commandVO);
ResponseEntity<CommandVO> response = commandController.command(commandReq);
... |
public static List<ProcessId> getEnabledProcesses(AppSettings settings) {
if (!isClusterEnabled(settings)) {
return asList(ProcessId.ELASTICSEARCH, ProcessId.WEB_SERVER, ProcessId.COMPUTE_ENGINE);
}
NodeType nodeType = NodeType.parse(settings.getValue(CLUSTER_NODE_TYPE.getKey()).orElse(""));
switc... | @Test
public void getEnabledProcesses_returns_all_processes_in_standalone_mode() {
TestAppSettings settings = new TestAppSettings(of(CLUSTER_ENABLED.getKey(), "false"));
assertThat(ClusterSettings.getEnabledProcesses(settings)).containsOnly(COMPUTE_ENGINE, ELASTICSEARCH, WEB_SERVER);
} |
@Override
public void start() {
} | @Test
public void start() {
provider.start();
} |
public static <T> T createInstance(String userClassName,
Class<T> xface,
ClassLoader classLoader) {
Class<?> theCls;
try {
theCls = Class.forName(userClassName, true, classLoader);
} catch (ClassNotFoundExc... | @Test
public void testCreateTypedInstanceConstructorThrowsException() {
try {
createInstance(ThrowExceptionClass.class.getName(), aInterface.class, classLoader);
fail("Should fail to load class whose constructor throws exceptions");
} catch (RuntimeException re) {
... |
@Udf
public Map<String, String> records(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final Map<String, String> ret = new HashMap<>... | @Test
public void shouldReturnNullForJsonNull() {
assertNull(udf.records("null"));
} |
@VisibleForTesting
void validateDeptNameUnique(Long id, Long parentId, String name) {
DeptDO dept = deptMapper.selectByParentIdAndName(parentId, name);
if (dept == null) {
return;
}
// 如果 id 为空,说明不用比较是否为相同 id 的部门
if (id == null) {
throw exception(DEPT_... | @Test
public void testValidateNameUnique_duplicate() {
// mock 数据
DeptDO deptDO = randomPojo(DeptDO.class);
deptMapper.insert(deptDO);
// 准备参数
Long id = randomLongId();
Long parentId = deptDO.getParentId();
String name = deptDO.getName();
// 调用, 并断言异... |
public void fillMaxSpeed(Graph graph, EncodingManager em) {
// In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info,
// but now we have and can fill the country-dependent max_speed value where missing.
EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(... | @Test
public void testUnsupportedCountry() {
ReaderWay way = new ReaderWay(0L);
way.setTag("country", Country.AIA);
way.setTag("highway", "primary");
EdgeIteratorState edge = createEdge(way).set(urbanDensity, CITY);
calc.fillMaxSpeed(graph, em);
assertEquals(UNSET_SPE... |
@Override
public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) {
long used = MemoryUtil.heapMemoryUsed();
long max = MemoryUtil.heapMemoryMax();
String memoryProportion = StringUtil.newBuilder(
"Allocation: ",
ByteConvertUtil.getPr... | @Test
void testSupplement() {
long used = MemoryUtil.heapMemoryUsed();
long max = MemoryUtil.heapMemoryMax();
String memoryProportion = StringUtil.newBuilder(
"Allocation: ",
ByteConvertUtil.getPrintSize(used),
" / Maximum available: ",
... |
public boolean matchStage(StageConfigIdentifier stageIdentifier, StageEvent event) {
return this.event.include(event) && appliesTo(stageIdentifier.getPipelineName(), stageIdentifier.getStageName());
} | @Test
void anyPipelineShouldAlwaysMatch() {
NotificationFilter filter = new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Breaks, false);
assertThat(filter.matchStage(new StageConfigIdentifier("cruise", "dev"), StageEvent.Breaks)).isTrue();
} |
public Map<String, Object> getKsqlStreamConfigProps(final String applicationId) {
final Map<String, Object> map = new HashMap<>(getKsqlStreamConfigProps());
map.put(
MetricCollectors.RESOURCE_LABEL_PREFIX
+ StreamsConfig.APPLICATION_ID_CONFIG,
applicationId
);
// Streams cli... | @Test
public void shouldSetLogAndContinueExceptionHandlerWhenFailOnDeserializationErrorFalse() {
final KsqlConfig ksqlConfig = new KsqlConfig(Collections.singletonMap(KsqlConfig.FAIL_ON_DESERIALIZATION_ERROR_CONFIG, false));
final Object result = ksqlConfig.getKsqlStreamConfigProps().get(StreamsConfig.DEFAULT... |
@Subscribe
@AllowConcurrentEvents
public void handleIndexDeletion(IndicesDeletedEvent event) {
for (String index : event.indices()) {
LOG.debug("Index \"{}\" has been deleted. Removing index range.", index);
if (remove(index)) {
auditEventSender.success(AuditActor... | @Test
@MongoDBFixtures("MongoIndexRangeServiceTest.json")
public void testHandleIndexDeletion() throws Exception {
assertThat(indexRangeService.findAll()).hasSize(2);
localEventBus.post(IndicesDeletedEvent.create(Collections.singleton("graylog_1")));
assertThat(indexRangeService.findAl... |
public MeasureDto toMeasureDto(Measure measure, Metric metric, Component component) {
MeasureDto out = new MeasureDto();
out.setMetricUuid(metric.getUuid());
out.setComponentUuid(component.getUuid());
out.setAnalysisUuid(analysisMetadataHolder.getUuid());
if (measure.hasQualityGateStatus()) {
... | @Test
@UseDataProvider("all_types_Measures")
public void toMeasureDto_returns_Dto_without_alertStatus_nor_alertText_if_Measure_has_no_QualityGateStatus(Measure measure, Metric metric) {
MeasureDto measureDto = underTest.toMeasureDto(measure, metric, SOME_COMPONENT);
assertThat(measureDto.getAlertStatus()).... |
private Set<TimelineEntity> getEntities(Path dir, String entityType,
TimelineEntityFilters filters, TimelineDataToRetrieve dataToRetrieve)
throws IOException {
// First sort the selected entities based on created/start time.
Map<Long, Set<TimelineEntity>> sortedEntities =
new TreeMap<>(
... | @Test
void testGetAllEntities() throws Exception {
Set<TimelineEntity> result = reader.getEntities(
new TimelineReaderContext("cluster1", "user1", "flow1", 1L, "app1",
"app", null), new TimelineEntityFilters.Builder().build(),
new TimelineDataToRetrieve(null, null, EnumSet.of(Field.ALL... |
@Override
public void enableDeepLinkInstallSource(boolean enable) {
} | @Test
public void enableDeepLinkInstallSource() {
mSensorsAPI.enableDeepLinkInstallSource(true);
Assert.assertFalse(mSensorsAPI.isNetworkRequestEnable());
} |
@Override
public UniquenessLevel getIndexUniquenessLevel() {
return UniquenessLevel.SCHEMA_LEVEL;
} | @Test
void assertGetIndexUniquenessLevel() {
assertThat(uniquenessLevelProvider.getIndexUniquenessLevel(), is(UniquenessLevel.SCHEMA_LEVEL));
} |
public RepositoryMeta createRepository( String id, Map<String, Object> items ) {
RepositoryMeta repositoryMeta;
try {
repositoryMeta = pluginRegistry.loadClass( RepositoryPluginType.class, id, RepositoryMeta.class );
repositoryMeta.populate( items, repositoriesMeta );
if ( repositoryMeta.getN... | @Test
public void testCreateRepository() throws Exception {
String id = ID;
Map<String, Object> items = new HashMap<>();
when( pluginRegistry.loadClass( RepositoryPluginType.class, id, RepositoryMeta.class ) )
.thenReturn( repositoryMeta );
when( pluginRegistry.loadClass( RepositoryPluginType.c... |
@Description("Returns true if the input geometry is well formed")
@ScalarFunction("ST_IsValid")
@SqlType(BOOLEAN)
public static boolean stIsValid(@SqlType(GEOMETRY_TYPE_NAME) Slice input)
{
try {
return deserialize(input).isValid();
}
catch (PrestoException e) {
... | @Test
public void testSTIsValid()
{
// empty geometries are valid
assertValidGeometry("POINT EMPTY");
assertValidGeometry("MULTIPOINT EMPTY");
assertValidGeometry("LINESTRING EMPTY");
assertValidGeometry("MULTILINESTRING EMPTY");
assertValidGeometry("POLYGON EMPTY... |
public static Iterable<Snapshot> ancestorsOf(long snapshotId, Function<Long, Snapshot> lookup) {
Snapshot start = lookup.apply(snapshotId);
Preconditions.checkArgument(start != null, "Cannot find snapshot: %s", snapshotId);
return ancestorsOf(start, lookup);
} | @Test
public void ancestorsOf() {
Iterable<Snapshot> snapshots = SnapshotUtil.ancestorsOf(snapshotFork2Id, table::snapshot);
expectedSnapshots(new long[] {snapshotFork2Id, snapshotFork1Id}, snapshots);
Iterator<Snapshot> snapshotIter = snapshots.iterator();
while (snapshotIter.hasNext()) {
snap... |
@Override
public void execute(Context context) {
List<MeasureComputerWrapper> wrappers = Arrays.stream(measureComputers).map(ToMeasureWrapper.INSTANCE).toList();
validateMetrics(wrappers);
measureComputersHolder.setMeasureComputers(sortComputers(wrappers));
} | @Test
public void return_empty_list_when_no_metrics_neither_measure_computers() {
ComputationStep underTest = new LoadMeasureComputersStep(holder);
underTest.execute(new TestComputationStepContext());
assertThat(holder.getMeasureComputers()).isEmpty();
} |
public static SlaveConnectionManager getInstance() {
if ( slaveConnectionManager == null ) {
slaveConnectionManager = new SlaveConnectionManager();
}
return slaveConnectionManager;
} | @Test
public void shouldNotOverrideDefaultSSLContextIfKeystoreIsSet() throws Exception {
System.setProperty( "javax.net.ssl.keyStore", "NONE" );
SlaveConnectionManager instance = SlaveConnectionManager.getInstance();
assertEquals( defaultContext, SSLContext.getDefault() );
} |
@Override
public boolean fastPutIfAbsent(K key, V value, Duration ttl) {
return get(fastPutIfAbsentAsync(key, value, ttl));
} | @Test
public void testFastPutIfAbsentWithTTL() throws Exception {
RMapCacheNative<SimpleKey, SimpleValue> map = redisson.getMapCacheNative("simpleTTL");
SimpleKey key = new SimpleKey("1");
SimpleValue value = new SimpleValue("2");
map.fastPutIfAbsent(key, value, Duration.ofSeconds(1)... |
public final Logger getLogger(final Class<?> clazz) {
return getLogger(clazz.getName());
} | @Test
public void testLoggerX() {
Logger x = lc.getLogger("x");
assertNotNull(x);
assertEquals("x", x.getName());
assertNull(x.getLevel());
assertEquals(Level.DEBUG, x.getEffectiveLevel());
} |
boolean isWriteShareGroupStateSuccessful(List<PersisterStateBatch> stateBatches) {
WriteShareGroupStateResult response;
try {
response = persister.writeState(new WriteShareGroupStateParameters.Builder()
.setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<Partition... | @Test
public void testWriteShareGroupStateWithNoOpShareStatePersister() {
SharePartition sharePartition = SharePartitionBuilder.builder().build();
List<PersisterStateBatch> stateBatches = Arrays.asList(
new PersisterStateBatch(5L, 10L, RecordState.AVAILABLE.id, (short) 2),
... |
@Override
public void destroy() {
if (evictionScheduler != null) {
evictionScheduler.remove(getRawName());
}
super.destroy();
List<String> channels = Arrays.asList(getCreatedChannelName(), getRemovedChannelName(), getUpdatedChannelName(), getExpiredChannelName());
... | @Test
public void testDestroy() {
RMapCache<String, String> cache = redisson.getMapCache("test");
AtomicInteger counter = new AtomicInteger();
cache.addListener(new EntryCreatedListener<>() {
@Override
public void onCreated(EntryEvent<Object, Object> event) {
... |
@Description("encode value as a 32-bit 2's complement big endian varbinary")
@ScalarFunction("to_big_endian_32")
@SqlType(StandardTypes.VARBINARY)
public static Slice toBigEndian32(@SqlType(StandardTypes.INTEGER) long value)
{
Slice slice = Slices.allocate(Integer.BYTES);
slice.setInt(0,... | @Test
public void testToBigEndian32()
{
assertFunction("to_big_endian_32(0)", VARBINARY, sqlVarbinaryHex("00000000"));
assertFunction("to_big_endian_32(1)", VARBINARY, sqlVarbinaryHex("00000001"));
assertFunction("to_big_endian_32(2147483647)", VARBINARY, sqlVarbinaryHex("7FFFFFFF"));
... |
@Override
public SymbolTable getResponseSymbolTable(URI requestUri, Map<String, String> requestHeaders)
{
return _defaultResponseSymbolTable;
} | @Test
public void testGetResponseSymbolTableBeforeInit()
{
Assert.assertNull(_provider.getResponseSymbolTable(URI.create("https://Host:100/service/symbolTable"), Collections.emptyMap()));
} |
@Override
public NativeQuerySpec<Record> select(String sql, Object... args) {
return new NativeQuerySpecImpl<>(this, sql, args, DefaultRecord::new, false);
} | @Test
public void testPage() {
DefaultQueryHelper helper = new DefaultQueryHelper(database);
database.dml()
.insert("s_test")
.value("id", "page-test")
.value("name", "page")
.value("age", 22)
.execute()
... |
public SimpleRabbitListenerContainerFactory decorateSimpleRabbitListenerContainerFactory(
SimpleRabbitListenerContainerFactory factory
) {
return decorateRabbitListenerContainerFactory(factory);
} | @Test void decorateSimpleRabbitListenerContainerFactory_adds_TracingMessagePostProcessor() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory))
.extracting("beforeSendReplyPostProcessors... |
public Set<MediaType> getSupportedTypes(ParseContext context) {
return SUPPORTED_TYPES;
} | @Test
public void testAccept() throws Exception {
assertTrue((parser.getSupportedTypes(null)
.contains(MediaType.application("vnd.ms-outlook-pst"))));
} |
@Udf
public <T> List<String> mapKeys(final Map<String, T> input) {
if (input == null) {
return null;
}
return Lists.newArrayList(input.keySet());
} | @Test
public void shouldGetKeys() {
final Map<String, String> input = new HashMap<>();
input.put("foo", "spam");
input.put("bar", "baloney");
assertThat(udf.mapKeys(input), containsInAnyOrder("foo", "bar"));
} |
@Override
public void handle(ContainersLauncherEvent event) {
// TODO: ContainersLauncher launches containers one by one!!
Container container = event.getContainer();
ContainerId containerId = container.getContainerId();
switch (event.getType()) {
case LAUNCH_CONTAINER:
Application app =... | @Test
public void testRecoverPausedContainerEvent()
throws IllegalArgumentException {
when(event.getType())
.thenReturn(ContainersLauncherEventType.RECOVER_PAUSED_CONTAINER);
spy.handle(event);
Mockito.verify(containerLauncher, Mockito.times(1))
.submit(Mockito.any(RecoverPausedConta... |
public static String generateWsRemoteAddress(HttpServletRequest request) {
if (request == null) {
throw new IllegalArgumentException("HttpServletRequest must not be null.");
}
StringBuilder remoteAddress = new StringBuilder();
String scheme = request.getScheme();
rem... | @Test
public void testGenerateWssRemoteAddress() {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getScheme()).thenReturn("https");
when(request.getRemoteAddr()).thenReturn("localhost");
when(request.getRemotePort()).thenReturn(8443);
assertEquals(... |
@Override
public Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(Map<TopicPartition, Long> timestampsToSearch) {
return offsetsForTimes(timestampsToSearch, Duration.ofMillis(defaultApiTimeoutMs));
} | @Test
public void testOffsetsForTimes() {
consumer = newConsumer();
Map<TopicPartition, OffsetAndTimestampInternal> expectedResult = mockOffsetAndTimestamp();
Map<TopicPartition, Long> timestampToSearch = mockTimestampToSearch();
doReturn(expectedResult).when(applicationEventHandler... |
@Override
protected void doDelete(final List<MetaData> dataList) {
dataList.forEach(metaData -> metaDataSubscribers.forEach(metaDataSubscriber -> metaDataSubscriber.unSubscribe(metaData)));
} | @Test
public void testDoDelete() {
List<MetaData> metaDataList = createFakeMetaDataObjects(3);
metaDataHandler.doDelete(metaDataList);
metaDataList.forEach(metaData ->
subscribers.forEach(subscriber -> verify(subscriber).unSubscribe(metaData)));
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final ReadOnlyWindowStore<GenericKey, ValueAndTime... | @Test
public void shouldGetStoreWithCorrectParams_fetchAll() {
// When:
table.get(PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS);
// Then:
verify(stateStore).store(storeTypeCaptor.capture(), anyInt());
assertThat(storeTypeCaptor.getValue().getClass().getSimpleName(),
is("TimestampedWi... |
public OptExpression next() {
// For logic scan to physical scan, we only need to match once
if (isPatternWithoutChildren && groupExpressionIndex.get(0) > 0) {
return null;
}
OptExpression expression;
do {
this.groupTraceKey = 0;
// Match wit... | @Test
public void testBinderMulti2() {
OptExpression expr1 = OptExpression.create(new MockOperator(OperatorType.LOGICAL_JOIN, 0),
OptExpression.create(new MockOperator(OperatorType.LOGICAL_PROJECT, 1)),
OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN, 2))... |
public boolean optionallyValidateClientResponseStatusCode(int statusCode) throws Exception {
HttpStatus httpStatus = HttpStatus.resolve(statusCode);
if (this.statusCodesValid.isPresent() && httpStatus!=null) {
if (!this.statusCodesValid.get().contains(httpStatus)) {
return fa... | @Test
public void testSuccessStatus() throws Exception{
assertTrue(http2ServiceRequest.optionallyValidateClientResponseStatusCode(200));
assertTrue(http2ServiceRequest.optionallyValidateClientResponseStatusCode(201));
assertTrue(http2ServiceRequest.optionallyValidateClientResponseStatusCode... |
public static <T extends Throwable> void checkContains(final Collection<?> values, final Object element, final Supplier<T> exceptionSupplierIfUnexpected) throws T {
if (!values.contains(element)) {
throw exceptionSupplierIfUnexpected.get();
}
} | @Test
void assertCheckContainsToThrowsException() {
assertThrows(SQLException.class, () -> ShardingSpherePreconditions.checkContains(Collections.singleton("foo"), "bar", SQLException::new));
} |
@GetMapping("create")
public String getNewProductPage() {
return "catalogue/products/new_product";
} | @Test
void getNewProductPage_ReturnsNewProductPage () {
// given
// when
var result = this.controller.getNewProductPage();
// then
assertEquals("catalogue/products/new_product", result);
} |
public HMac(HmacAlgorithm algorithm) {
this(algorithm, (Key) null);
} | @Test
public void hmacTest(){
String testStr = "test中文";
byte[] key = "password".getBytes();
HMac mac = new HMac(HmacAlgorithm.HmacMD5, key);
String macHex1 = mac.digestHex(testStr);
assertEquals("b977f4b13f93f549e06140971bded384", macHex1);
String macHex2 = mac.digestHex(IoUtil.toStream(testStr, Charse... |
@Override
public final char readChar() throws EOFException {
final char c = readChar(pos);
pos += CHAR_SIZE_IN_BYTES;
return c;
} | @Test
public void testReadChar() throws Exception {
char c = in.readChar();
char expected = Bits.readChar(INIT_DATA, 0, byteOrder == BIG_ENDIAN);
assertEquals(expected, c);
} |
public static SQLStatementParserEngine getSQLStatementParserEngine(final DatabaseType databaseType,
final CacheOption sqlStatementCacheOption, final CacheOption parseTreeCacheOption) {
SQLStatementParserEngine result = ENGINES.get(databaseTy... | @Test
void assertGetSQLStatementParserEngineSame() {
SQLStatementParserEngine before = SQLStatementParserEngineFactory.getSQLStatementParserEngine(databaseType, new CacheOption(2000, 65535L), new CacheOption(128, 1024L));
SQLStatementParserEngine after = SQLStatementParserEngineFactory.getSQLStateme... |
Configuration getEffectiveConfiguration(String[] args) throws CliArgsException {
final CommandLine commandLine = cli.parseCommandLineOptions(args, true);
final Configuration effectiveConfiguration = new Configuration(baseConfiguration);
effectiveConfiguration.addAll(cli.toConfiguration(commandLi... | @Test
void testCorrectSettingOfMaxSlots() throws Exception {
final String[] params =
new String[] {
"-e",
KubernetesSessionClusterExecutor.NAME,
"-D" + TaskManagerOptions.NUM_TASK_SLOTS.key() + "=3"
};
final... |
@SuppressWarnings("unchecked")
void openDB(final Map<String, Object> configs, final File stateDir) {
// initialize the default rocksdb options
final DBOptions dbOptions = new DBOptions();
final ColumnFamilyOptions columnFamilyOptions = new ColumnFamilyOptions();
userSpecifiedOptions... | @Test
public void shouldNotSetCacheInValueProvidersWhenUserProvidesPlainTableFormatConfig() {
rocksDBStore = getRocksDBStoreWithRocksDBMetricsRecorder();
context = getProcessorContext(
RecordingLevel.DEBUG,
RocksDBConfigSetterWithUserProvidedNewPlainTableFormatConfig.class
... |
@Override
public List<ServiceCombServer> getInitialListOfServers() {
return getUpdatedListOfServers();
} | @Test
public void getInitialListOfServers() {
final List<ServiceCombServer> initialListOfServers = serviceCombServiceList.getInitialListOfServers();
Assert.assertEquals(initialListOfServers.size(), instances.size());
} |
public boolean isAllowed() {
return get(ALLOWED, true);
} | @Test
public void basicTest() {
ConfigApplyDelegate delegate = configApply -> { };
ObjectMapper mapper = new ObjectMapper();
TestConfig allowed = new TestConfig();
TestConfig notAllowed = new TestConfig();
allowed.init("enabled", "KEY", JsonNodeFactory.instance.objectNode()... |
@SuppressFBWarnings(value = "DMI_RANDOM_USED_ONLY_ONCE")
public static LocalCommands open(
final KsqlEngine ksqlEngine,
final File directory
) {
if (!directory.exists()) {
if (!directory.mkdirs()) {
throw new KsqlServerException("Couldn't create the local commands directory: "
... | @Test
public void shouldCreateCommandLocationWhenDoesNotExist() throws IOException {
// Given
final Path dir = Paths.get(commandsDir.newFolder().getAbsolutePath(), "ksql-local-commands");
assertThat(Files.exists(dir), is(false));
// When
LocalCommands.open(ksqlEngine, dir.toFile());
// Then
... |
@Override
public Num calculate(BarSeries series, Position position) {
return isConsecutive(position) ? series.one() : series.zero();
} | @Test
public void calculateWithNoPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
assertNumEquals(0, getCriterion(PositionFilter.LOSS).calculate(series, new BaseTradingRecord()));
assertNumEquals(0, getCriterion(PositionFilter.PROFIT).calcula... |
@SuppressWarnings("unused") // Required for automatic type inference
public static <K> Builder0<K> forClass(final Class<K> type) {
return new Builder0<>();
} | @Test
public void shouldNotThrowOnDuplicateHandler2() {
HandlerMaps.forClass(BaseType.class).withArgTypes(String.class, Integer.class)
.put(LeafTypeA.class, handler2_1)
.put(LeafTypeB.class, handler2_1);
} |
public boolean isConfigServiceCacheKeyIgnoreCase() {
return getBooleanProperty("config-service.cache.key.ignore-case", false);
} | @Test
public void testIsConfigServiceCacheKeyIgnoreCase() {
assertFalse(bizConfig.isConfigServiceCacheKeyIgnoreCase());
when(environment.getProperty("config-service.cache.key.ignore-case")).thenReturn("true");
assertTrue(bizConfig.isConfigServiceCacheKeyIgnoreCase());
} |
public ShardingSphereDatabase getDatabase(final String name) {
ShardingSpherePreconditions.checkNotEmpty(name, NoDatabaseSelectedException::new);
ShardingSphereMetaData metaData = getMetaDataContexts().getMetaData();
ShardingSpherePreconditions.checkState(metaData.containsDatabase(name), () -> n... | @Test
void assertGetDatabaseWithEmptyString() {
assertThrows(NoDatabaseSelectedException.class, () -> contextManager.getDatabase(""));
} |
private RemotingCommand getConsumeStats(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final GetConsumeStatsRequestHeader requestHeader =
(GetConsumeStatsRequestHeader... | @Test
public void testGetConsumeStats() throws RemotingCommandException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUME_STATS, null);
request.addExtField("topic", "topicTest");
request.addExtField("consumerGroup", "GID-test");
RemotingCommand ... |
@VisibleForTesting
Map<String, Object> getCustomMessageModel(EventNotificationContext ctx, String type, List<MessageSummary> backlog, DateTimeZone timeZone) {
final EventNotificationModelData modelData = EventNotificationModelData.of(ctx, backlog);
LOG.debug("Custom message model: {}", modelData);
... | @Test
public void getCustomMessageModel() {
List<MessageSummary> messageSummaries = generateMessageSummaries(50);
Map<String, Object> customMessageModel = teamsEventNotification.getCustomMessageModel(eventNotificationContext, notificationConfig.type(), messageSummaries, DateTimeZone.UTC);
a... |
@Override
public boolean checkCredentials(String username, String password) {
if (username == null || password == null) {
return false;
}
Credentials credentials = new Credentials(username, password);
if (validCredentialsCache.contains(credentials)) {
return ... | @Test
public void testPBKDF2WithHmacSHA512_withoutColon() throws Exception {
String algorithm = "PBKDF2WithHmacSHA512";
int iterations = 1000;
int keyLength = 128;
String hash =
"07:6F:E2:27:9B:CA:48:66:9B:13:9E:02:9C:AE:FC:E4:1A:2F:0F:E6:48:A3:FF:8E:D2:30:59:68:12:A6... |
@Override
public void persist(final String key, final String value) {
try {
if (isExisted(key)) {
update(key, value);
return;
}
String tempPrefix = "";
String parent = SEPARATOR;
String[] paths = Arrays.stream(key.sp... | @Test
void assertPersistWithInsertForSimpleKeys() throws SQLException {
final String key = "key";
final String value = "value";
when(mockJdbcConnection.prepareStatement(repositorySQL.getSelectByKeySQL())).thenReturn(mockPreparedStatement);
when(mockJdbcConnection.prepareStatement(rep... |
public static void delete(final File file, final boolean ignoreFailures)
{
if (file.exists())
{
if (file.isDirectory())
{
final File[] files = file.listFiles();
if (null != files)
{
for (final File f : files)... | @Test
void deleteIgnoreFailuresFile() throws IOException
{
final Path file = tempDir.resolve("file.txt");
Files.createFile(file);
IoUtil.delete(file.toFile(), false);
assertFalse(Files.exists(file));
} |
@Override
public boolean filterTopic(String topicName) {
if (StringUtils.isBlank(topicName)) {
return true;
}
return TopicValidator.isSystemTopic(topicName) ||
PopAckConstants.isStartWithRevivePrefix(topicName) ||
this.topicBlackSet.contains(topicName) ||
... | @Test
public void filterTopicTest() {
MessageStoreFilter topicFilter = new MessageStoreTopicFilter(new MessageStoreConfig());
Assert.assertTrue(topicFilter.filterTopic(""));
Assert.assertTrue(topicFilter.filterTopic(TopicValidator.SYSTEM_TOPIC_PREFIX + "_Topic"));
String topicName =... |
@VisibleForTesting
void loadUdfFromClass(final Class<?>... udfClasses) {
for (final Class<?> theClass : udfClasses) {
loadUdfFromClass(
theClass, KsqlScalarFunction.INTERNAL_PATH);
}
} | @Test
public void shouldThrowOnMissingAnnotation() throws Exception {
// Given:
final MutableFunctionRegistry functionRegistry = new InternalFunctionRegistry();
final Path udfJar = new File("src/test/resources/udf-failing-tests.jar").toPath();
try (UdfClassLoader udfClassLoader = newClassLoader(udfJar... |
public static MultivaluedHashMap<String, String> getQueryParams(Map<String, String[]> parameterMap) {
MultivaluedHashMap<String, String> queryParameters = new MultivaluedHashMap<>();
if (parameterMap.size() == 0) {
return queryParameters;
}
for (Map.Entry<String, String[]> ... | @Test(description = "convert query parameters to multivaluedmap")
public void convertWithRightOutputSize() throws Exception {
Map<String, String[]> params = new HashMap<>();
params.put("key1", new String[]{"value1", "value2"});
params.put("key2", new String[]{"value2", "value3", "value4", "... |
public static Frequency ofKHz(long value) {
return new Frequency(value * KHZ);
} | @Test
public void testofKHz() {
Frequency frequency = Frequency.ofKHz(1.0);
assertThat(frequency.asHz(), is(1000L));
} |
static String formatAuthorizationHeader(String clientId, String clientSecret, boolean urlencode) throws
UnsupportedEncodingException {
clientId = sanitizeString("the token endpoint request client ID parameter", clientId);
clientSecret = sanitizeString("the token endpoint request client secret pa... | @Test
public void testFormatAuthorizationHeader() throws UnsupportedEncodingException {
assertAuthorizationHeader("id", "secret", false, "Basic aWQ6c2VjcmV0");
} |
protected int getRepoStringLength() {
return database.getDatabaseMeta().getDatabaseInterface().getMaxVARCHARLength() - 1 > 0 ? database.getDatabaseMeta()
.getDatabaseInterface().getMaxVARCHARLength() - 1 : KettleDatabaseRepository.REP_ORACLE_STRING_LENGTH;
} | @Test
public void testOracleDBRepoStringLength() throws Exception {
KettleEnvironment.init();
DatabaseMeta databaseMeta = new DatabaseMeta( "OraRepo", "ORACLE", "JDBC", null, "test", null, null, null );
repositoryMeta =
new KettleDatabaseRepositoryMeta( "KettleDatabaseRepository", "OraRepo", "Ora... |
@Override
public void getFields( RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
if ( nextStep != null ) {
if ( nextStep.equals( executionResultTar... | @Test
public void testGetFields() throws Exception {
TransExecutorMeta meta = new TransExecutorMeta();
meta = spy( meta );
StepMeta nextStep = mock( StepMeta.class );
// Test null
meta.getFields( null, null, null, nextStep, null, null, null );
verify( meta, never() ).addFieldToRow( any( RowM... |
@Override
public List<? extends Issue> getIssues() {
return componentIssues;
} | @Test
public void get_issues() {
DefaultIssue issue = new DefaultIssue()
.setKey("KEY")
.setRuleKey(RuleKey.of("xoo", "S01"))
.setSeverity("MAJOR")
.setStatus("CLOSED")
.setResolution("FIXED")
.setEffort(Duration.create(10L));
MeasureComputerContextImpl underTest = newCont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.