focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@ConstantFunction.List(list = { @ConstantFunction(name = "day", argTypes = {DATETIME}, returnType = TINYINT), @ConstantFunction(name = "day", argTypes = {DATE}, returnType = TINYINT) }) public static ConstantOperator day(ConstantOperator arg) { return ConstantOperator.createTinyI...
@Test public void day() { assertEquals(23, ScalarOperatorFunctions.day(O_DT_20150323_092355).getTinyInt()); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testUnpartitionedBucketString() throws Exception { createUnpartitionedTable(spark, tableName); SparkScanBuilder builder = scanBuilder(); BucketFunction.BucketString function = new BucketFunction.BucketString(); UserDefinedScalarFunc udf = toUDF(function, expressions(intLit(...
public static void clean( Object func, ExecutionConfig.ClosureCleanerLevel level, boolean checkSerializable) { clean(func, level, checkSerializable, Collections.newSetFromMap(new IdentityHashMap<>())); }
@Test void testWriteReplaceRecursive() { WithWriteReplace writeReplace = new WithWriteReplace(new WithWriteReplace.Payload("text")); assertThat(writeReplace.getPayload().getRaw()).isEqualTo("text"); ClosureCleaner.clean(writeReplace, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true); ...
public static Schema reassignOrRefreshIds(Schema schema, Schema idSourceSchema) { return reassignOrRefreshIds(schema, idSourceSchema, true); }
@Test public void testReassignOrRefreshIdsCaseInsensitive() { Schema schema = new Schema( Lists.newArrayList( required(1, "FIELD1", Types.IntegerType.get()), required(2, "FIELD2", Types.IntegerType.get()))); Schema sourceSchema = new Schema( ...
public CompletableFuture<Optional<Account>> getByAccountIdentifierAsync(final UUID uuid) { return checkRedisThenAccountsAsync( getByUuidTimer, () -> redisGetByAccountIdentifierAsync(uuid), () -> accounts.getByAccountIdentifierAsync(uuid) ); }
@Test void testGetAccountByUuidBrokenCacheAsync() { UUID uuid = UUID.randomUUID(); UUID pni = UUID.randomUUID(); Account account = AccountsHelper.generateTestAccount("+14152222222", uuid, pni, new ArrayList<>(), new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]); when(asyncCommands.get(...
@Override public void removeSensor(final Sensor sensor) { Objects.requireNonNull(sensor, "Sensor is null"); metrics.removeSensor(sensor.name()); final Sensor parent = parentSensors.remove(sensor); if (parent != null) { metrics.removeSensor(parent.name()); } }
@Test public void testRemoveNullSensor() { assertThrows(NullPointerException.class, () -> streamsMetrics.removeSensor(null)); }
@Override public int count(double startScore, boolean startScoreInclusive, double endScore, boolean endScoreInclusive) { return get(countAsync(startScore, startScoreInclusive, endScore, endScoreInclusive)); }
@Test public void testCount() { RScoredSortedSet<String> set = redisson.getScoredSortedSet("simple"); set.add(0, "1"); set.add(1, "4"); set.add(2, "2"); set.add(3, "5"); set.add(4, "3"); assertThat(set.count(0, true, 3, false)).isEqualTo(3); }
@Override public Stream<ColumnName> resolveSelectStar( final Optional<SourceName> sourceName ) { if (sourceName.isPresent() && !sourceName.equals(getSourceName())) { throw new IllegalArgumentException("Expected alias of " + getAlias() + ", but was " + sourceName.get()); } // Note:...
@Test public void shouldResolveSelectStartToAllColumnsIncludingWindowBounds() { // Given: givenWindowedSource(true); givenNodeWithMockSource(); // When: final Stream<ColumnName> result = node.resolveSelectStar(Optional.empty()); // Then: final List<ColumnName> columns = result.collect(Co...
public void formatTo(DataTable table, StringBuilder appendable) { try { formatTo(table, (Appendable) appendable); } catch (IOException e) { throw new CucumberDataTableException(e.getMessage(), e); } }
@Test void should_print_to_string_builder() { DataTable table = tableOf("hello"); StringBuilder stringBuilder = new StringBuilder(); formatter.formatTo(table, stringBuilder); assertEquals("| hello |\n", stringBuilder.toString()); }
@Override public void close() { for (XATransactionDataSource each : cachedDataSources.values()) { each.close(); } cachedDataSources.clear(); if (null != xaTransactionManagerProvider) { xaTransactionManagerProvider.close(); } }
@Test void assertClose() { xaTransactionManager.close(); Map<String, XATransactionDataSource> cachedSingleXADataSourceMap = getCachedDataSources(); assertTrue(cachedSingleXADataSourceMap.isEmpty()); }
@Override public synchronized void setConf(Configuration conf) { super.setConf(conf); MetadataStore store; try { store = getMetadataStore(conf); } catch (MetadataException e) { throw new RuntimeException(METADATA_STORE_INSTANCE + " failed to init BookieId list...
@Test public void testMultipleMetadataServiceUris() { BookieRackAffinityMapping mapping1 = new BookieRackAffinityMapping(); ClientConfiguration bkClientConf1 = new ClientConfiguration(); bkClientConf1.setProperty("metadataServiceUri", "memory:local,memory:local"); bkClientConf1.setPr...
@Override List<DiscoveryNode> resolveNodes() { if (serviceName != null && !serviceName.isEmpty()) { logger.fine("Using service name to discover nodes."); return getSimpleDiscoveryNodes(client.endpointsByName(serviceName)); } else if (serviceLabel != null && !serviceLabel.isEm...
@Test public void resolveWithPodLabelWhenNodeWithPodLabel() { // given List<Endpoint> endpoints = createEndpoints(2); given(client.endpointsByPodLabel(POD_LABEL, POD_LABEL_VALUE)).willReturn(endpoints); KubernetesApiEndpointResolver sut = new KubernetesApiEndpointResolver(LOGGER, nu...
@Override public void register(@NonNull ThreadPoolPlugin plugin) { mainLock.runWithWriteLock(() -> { String id = plugin.getId(); Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered"); registeredPlugins.put(id, plugin); forQuic...
@Test public void testGetAllPluginsOfType() { manager.register(new TestExecuteAwarePlugin()); manager.register(new TestRejectedAwarePlugin()); Assert.assertEquals(1, manager.getAllPluginsOfType(TestExecuteAwarePlugin.class).size()); Assert.assertEquals(1, manager.getAllPluginsOfType(...
@Override public void createSubnet(Subnet osSubnet) { checkNotNull(osSubnet, ERR_NULL_SUBNET); checkArgument(!Strings.isNullOrEmpty(osSubnet.getId()), ERR_NULL_SUBNET_ID); checkArgument(!Strings.isNullOrEmpty(osSubnet.getNetworkId()), ERR_NULL_SUBNET_NET_ID); checkArgument(!Strings.i...
@Test(expected = IllegalArgumentException.class) public void testCreateSubnetWithNullNetworkId() { final Subnet testSubnet = NeutronSubnet.builder() .cidr("192.168.0.0/24") .build(); testSubnet.setId(SUBNET_ID); target.createSubnet(testSubnet); }
public Num getK() { return k; }
@Test public void bollingerBandsUpperUsingSMAAndStandardDeviation() { BollingerBandsMiddleIndicator bbmSMA = new BollingerBandsMiddleIndicator(sma); StandardDeviationIndicator standardDeviation = new StandardDeviationIndicator(closePrice, barCount); BollingerBandsUpperIndicator bbuSMA = new...
public void registerClass( String key, String className ) { extendedClasses.put( key, className ); }
@Test public void testRegisterClass() throws Exception { assertTrue( dialog.extendedClasses.isEmpty() ); dialog.registerClass( "MyClass", "org.pentaho.test.MyClass" ); assertFalse( dialog.extendedClasses.isEmpty() ); assertEquals( "org.pentaho.test.MyClass", dialog.extendedClasses.get( "MyClass" ) ); ...
public String generate() { return this.generate(false); }
@Test void testGenerate() throws IOException { AdaptiveClassCodeGenerator generator = new AdaptiveClassCodeGenerator(HasAdaptiveExt.class, "adaptive"); String value = generator.generate(); URL url = getClass().getResource("/org/apache/dubbo/common/extension/adaptive/HasAdaptiveExt$Adaptive")...
@Override public void setRole(Dpid dpid, RoleState role) { final OpenFlowSwitch sw = getSwitch(dpid); if (sw == null) { log.debug("Switch not connected. Ignoring setRole({}, {})", dpid, role); return; } sw.setRole(role); }
@Test public void testRoleSetting() { agent.addConnectedSwitch(dpid2, switch2); // check that state can be changed for a connected switch assertThat(switch2.getRole(), is(RoleState.MASTER)); controller.setRole(dpid2, RoleState.EQUAL); assertThat(switch2.getRole(), is(RoleSta...
public String orderClause(AmountRequest amountRequest) { return orderClause(amountRequest, ORDER_TERM_TO_SQL_STRING); }
@Test void mapWithSomeIllegalStuff2() { final AmountRequest pageRequest = new AmountRequest("updatedAt:\"delete * from jobtable\",createdAt:DESC", 2); assertThatThrownBy(() -> amountMapper.orderClause(pageRequest)) .isInstanceOf(IllegalArgumentException.class); }
@Override protected Object getContent(ScmGetRequest request) { GithubScm.validateUserHasPushPermission(request.getApiUrl(), request.getCredentials().getPassword().getPlainText(), request.getOwner(), request.getRepo()); String url = String.format("%s/repos/%s/%s/contents/%s", request...
@Test public void getContentForOrgFolderGHE() throws UnirestException { String credentialId = createGithubEnterpriseCredential(); StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID); MultiBranchProject mbp = mockMbp(credentialId, user, GithubEnterpriseScm.DOMAIN_NAME); ...
@SuppressWarnings("MagicConstant") @Override public int getTransactionIsolation() throws SQLException { return databaseConnectionManager.getTransactionIsolation().orElseGet(() -> transactionIsolation); }
@Test void assertGetTransactionIsolationWithoutCachedConnections() throws SQLException { try (ShardingSphereConnection connection = new ShardingSphereConnection(DefaultDatabase.LOGIC_NAME, mockContextManager())) { assertThat(connection.getTransactionIsolation(), is(Connection.TRANSACTION_READ_UN...
@SneakyThrows @Override public Integer call() throws Exception { super.call(); PicocliRunner.call(App.class, "sys", "database", "--help"); return 0; }
@Test void runWithNoParam() { ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); try (ApplicationContext ctx = ApplicationContext.builder().deduceEnvironment(false).start()) { String[] args = {}; Integer call = PicocliRunner...
public boolean accept(DefaultIssue issue, Component component) { if (component.getType() != FILE || (exclusionPatterns.isEmpty() && inclusionPatterns.isEmpty())) { return true; } if (isExclude(issue, component)) { return false; } return isInclude(issue, component); }
@Test public void ignore_and_include_same_rule_and_component() { IssueFilter underTest = newIssueFilter(newSettings( asList("xoo:x1", "**/xoo/File1*"), asList("xoo:x1", "**/xoo/File1*"))); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_1, COMPO...
public SQLTranslatorContext translate(final String sql, final List<Object> parameters, final QueryContext queryContext, final DatabaseType storageType, final ShardingSphereDatabase database, final RuleMetaData globalRuleMetaData) { DatabaseType sqlParserType = queryCont...
@Test void assertNotUseOriginalSQLWhenTranslatingFailed() { QueryContext queryContext = mock(QueryContext.class, RETURNS_DEEP_STUBS); DatabaseType sqlParserType = TypedSPILoader.getService(DatabaseType.class, "PostgreSQL"); when(queryContext.getSqlStatementContext().getDatabaseType()).thenRe...
protected T executeAutoCommitFalse(Object[] args) throws Exception { try { TableRecords beforeImage = beforeImage(); T result = statementCallback.execute(statementProxy.getTargetStatement(), args); TableRecords afterImage = afterImage(beforeImage); prepareUndoLog(...
@Test public void testExecuteAutoCommitFalse() throws Exception { Mockito.when(connectionProxy.getContext()) .thenReturn(new ConnectionContext()); PreparedStatementProxy statementProxy = Mockito.mock(PreparedStatementProxy.class); Mockito.when(statementProxy.getConnectionProx...
public final void sendResponse(Object value) { OperationResponseHandler responseHandler = getOperationResponseHandler(); if (responseHandler == null) { if (value instanceof Throwable throwable) { // in case of a throwable, we want the stacktrace. getLogger().w...
@Test public void sendResponse_whenResponseHandlerIsNull_andThrowableValue_thenNoNPE() { Operation op = new DummyOperation(); op.sendResponse(new Exception()); }
public EndpointResponse streamQuery( final KsqlSecurityContext securityContext, final KsqlRequest request, final CompletableFuture<Void> connectionClosedFuture, final Optional<Boolean> isInternalRequest, final MetricsCallbackHolder metricsCallbackHolder, final Context context ) { ...
@Test public void shouldSuggestAlternativesIfPrintTopicDoesNotExist() { // Given: final PrintTopic cmd = mock(PrintTopic.class); when(cmd.getTopic()).thenReturn("TEST_TOPIC"); print = PreparedStatement.of("print", cmd); when(mockStatementParser.<PrintTopic>parseSingleStatement(any())) .the...
@JsonCreator public static AuditEventType create(@JsonProperty(FIELD_NAMESPACE) String namespace, @JsonProperty(FIELD_OBJECT) String object, @JsonProperty(FIELD_ACTION) String action) { return new AutoValue_AuditEventType(namesp...
@Test public void testInvalid2() throws Exception { expectedException.expect(IllegalArgumentException.class); AuditEventType.create(""); }
public static <T extends com.google.protobuf.GeneratedMessageV3> ProtobufSchema<T> of(Class<T> pojo) { return of(pojo, new HashMap<>()); }
@Test public void testEncodeAndDecode() { Function.FunctionDetails functionDetails = Function.FunctionDetails.newBuilder().setName(NAME).build(); ProtobufSchema<Function.FunctionDetails> protobufSchema = ProtobufSchema.of(Function.FunctionDetails.class); byte[] bytes = protobufSchema.encod...
@Override protected String processLink(IExpressionContext context, String link) { if (link == null || !linkInSite(externalUrlSupplier.get(), link)) { return link; } if (StringUtils.isBlank(link)) { link = "/"; } if (isAssetsRequest(link)) { ...
@Test void processTemplateLinkWithActive() { ThemeLinkBuilder themeLinkBuilder = new ThemeLinkBuilder(getTheme(true), externalUrlSupplier); String link = "/post"; String processed = themeLinkBuilder.processLink(null, link); assertThat(processed).isEqualTo("/post"); }
@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 test_resolveObjectFields(boolean key, String prefix) { Map<String, String> options = Map.of( (key ? OPTION_KEY_FORMAT : OPTION_VALUE_FORMAT), JAVA_FORMAT, (key ? OPTION_KEY_CLASS :...
@Override public void init(HazelcastInstance instance, Properties properties, String mapName) { validateMapStoreConfig(instance, mapName); logger = instance.getLoggingService().getLogger(GenericMapLoader.class); this.instance = Util.getHazelcastInstanceImpl(instance); this.genericM...
@Test public void givenMapStoreConfig_WithoutDataConnection_thenFail() { MapStoreConfig mapStoreConfig = new MapStoreConfig() .setClassName(GenericMapLoader.class.getName()); MapConfig mapConfig = new MapConfig(mapName); mapConfig.setMapStoreConfig(mapStoreConfig); i...
@VisibleForTesting static ExternalResourceInfoProvider createStaticExternalResourceInfoProvider( Map<String, Long> externalResourceAmountMap, Map<String, ExternalResourceDriver> externalResourceDrivers) { final Map<String, Set<? extends ExternalResourceInfo>> externalResources = new ...
@Test public void testGetExternalResourceInfoProviderWithoutAmount() { final Map<String, Long> externalResourceAmountMap = new HashMap<>(); final Map<String, ExternalResourceDriver> externalResourceDrivers = new HashMap<>(); externalResourceDrivers.put(RESOURCE_NAME_1, new TestingExternalRes...
@SuppressWarnings("unchecked") public DynamicDestinations<UserT, DestinationT, OutputT> getDynamicDestinations() { return (DynamicDestinations<UserT, DestinationT, OutputT>) dynamicDestinations; }
@Test public void testCopyToOutputFiles() throws Exception { SimpleSink.SimpleWriteOperation<Void> writeOp = buildWriteOperation(); List<String> inputFilenames = Arrays.asList("input-1", "input-2", "input-3"); List<String> inputContents = Arrays.asList("1", "2", "3"); List<String> expectedOutputFilena...
public static Criterion matchTcpSrc(TpPort tcpPort) { return new TcpPortCriterion(tcpPort, Type.TCP_SRC); }
@Test public void testMatchTcpSrcMethod() { Criterion matchTcpSrc = Criteria.matchTcpSrc(tpPort1); TcpPortCriterion tcpPortCriterion = checkAndConvert(matchTcpSrc, Criterion.Type.TCP_SRC, TcpPortCriterion.class); ...
@Override public ByteBuf slice() { return slice(readerIndex, readableBytes()); }
@Test public void testSliceRelease() { ByteBuf buf = newBuffer(8); assertEquals(1, buf.refCnt()); assertTrue(buf.slice().release()); assertEquals(0, buf.refCnt()); }
@SuppressWarnings("unchecked") RestartRequest recordToRestartRequest(ConsumerRecord<String, byte[]> record, SchemaAndValue value) { String connectorName = record.key().substring(RESTART_PREFIX.length()); if (!(value.value() instanceof Map)) { log.error("Ignoring restart request because t...
@Test public void testRecordToRestartRequestIncludeTasksInconsistent() { ConsumerRecord<String, byte[]> record = new ConsumerRecord<>(TOPIC, 0, 0, 0L, TimestampType.CREATE_TIME, 0, 0, RESTART_CONNECTOR_KEYS.get(0), CONFIGS_SERIALIZED.get(0), new RecordHeaders(), Optional.empty()); St...
public static Map<AbilityKey, Boolean> getStaticAbilities() { return INSTANCE.getSupportedAbilities(); }
@Test void testGetStaticAbilities() { assertFalse(ServerAbilities.getStaticAbilities().isEmpty()); }
@Override public void addChildren(Deque<Expression> expressions) { addChildren(expressions, 2); }
@Test public void testSetOptions() throws IOException { And and = new And(); Expression first = mock(Expression.class); Expression second = mock(Expression.class); Deque<Expression> children = new LinkedList<Expression>(); children.add(second); children.add(first); and.addChildren(childre...
public static ApplyPermissionTemplateQuery create(String templateUuid, List<String> componentKeys) { return new ApplyPermissionTemplateQuery(templateUuid, componentKeys); }
@Test public void should_invalidate_query_with_empty_name() { assertThatThrownBy(() -> create("", newArrayList("1", "2", "3"))) .isInstanceOf(BadRequestException.class) .hasMessage("Permission template is mandatory"); }
public List<File> process() throws Exception { try { return doProcess(); } catch (Exception e) { // Cleaning up output dir as processing has failed. file managers left from map or reduce phase will be cleaned // up in the respective phases. FileUtils.deleteQuietly(_segmentsOutputDi...
@Test public void testRecordReaderFileConfigInit() throws Exception { File workingDir = new File(TEMP_DIR, "segmentOutput"); FileUtils.forceMkdir(workingDir); ClassLoader classLoader = getClass().getClassLoader(); URL resource = classLoader.getResource("data/dimBaseballTeams.csv"); RecordReader re...
public synchronized void createTable(String tableId, Iterable<String> columnFamilies) throws BigtableResourceManagerException { createTable(tableId, columnFamilies, Duration.ofHours(1)); }
@Test public void testCreateTableShouldWorkWhenBigtableDoesNotThrowAnyError() { setupReadyTable(); when(bigtableResourceManagerClientFactory.bigtableTableAdminClient().exists(anyString())) .thenReturn(false); testManager.createTable(TABLE_ID, ImmutableList.of("cf1")); verify(bigtableResourc...
@Override public void configure(final KsqlConfig config) { if (!config.getKsqlStreamConfigProps().containsKey(StreamsConfig.APPLICATION_SERVER_CONFIG)) { throw new IllegalArgumentException("Need KS application server set"); } final String applicationServer = (String) config.getKsqlStreamCon...
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnConfigureIfAppServerNotSet() { // Given: final KsqlConfig configNoAppServer = new KsqlConfig(ImmutableMap.of()); // When: ksqlResource.configure(configNoAppServer); }
@Operation(summary = "Finalize rda activation", tags = { SwaggerConfig.ACTIVATE_RDA}, operationId = "rdaActivationVerified", parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")}) @PostMapping(value = "rda_activatio...
@Test void validateIfCorrectProcessesAreCalledRdaFinalize() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException { AppSessionRequest request = new AppSessionRequest(); activationController.rdaFinalize(request); ver...
@Override public void run() throws Exception { // Get list of files to process. List<String> filteredFiles = SegmentGenerationUtils.listMatchedFilesWithRecursiveOption(_inputDirFS, _inputDirURI, _spec.getIncludeFileNamePattern(), _spec.getExcludeFileNamePattern(), _spec.isSearchRecursively()); ...
@Test public void testInputFilesWithSameNameInDifferentDirectories() throws Exception { File testDir = makeTestDir(); File inputDir = new File(testDir, "input"); File inputSubDir1 = new File(inputDir, "2009"); File inputSubDir2 = new File(inputDir, "2010"); inputSubDir1.mkdirs(); inputSu...
public void validate(DataConnectionConfig dataConnectionConfig) { int numberOfSetItems = getNumberOfSetItems(dataConnectionConfig, CLIENT_XML_PATH, CLIENT_YML_PATH, CLIENT_XML, CLIENT_YML); if (numberOfSetItems != 1) { throw new HazelcastException("HazelcastDataConnection wit...
@Test public void testValidateEitherStringOrFilePath() { DataConnectionConfig dataConnectionConfig = new DataConnectionConfig(); dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_XML_PATH, "xml_path"); dataConnectionConfig.setProperty(HazelcastDataConnection.CLIENT_XML, "xml");...
@Override public ChannelFuture writeData(final ChannelHandlerContext ctx, final int streamId, ByteBuf data, int padding, final boolean endOfStream, ChannelPromise promise) { promise = promise.unvoid(); final Http2Stream stream; try { stream = requireStream(streamId); ...
@Test public void dataFramesShouldMergeUseVoidPromise() throws Exception { createStream(STREAM_ID, false); final ByteBuf data = dummyData().retain(); ChannelPromise promise1 = newVoidPromise(channel); encoder.writeData(ctx, STREAM_ID, data, 0, true, promise1); ChannelPromise...
@Override public boolean hasPlugin(String key) { checkState(started.get(), NOT_STARTED_YET); return pluginInfosByKeys.containsKey(key); }
@Test public void hasPlugin_throws_ISE_if_repo_is_not_started() { assertThatThrownBy(() -> underTest.hasPlugin("foo")) .isInstanceOf(IllegalStateException.class) .hasMessage("not started yet"); }
static boolean isLeaf(int nodeOrder, int depth) { checkTrue(depth > 0, "Invalid depth: " + depth); int leafLevel = depth - 1; int numberOfNodes = getNumberOfNodes(depth); int maxNodeOrder = numberOfNodes - 1; checkTrue(nodeOrder >= 0 && nodeOrder <= maxNodeOrder, "Invalid nodeOrd...
@Test public void testIsLeaf() { assertTrue(MerkleTreeUtil.isLeaf(0, 1)); assertFalse(MerkleTreeUtil.isLeaf(0, 2)); assertTrue(MerkleTreeUtil.isLeaf(1, 2)); assertTrue(MerkleTreeUtil.isLeaf(2, 2)); assertFalse(MerkleTreeUtil.isLeaf(1, 3)); assertFalse(MerkleTreeUtil....
@Operation(summary = "Get the correct AT cetificate") @PostMapping(value = Constants.URL_NIK_START, consumes = "application/json", produces = "application/json") public GetCertificateResponse getCertificateRestService(@Valid @RequestBody GetCertificateRequest request, ...
@Test public void getCertificateRestServiceTest() { GetCertificateResponse expectedResponse = new GetCertificateResponse(); when(nikServiceMock.getCertificateRestService(any(GetCertificateRequest.class), anyString())).thenReturn(expectedResponse); GetCertificateResponse actualResponse = nik...
@Override public Set<Entry<K, V>> entries() { return (Set<Entry<K, V>>) super.entries(); }
@Test public void testEntrySet() { RSetMultimap<SimpleKey, SimpleValue> map = redisson.getSetMultimap("test1"); map.put(new SimpleKey("0"), new SimpleValue("1")); map.put(new SimpleKey("3"), new SimpleValue("4")); assertThat(map.entries().size()).isEqualTo(2); Map<SimpleKey,...
@Override public String getName() { return name; }
@Test public void testConstructor_withName() { config = new ScheduledExecutorConfig("myName"); assertEquals("myName", config.getName()); }
public static <K extends WritableComparable<?>, V extends Writable> Writable getEntry(MapFile.Reader[] readers, Partitioner<K, V> partitioner, K key, V value) throws IOException { int readerLength = readers.length; int part; if (readerLength <= 1) { part = 0; } else { part = par...
@SuppressWarnings("static-access") @Test public void testPartitionerShouldNotBeCalledWhenOneReducerIsPresent() throws Exception { MapFileOutputFormat outputFormat = new MapFileOutputFormat(); Reader reader = Mockito.mock(Reader.class); Reader[] readers = new Reader[]{reader}; outputFormat.getE...
@PublicEvolving public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes( MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) { return getMapReturnTypes(mapInterface, inType, null, false); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void testTupleArray() { RichMapFunction<?, ?> function = new RichMapFunction<Tuple2<String, String>[], Tuple2<String, String>[]>() { private static final long serialVersionUID = 1L; @Override ...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void testBuildWithIllegalMaxThreadPoolSize() { ThreadPoolBulkheadConfig.custom() .maxThreadPoolSize(-1) .build(); }
public static String safeBeaconCode(Point point) { if(point.rawData() instanceof HasBeaconCodes hbc) { String beacon = hbc.beaconActual(); return (beacon == null) ? UNKOWN_BEACON_VALUE : beacon; } return UNKOWN_BEACON_VALUE; }
@Test public void safeBeaconGeneratesDefaultValue() { Point p = Point.builder() .time(EPOCH) .latLong(0.0, 0.0) .build(); assertThat(safeBeaconCode(p), is(UNKOWN_BEACON_VALUE)); }
public StepInstanceActionResponse terminate( WorkflowInstance instance, String stepId, User user, Actions.StepInstanceAction action, boolean blocking) { validateStepId(instance, stepId, action); StepInstance stepInstance = stepInstanceDao.getStepInstance( insta...
@Test public void testSkip() { StepInstanceActionResponse response = actionDao.terminate(instance, "job1", user, SKIP, false); Assert.assertEquals("sample-dag-test-3", response.getWorkflowId()); Assert.assertEquals(1, response.getWorkflowInstanceId()); Assert.assertEquals(1, response.getWorkflowRunId(...
public static JsonMapper validateJsonMapper(JsonMapper jsonMapper) { try { final String serializedJob = jsonMapper.serialize(getJobForTesting()); testTimeFields(serializedJob); testUseFieldsNotMethods(serializedJob); testUsePolymorphism(serializedJob); ...
@Test void testInvalidJacksonJsonMapperNoISO8601TimeFormat() { assertThatThrownBy(() -> validateJsonMapper(new InvalidJacksonJsonMapper(new ObjectMapper().registerModule(new Jdk8Module()).registerModule(new JavaTimeModule())))) .isInstanceOf(IllegalArgumentException.class) .h...
public ClusterSerdes init(Environment env, ClustersProperties clustersProperties, int clusterIndex) { ClustersProperties.Cluster clusterProperties = clustersProperties.getClusters().get(clusterIndex); log.debug("Configuring serdes for cluster {}", clusterP...
@Test void serdeWithCustomNameAndBuiltInClassnameAreExplicitlyConfigured() { ClustersProperties.SerdeConfig serdeConfig = new ClustersProperties.SerdeConfig(); serdeConfig.setName("SomeSerde"); serdeConfig.setClassName(BuiltInSerdeWithAutoconfigure.class.getName()); serdeConfig.setTopicKeysPattern("ke...
@SuppressWarnings("MethodLength") public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { final MessageHeaderDecoder headerDecoder = decoders.header; headerDecoder.wrap(buffer, offset); final int schemaId = headerDecoder.schemaId(); ...
@Test void shouldHandleReplayRequest() { final ControlSessionDemuxer controlSessionDemuxer = new ControlSessionDemuxer( new ControlRequestDecoders(), mockImage, mockConductor, mockAuthorisationService); setupControlSession(controlSessionDemuxer, CONTROL_SESSION_ID); final Ex...
public void convertQueueHierarchy(FSQueue queue) { List<FSQueue> children = queue.getChildQueues(); final String queueName = queue.getName(); emitChildQueues(queueName, children); emitMaxAMShare(queueName, queue); emitMaxParallelApps(queueName, queue); emitMaxAllocations(queueName, queue); ...
@Test public void testQueueSizeBasedWeightDisabled() { converter = builder.build(); converter.convertQueueHierarchy(rootQueue); for (String queue : ALL_QUEUES) { key = PREFIX + queue + ".ordering-policy.fair.enable-size-based-weight"; assertNull("Key " + key + " has different value", ...
public Data getValueData() { if (valueData == null && serializationService != null) { valueData = serializationService.toData(value); } return valueData; }
@Test public void testGetValueData_withObjectValue() { assertEquals(toData("value"), objectEvent.getValueData()); }
@Override public EventNotificationConfigEntity toContentPackEntity(EntityDescriptorIds entityDescriptorIds) { return SlackEventNotificationConfigEntity.builder() .color(ValueReference.of(color())) .webhookUrl(ValueReference.of(webhookUrl())) .channel(ValueRefe...
@Test(expected = NullPointerException.class) public void toContentPackEntity() { final SlackEventNotificationConfig slackEventNotificationConfig = SlackEventNotificationConfig.builder().build(); slackEventNotificationConfig.toContentPackEntity(EntityDescriptorIds.empty()); }
public static void writePositionToBlockBuilder(Block block, int position, BlockBuilder blockBuilder) { if (block instanceof DictionaryBlock) { position = ((DictionaryBlock) block).getId(position); block = ((DictionaryBlock) block).getDictionary(); } if (blockBuilder ...
@Test public void testArrayBlockBuilder() { long[] values = new long[]{1, 2, 3, 4, 5}; ArrayBlockBuilder blockBuilder1 = new ArrayBlockBuilder(BIGINT, null, 1); BlockBuilder elementBuilder = blockBuilder1.beginBlockEntry(); for (long value : values) { BIGINT.writeLon...
public static boolean isNameCoveredByPattern( String name, String pattern ) { if ( name == null || name.isEmpty() || pattern == null || pattern.isEmpty() ) { throw new IllegalArgumentException( "Arguments cannot be null or empty." ); } final String needle = name.toLowerC...
@Test public void testNameCoverageSubSubdomainWithWildcard() throws Exception { // setup final String name = "deeper.xmpp.example.org"; final String pattern = "*.example.org"; // do magic final boolean result = DNSUtil.isNameCoveredByPattern( name, pattern ); //...
public void applyConfig(ClientBwListDTO configDTO) { requireNonNull(configDTO, "Client filtering config must not be null"); requireNonNull(configDTO.mode, "Config mode must not be null"); requireNonNull(configDTO.entries, "Config entries must not be null"); ClientSelector selector; ...
@Test public void testApplyConfig_nullEntryValue_throws() { ClientBwListDTO config = createConfig(Mode.WHITELIST, new ClientBwListEntryDTO(Type.IP_ADDRESS, null)); assertThrows(NullPointerException.class, () -> handler.applyConfig(config)); }
@Override public ByteBuf setByte(int index, int value) { checkIndex(index); _setByte(index, value); return this; }
@Test public void testSetByteAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().setByte(0, 1); } }); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("s3.listing.chunksize")); }
@Test public void tetsEmptyPlaceholder() throws Exception { final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(session)).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());...
@Override protected String copy(final Path source, final S3Object destination, final TransferStatus status, final StreamListener listener) throws BackgroundException { try { final List<MultipartPart> completed = new ArrayList<>(); // ID for the initiated multipart upload. ...
@Test public void testCopyBucketNameInHostname() throws Exception { final Path test = new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); final byte[] content = RandomUtils.nextBytes(1023); final TransferStatus status = new TransferStatus().withLength(conten...
@Override public List<AppAuthData> convert(final String json) { return GsonUtils.getInstance().fromList(json, AppAuthData.class); }
@Test public void testConvert() { AppAuthData appAuthData = createFakerAppAuthDataObjects(1).get(0); setAppAuthDataProperties(appAuthData); List<AppAuthData> sources = Collections.singletonList(appAuthData); Gson gson = new Gson(); String json = gson.toJson(sources); ...
public Account updatePniKeys(final Account account, final IdentityKey pniIdentityKey, final Map<Byte, ECSignedPreKey> deviceSignedPreKeys, @Nullable final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys, final List<IncomingMessage> deviceMessages, final Map<Byte, Integer> pniRegistrat...
@Test void updatePniKeysMismatchedRegistrationId() { final Account account = mock(Account.class); when(account.getNumber()).thenReturn("+18005551234"); final List<Device> devices = new ArrayList<>(); for (byte i = 1; i <= 3; i++) { final Device device = mock(Device.class); when(device.ge...
@PublicAPI(usage = ACCESS) public static PlantUmlArchCondition adhereToPlantUmlDiagram(URL url, Configuration configuration) { return create(url, configuration); }
@Test public void diagram_with_multiple_dependencies_that_considers_only_certain_packages() { File file = TestDiagram.in(temporaryFolder) .component("SomeOrigin").withStereoTypes("..origin") .component("SomeIntermediary").withStereoTypes("..intermediary") .com...
public static <V> SetOnceReference<V> ofNullable(final V value) { return new SetOnceReference<>(value); }
@Test public void testFromOfNullableWithValue() { final Sentinel sentinel = new Sentinel(); checkSetReferenceIsImmutable(SetOnceReference.ofNullable(sentinel), sentinel); }
@Override public List<ProviderGroup> subscribe(ConsumerConfig config) { String appName = config.getAppName(); if (!registryConfig.isSubscribe()) { // 注册中心不订阅 if (LOGGER.isInfoEnabled(appName)) { LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTR...
@Test public void testSubscribe() { ProviderConfig<?> providerConfig = providerConfig("consul-test-1", 12200, 12201, 12202); registry.register(providerConfig); ConsumerConfig<?> consumerConfig = consumerConfig("consul-test-1"); assertUntil(() -> { List<ProviderGroup> pr...
@Override public void publish(ScannerReportWriter writer) { AbstractProjectOrModule rootProject = moduleHierarchy.root(); ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder() .setAnalysisDate(projectInfo.getAnalysisDate().getTime()) // Here we want key without branch ...
@Test public void dont_write_new_code_reference_if_not_specified_in_properties() { when(referenceBranchSupplier.get()).thenReturn("ref"); when(referenceBranchSupplier.getFromProperties()).thenReturn(null); underTest.publish(writer); ScannerReport.Metadata metadata = reader.readMetadata(); asser...
private PlantUmlDiagram createDiagram(List<String> rawDiagramLines) { List<String> diagramLines = filterOutComments(rawDiagramLines); Set<PlantUmlComponent> components = parseComponents(diagramLines); PlantUmlComponents plantUmlComponents = new PlantUmlComponents(components); List<Parse...
@Test public void parses_multiple_components_and_dependencies() { File file = TestDiagram.in(temporaryFolder) .component("Component1").withStereoTypes("..origin1..") .component("Component2").withStereoTypes("..target1..") .component("Component3").withStereoTyp...
public synchronized String get() { ConfidentialStore cs = ConfidentialStore.get(); if (secret == null || cs != lastCS) { lastCS = cs; try { byte[] payload = load(); if (payload == null) { payload = cs.randomBytes(length / 2); ...
@Test public void multipleGetsAreIdempotent() { HexStringConfidentialKey key = new HexStringConfidentialKey("test", 8); assertEquals(key.get(), key.get()); }
public static void extractFilesUsingFilter(File archive, File destination, FilenameFilter filter) throws ExtractionException { if (archive == null || destination == null) { return; } try (FileInputStream fis = new FileInputStream(archive)) { extractArchive(new ZipArchive...
@Test(expected = org.owasp.dependencycheck.utils.ExtractionException.class) public void testExtractFilesUsingFilter() throws Exception { File destination = getSettings().getTempDirectory(); File archive = BaseTest.getResourceAsFile(this, "evil.zip"); ExtractionUtil.extractFiles(archive, dest...
@Override public Long time(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<Long> f = executorService.readAsync(entry, LongCodec.INSTANCE, RedisCommands.TIME_LONG); return syncFuture(f); }
@Test public void testTime() { RedisClusterNode master = getFirstMaster(); Long time = connection.time(master); assertThat(time).isGreaterThan(1000); }
static long calculateRocksDBMutableLimit(long bufferSize) { return bufferSize * 7 / 8; }
@Test public void testCalculateRocksDBMutableLimit() { long bufferSize = 64 * 1024 * 1024; long limit = bufferSize * 7 / 8; assertThat( RocksDBMemoryControllerUtils.calculateRocksDBMutableLimit(bufferSize), is(limit)); }
@SuppressWarnings({ "nullness" // TODO(https://github.com/apache/beam/issues/20497) }) @Override protected SchemaTransform from(KafkaReadSchemaTransformConfiguration configuration) { return new KafkaReadSchemaTransform(configuration); }
@Test public void testBuildTransformWithProtoFormatWrongMessageName() { ServiceLoader<SchemaTransformProvider> serviceLoader = ServiceLoader.load(SchemaTransformProvider.class); List<SchemaTransformProvider> providers = StreamSupport.stream(serviceLoader.spliterator(), false) .filt...
public static Schema schemaFromPojoClass( TypeDescriptor<?> typeDescriptor, FieldValueTypeSupplier fieldValueTypeSupplier) { return StaticSchemaInference.schemaFromClass(typeDescriptor, fieldValueTypeSupplier); }
@Test public void testNestedMap() { Schema schema = POJOUtils.schemaFromPojoClass( new TypeDescriptor<NestedMapPOJO>() {}, JavaFieldTypeSupplier.INSTANCE); SchemaTestUtils.assertSchemaEquivalent(NESTED_MAP_POJO_SCHEMA, schema); }
public Visibility get(DbSession dbSession) { PropertyDto defaultProjectVisibility = Optional .ofNullable(dbClient.propertiesDao().selectGlobalProperty(dbSession, PROJECTS_DEFAULT_VISIBILITY_PROPERTY_NAME)) .orElseThrow(() -> new IllegalStateException("Could not find default project visibility setting"))...
@Test public void fail_if_project_visibility_property_not_exist() { DbSession dbSession = db.getSession(); assertThatThrownBy(() -> underTest.get(dbSession)) .isInstanceOf(IllegalStateException.class) .hasMessage("Could not find default project visibility setting"); }
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}") public ApolloConfig queryConfig(@PathVariable String appId, @PathVariable String clusterName, @PathVariable String namespace, @RequestParam(value = "dataCenter", required = false) String da...
@Test public void testQueryConfigWithPublicNamespaceAndAppOverride() throws Exception { String someAppSideReleaseKey = "1"; String somePublicAppSideReleaseKey = "2"; HttpServletResponse someResponse = mock(HttpServletResponse.class); String somePublicAppId = "somePublicAppId"; AppNamespace somePu...
@Override public ImportResult importItem( UUID jobId, IdempotentImportExecutor idempotentExecutor, TokenSecretAuthData authData, VideosContainerResource data) throws Exception { if (data == null) { // Nothing to do return ImportResult.OK; } BackblazeDataTransferC...
@Test public void testNullData() throws Exception { BackblazeVideosImporter sut = new BackblazeVideosImporter(monitor, dataStore, streamProvider, clientFactory); ImportResult result = sut.importItem(UUID.randomUUID(), executor, authData, null); assertEquals(ImportResult.OK, result); }
@Override public boolean processArgument(final ShenyuRequest shenyuRequest, final Annotation annotation, final Object arg) { RequestTemplate requestTemplate = shenyuRequest.getRequestTemplate(); CookieValue cookie = ANNOTATION.cast(annotation); String name = cookie.value().trim(); ch...
@Test public void processArgumentTwoTest() { headers.put(HttpHeaders.COOKIE, Lists.newArrayList("one=one")); final CookieValue cookie = spy(CookieValue.class); when(cookie.value()).thenReturn("two"); processor.processArgument(request, cookie, "twoValue"); assertTrue(request....
@Override public boolean contains(Object o) { QueryableEntry entry = (QueryableEntry) o; if (index != null) { return checkFromIndex(entry); } else { //todo: what is the point of this condition? Is it some kind of optimization? if (resultSets.size() > 3) { ...
@Test public void testContains_notEmpty() { QueryableEntry entry = entry(data()); addEntry(entry); assertThat(result.contains(entry)).isTrue(); }
@VisibleForTesting void loadUdfFromClass(final Class<?>... udfClasses) { for (final Class<?> theClass : udfClasses) { loadUdfFromClass( theClass, KsqlScalarFunction.INTERNAL_PATH); } }
@Test public void shouldThrowOnMissingSchemaProvider() throws Exception { // Given: final MutableFunctionRegistry functionRegistry = new InternalFunctionRegistry(); final Path udfJar = new File("src/test/resources/udf-failing-tests.jar").toPath(); try (final UdfClassLoader udfClassLoader = newClassLoa...
@Override public Sensor addLatencyRateTotalSensor(final String scopeName, final String entityName, final String operationName, final Sensor.RecordingLevel recordingLevel, ...
@Test public void testTotalMetricDoesntDecrease() { final MockTime time = new MockTime(1); final MetricConfig config = new MetricConfig().timeWindow(1, TimeUnit.MILLISECONDS); final Metrics metrics = new Metrics(config, time); final StreamsMetricsImpl streamsMetrics = new StreamsMetr...
@Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { // 1.1 参数校验 if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } ...
@Test public void testImportUserList_01() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setEmail(randomEmail()); o.setMobile(randomMobile()); }); // mock 方法,模拟失败 doThrow(new ServiceException(DEPT_NOT_FOUND)).when...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() == 1) { final int batteryLevel = data.getIntValue(Data.FORMAT_UINT8, 0); if (batteryLevel >= 0 && batteryLevel <= 100) { onBatteryLevelChanged(devic...
@Test public void onInvalidDataReceived_dataTooLong() { final DataReceivedCallback callback = new BatteryLevelDataCallback() { @Override public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { assertEquals("Invalid date returned Battery Level", 1, 2); } @Ov...
@Override public boolean serverHealthy() { try { String result = reqApi(UtilAndComs.nacosUrlBase + "/operator/metrics", new HashMap<>(8), HttpMethod.GET); JsonNode json = JacksonUtils.toObj(result); String serverStatus = json.get("status").asText(); return "UP...
@Test void testServerHealthyForException() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenThrow( new RuntimeException("test")); final Field nacosRestTem...
@Override public List<URL> lookup(URL url) { if (url == null) { throw new IllegalArgumentException("lookup url == null"); } try { checkDestroyed(); List<String> providers = new ArrayList<>(); for (String path : toCategoriesPath(url)) { ...
@Test void testLookupWithException() { URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); Assertions.assertThrows(RpcException.class, () -> zookeeperRegistry.lookup(errorUrl)); }
@VisibleForTesting public int getMaxLeavesToBeActivated(int numPendingApps) { float childQueueAbsoluteCapacity = leafQueueTemplateAbsoluteCapacity; if (childQueueAbsoluteCapacity > 0) { int numLeafQueuesNeeded = (int) Math.floor(availableCapacity / childQueueAbsoluteCapacity); return Math.min(numL...
@Test public void testGetMaxLeavesToBeActivated() { DeactivatedLeafQueuesByLabel d1 = spy(DeactivatedLeafQueuesByLabel.class); d1.setAvailableCapacity(0.17f); d1.setLeafQueueTemplateAbsoluteCapacity(0.03f); assertEquals(1, d1.getMaxLeavesToBeActivated(1)); DeactivatedLeafQueuesByLabel d2 = spy(De...
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) { if (xmppServer.isLocal(user)) { try { getUser(user.getNode()); return true; } catch (final UserNotFoundException e) { return false; ...
@Test public void isRegisteredUserTrueWillReturnFalseForUnknownRemoteUsers() { final AtomicReference<IQResultListener> iqListener = new AtomicReference<>(); doAnswer(invocationOnMock -> { final IQResultListener listener = invocationOnMock.getArgument(1); iqListener.set(liste...
void placeOrder(Order order) { sendShippingRequest(order); }
@Test void testPlaceOrderNoExceptionShortQueueDuration() throws Exception { long paymentTime = timeLimits.paymentTime(); long queueTaskTime = timeLimits.queueTaskTime(); long messageTime = timeLimits.messageTime(); long employeeTime = timeLimits.employeeTime(); long queueTime = timeLim...
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execut...
@Test public void shouldFailDropStreamWhenMultipleStreamsAreReadingTheTable() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create stream bar as select * from test1;" + "create stream foo as select * from...
public static String normalize(CharSequence str) { return Normalizer.normalize(str, Normalizer.Form.NFC); }
@Test public void normalizeTest() { // https://blog.csdn.net/oscar999/article/details/105326270 String str1 = "\u00C1"; String str2 = "\u0041\u0301"; assertNotEquals(str1, str2); str1 = CharSequenceUtil.normalize(str1); str2 = CharSequenceUtil.normalize(str2); assertEquals(str1, str2); }
public void evaluate(AuthenticationContext context) { if (context == null) { return; } this.authenticationStrategy.evaluate(context); }
@Test public void evaluate1() { if (MixAll.isMac()) { return; } User user = User.of("test", "test"); this.authenticationMetadataManager.createUser(user); DefaultAuthenticationContext context = new DefaultAuthenticationContext(); context.setRpcCode("11"); ...
@Override public String pluginNamed() { return PluginEnum.HYSTRIX.getName(); }
@Test public void testPluginNamed() { assertEquals(hystrixPluginDataHandler.pluginNamed(), PluginEnum.HYSTRIX.getName()); }