focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Object judgeCustomThrowableForGenericObject(Object appObject) { if (!GENERIC_THROW_EXCEPTION || appObject == null) { return appObject; } if (!(appObject instanceof GenericObject)) { return appObject; } for (String field : THROWABLE_FIELDS) { ...
@Test public void testJudgeCustomThrowable() throws Exception { setGenericThrowException(true); try { Assert.assertNull(judgeCustomThrowableForGenericObject(null)); Object o = new Object(); Assert.assertEquals(o, judgeCustomThrowableForGenericObject(o)); ...
@Override public void handlerPlugin(final PluginData pluginData) { Map<String, String> configMap = GsonUtils.getInstance().toObjectMap(pluginData.getConfig(), String.class); String secretKey = Optional.ofNullable(configMap.get(Constants.SECRET_KEY)).orElse(""); JwtConfig jwtConfig = new JwtC...
@Test public void testHandlerPlugin() { final PluginData pluginData = new PluginData("pluginId", "pluginName", "{\"secretKey\":\"shenyu\"}", "0", false, null); jwtPluginDataHandlerUnderTest.handlerPlugin(pluginData); JwtConfig jwtConfig = Singleton.INST.get(JwtConfig.class); Map<Stri...
@Override public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException { try (InputStream input = provider.open(requireNonNull(path))) { final JsonNode node = mapper.readTree(createParser(input)); if (node == null) { th...
@Test void handleDefaultConfigurationWithoutOverriding() throws Exception { final ExampleWithDefaults example = new YamlConfigurationFactory<>(ExampleWithDefaults.class, validator, Jackson.newObjectMapper(), "dw") .build(); assertThat(example) .sa...
@Override boolean addStorage(DatanodeStorageInfo storage, Block reportedBlock) { Preconditions.checkArgument(BlockIdManager.isStripedBlockID( reportedBlock.getBlockId()), "reportedBlock is not striped"); Preconditions.checkArgument(BlockIdManager.convertToStripedID( reportedBlock.getBlockId())...
@Test(expected=IllegalArgumentException.class) public void testAddStorageWithReplicatedBlock() { DatanodeStorageInfo storage = DFSTestUtil.createDatanodeStorageInfo( "storageID", "127.0.0.1"); BlockInfo replica = new BlockInfoContiguous(new Block(1000L), (short) 3); info.addStorage(storage, replic...
@Override public boolean isIn(String ipAddress) { if (ipAddress == null || addressList == null) { return false; } return addressList.includes(ipAddress); }
@Test public void testFileNotSpecified() { IPList ipl = new FileBasedIPList(null); assertFalse("110.113.221.222 is in the list", ipl.isIn("110.113.221.222")); }
@Override public Object get(int fieldNum) { try { StructField fref = soi.getAllStructFieldRefs().get(fieldNum); return HCatRecordSerDe.serializeField( soi.getStructFieldData(wrappedObject, fref), fref.getFieldObjectInspector()); } catch (SerDeException e) { throw new Illega...
@Test public void testGet() throws Exception { HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector()); Assert.assertEquals(INT_CONST, ((Integer) r.get(0)).intValue()); Assert.assertEquals(LONG_CONST, ((Long) r.get(1)).longValue()); Assert.assertEquals(DOUBLE_CONST, ((Double) r.get(2)...
@Override public void remove(NamedNode master) { connection.sync(RedisCommands.SENTINEL_REMOVE, master.getName()); }
@Test public void testRemove() { Collection<RedisServer> masters = connection.masters(); connection.remove(masters.iterator().next()); }
public Properties getProperties() { return properties; }
@Test(expectedExceptions = SQLException.class) public void assertNonAlphanumericClientTags() throws SQLException { String clientTags = "d1,@d2,d3"; PrestoDriverUri parameters = createDriverUri("presto://localhost:8080?clientTags=" + clientTags); Properties properties = parame...
public FEELFnResult<Range> invoke(@ParameterName("from") String from) { if (from == null || from.isEmpty() || from.isBlank()) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "from", "cannot be null")); } Range.RangeBoundary startBoundary; if...
@Test void invokeInvalidTypes() { String from = "[if(false)..if(true)]"; FunctionTestUtil.assertResultError(rangeFunction.invoke(from), InvalidParametersEvent.class, from); }
private static void flakeIdGenerator(XmlGenerator gen, Map<String, ClientFlakeIdGeneratorConfig> flakeIdGenerators) { for (Map.Entry<String, ClientFlakeIdGeneratorConfig> entry : flakeIdGenerators.entrySet()) { ClientFlakeIdGeneratorConfig flakeIdGenerator = entry.getValue(); gen.open("f...
@Test public void flakeIdGenerator() { ClientFlakeIdGeneratorConfig expected = new ClientFlakeIdGeneratorConfig(randomString()); expected.setPrefetchCount(randomInt()) .setPrefetchValidityMillis(randomInt()); clientConfig.addFlakeIdGeneratorConfig(expected); Map<Stri...
public OSMReader setElevationProvider(ElevationProvider eleProvider) { if (eleProvider == null) throw new IllegalStateException("Use the NOOP elevation provider instead of null or don't call setElevationProvider"); if (!nodeAccess.is3D() && ElevationProvider.NOOP != eleProvider) ...
@Test public void testReadEleFromDataProvider() { GraphHopper hopper = new GraphHopperFacade("test-osm5.xml"); // get N10E046.hgt.zip ElevationProvider provider = new SRTMProvider(GraphHopperTest.DIR); hopper.setElevationProvider(provider); hopper.importOrLoad(); Gra...
@VisibleForTesting AuthRequest buildAuthRequest(Integer socialType, Integer userType) { // 1. 先查找默认的配置项,从 application-*.yaml 中读取 AuthRequest request = authRequestFactory.get(SocialTypeEnum.valueOfType(socialType).getSource()); Assert.notNull(request, String.format("社交平台(%d) 不存在", socialType)...
@Test public void testBuildAuthRequest_clientEnable() { // 准备参数 Integer socialType = SocialTypeEnum.WECHAT_MP.getType(); Integer userType = randomPojo(SocialTypeEnum.class).getType(); // mock 获得对应的 AuthRequest 实现 AuthConfig authConfig = mock(AuthConfig.class); AuthReq...
public static boolean containsPath(DataSchema schema, String path) { return getField(schema, path) != null; }
@Test(dataProvider = "pathData") public void testContainsPath(String path, boolean expected) throws IOException { DataSchema validationDemoSchema = pdscToDataSchema(DATA_SCHEMA_PATH); Assert.assertEquals(DataSchemaUtil.containsPath(validationDemoSchema, path), expected); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { if (!joinKey.isForeignKey()) { ensureMatchingPartitionCounts(buildContext.getServiceContext().getTopicClient()); } final JoinerFactory joinerFactory = new JoinerFactory( buildContext, this, ...
@Test public void shouldPerformStreamToTableLeftJoin() { // Given: setupStream(left, leftSchemaKStream); setupTable(right, rightSchemaKTable); final JoinNode joinNode = new JoinNode(nodeId, LEFT, joinKey, true, left, right, empty(), "KAFKA"); // When: joinNode.buildStream(planB...
private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); final int size = dataSet.size(); out.writeInt(size); if (size > 0) { DataOutputViewStreamWrapper wrapper = new DataOutputViewStreamWrapper(out); for (T element : data...
@Test void testSerializationFailure() { try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(buffer)) { // a mock serializer that fails when writing CollectionInputFormat<ElementType> inFormat = ...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final String prefix = containerService.isContainer(directory) ? StringUtils.EMPTY : containerService.getKey(directory) + Path.DELIMITER; return this.list(directory, list...
@Test public void testListPlaceholder() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); container.attributes().setRegion("IAD"); final Path placeholder = new SwiftDirectoryFeature(session).mkdir(new Path(container, n...
@Override public void apply(IntentOperationContext<FlowRuleIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); if (toInstall.isPresent() && toUninstall.isPresent()) { Intent intentToInstall = toInstal...
@Test public void testRuleModify() { List<Intent> intentsToInstall = createFlowRuleIntents(); List<Intent> intentsToUninstall = createFlowRuleIntentsWithSameMatch(); IntentData toInstall = new IntentData(createP2PIntent(), IntentState.INSTALLING...
public static Comparable canonicalizeForHashLookup(Comparable value) { if (value instanceof Number) { return Numbers.canonicalizeForHashLookup(value); } return value; }
@Test public void testCanonicalization() { assertSame("foo", canonicalizeForHashLookup("foo")); assertSame(null, canonicalizeForHashLookup(null)); assertEquals(1234L, ((Number) canonicalizeForHashLookup(1234)).longValue()); }
public List<IssueDto> sort() { String sort = query.sort(); Boolean asc = query.asc(); if (sort != null && asc != null) { return getIssueProcessor(sort).sort(issues, asc); } return issues; }
@Test public void should_not_sort_with_null_sort() { IssueDto issue1 = new IssueDto().setKee("A").setAssigneeUuid("perceval"); IssueDto issue2 = new IssueDto().setKee("B").setAssigneeUuid("arthur"); IssueDto issue3 = new IssueDto().setKee("C").setAssigneeUuid("vincent"); IssueDto issue4 = new IssueDto...
@Override public InterpreterResult interpret(String code, InterpreterContext context) { // choosing new name to class containing Main method String generatedClassName = "C" + UUID.randomUUID().toString().replace("-", ""); try { String res = StaticRepl.execute(generatedClassName, code); retur...
@Test void testStaticReplWithoutMain() { StringBuffer sourceCode = new StringBuffer(); sourceCode.append("package org.mdkt;\n"); sourceCode.append("public class HelloClass {\n"); sourceCode.append(" public String hello() { return \"hello\"; }"); sourceCode.append("}"); InterpreterResult res...
public synchronized boolean tryWriteLock() { if (!isFree()) { return false; } else { status = FREE_STATUS; return true; } }
@Test public void multiTryWriteLockTest() { SimpleReadWriteLock simpleReadWriteLock = new SimpleReadWriteLock(); simpleReadWriteLock.tryWriteLock(); boolean result = simpleReadWriteLock.tryWriteLock(); Assert.isTrue(!result); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { final PathContainerService service = new DefaultPathContainerService(); if(service.isContainer(file)) { for(RootFolder r : session.roots()) { ...
@Test public void testChangedNodeId() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random())...
public static Object parse(JsonParser parser) throws IOException { var token = parser.currentToken(); if (token == JsonToken.VALUE_NULL) { return null; } if (token.isScalarValue()) { if (token == JsonToken.VALUE_TRUE) { return true; } ...
@Test void readNestedMap() throws IOException { //language=json var json = """ { "template": { "data": { "url": "https://tinkoff.ru", "number": 1 } } } """; tr...
public String getStageName() { if(isBuilding()) { try { return buildLocator.split("/")[2]; } catch (ArrayIndexOutOfBoundsException e) { return null; } } return null; }
@Test public void shouldReturnNullForStageName() { AgentBuildingInfo agentBuildingInfo = new AgentBuildingInfo("buildInfo", "foo"); assertNull(agentBuildingInfo.getStageName()); }
@Override public boolean remove(Object o) { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void test_remove() { set.remove(1); }
public static int random(double[] prob) { int[] ans = random(prob, 1); return ans[0]; }
@Test public void testRandom() { System.out.println("random"); double[] prob = {0.473646292, 0.206116725, 0.009308497, 0.227844687, 0.083083799}; int[] sample = MathEx.random(prob, 300); double[][] hist = Histogram.of(sample, 5); double[] p = new double[5]; for (int i...
@Override public void populateContainer(MigrationContainer container) { container.add(executorType); populateFromMigrationSteps(container); }
@Test public void populateContainer_adds_classes_of_all_steps_defined_in_MigrationSteps() { when(migrationSteps.readAll()).thenReturn(asList( new RegisteredMigrationStep(1, "foo", MigrationStep1.class), new RegisteredMigrationStep(2, "bar", MigrationStep2.class), new RegisteredMigrationStep(3, "...
public List<ParsedTerm> filterElementsContainingUsefulInformation(final Map<String, List<ParsedTerm>> parsedTermsGroupedByField) { return parsedTermsGroupedByField.values() .stream() .map(this::filterElementsContainingUsefulInformation) .flatMap(Collection::stream...
@Test void doesNotLimitOnSingleElement() { final Map<String, List<ParsedTerm>> fieldTerms = Map.of("field", List.of( ParsedTerm.create("field", "oh!") )); assertThat(toTest.filterElementsContainingUsefulInformation(fieldTerms)) .hasSize(1) .con...
public Matrix.QR qr() { return qr(false); }
@Test public void testQR() { System.out.println("QR"); float[][] A = { {0.9000f, 0.4000f, 0.7000f}, {0.4000f, 0.5000f, 0.3000f}, {0.7000f, 0.3000f, 0.8000f} }; float[] b = {0.5f, 0.5f, 0.5f}; float[] x = {-0.2027027f, 0.8783784...
public static Optional<Object[]> coerceParams(Class<?> currentIdxActualParameterType, Class<?> expectedParameterType, Object[] actualParams, int i) { Object actualObject = actualParams[i]; Optional<Object> coercedObject = coerceParam(currentIdxActualParameterType, expectedParameterType, ...
@Test void coerceParamsToDateTimeConverted() { Object value = LocalDate.now(); Object[] actualParams = {value, "NOT_DATE"}; Optional<Object[]> retrieved = CoerceUtil.coerceParams(LocalDate.class, ZonedDateTime.class, actualParams, 0); assertNotNull(retrieved); assertTrue(retr...
@Override public void registerInstance(String namespaceId, String serviceName, Instance instance) throws NacosException { NamingUtils.checkInstanceIsLegal(instance); boolean ephemeral = instance.isEphemeral(); String clientId = IpPortBasedClient.getClientId(instance.toInetAddr(), ep...
@Test void testRegisterInstance() throws NacosException { instanceOperatorClient.registerInstance("A", "B", new Instance()); Mockito.verify(clientOperationService).registerInstance(Mockito.any(), Mockito.any(), Mockito.anyString()); }
public int getMaxIdle() { return maxIdle; }
@Test public void maxIdleDefaultValueTest() { assertEquals(DEFAULT_MAX_IDLE, redisConfigProperties.getMaxIdle()); }
UuidGenerator loadUuidGenerator() { Class<? extends UuidGenerator> objectFactoryClass = options.getUuidGeneratorClass(); ClassLoader classLoader = classLoaderSupplier.get(); ServiceLoader<UuidGenerator> loader = ServiceLoader.load(UuidGenerator.class, classLoader); if (objectFactoryClass...
@Test void test_case_8() { Options options = () -> IncrementingUuidGenerator.class; UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader( () -> new ServiceLoaderTestClassLoader(UuidGenerator.class, RandomUuidGenerator.class, IncrementingUuidG...
@Override public Encoder getMapValueEncoder() { return encoder; }
@Test public void shouldSerializeTheMapCorrectly() throws Exception { assertThat(mapCodec.getMapValueEncoder().encode(map).toString(CharsetUtil.UTF_8)) .isEqualTo("{\"foo\":[\"bar\"]}"); }
@Override @NotNull public List<PartitionStatistics> select(Collection<PartitionStatistics> statistics, Set<Long> excludeTables) { long now = System.currentTimeMillis(); return statistics.stream() .filter(p -> p.getNextCompactionTime() <= now) .filter(p -> !exclude...
@Test public void testCompactionTimeNotReached() { List<PartitionStatistics> statisticsList = new ArrayList<>(); final PartitionIdentifier partitionIdentifier = new PartitionIdentifier(1, 2, 4); PartitionStatistics statistics = new PartitionStatistics(partitionIdentifier); statistic...
@ScalarFunction public static String[] uniqueNgrams(String input, int length) { if (length == 0 || length > input.length()) { return new String[0]; } ObjectSet<String> ngramSet = new ObjectLinkedOpenHashSet<>(); for (int i = 0; i < input.length() - length + 1; i++) { ngramSet.add(input.sub...
@Test(dataProvider = "ngramTestCases") public void testNGram(String input, int minGram, int maxGram, String[] expectedExactNGram, String[] expectedNGram) { assertEquals(StringFunctions.uniqueNgrams(input, maxGram), expectedExactNGram); assertEquals(StringFunctions.uniqueNgrams(input, minGram, maxGram), expect...
@Udf(description = "Converts a string representation of a date in the given format" + " into the number of days since 1970-01-01 00:00:00 UTC/GMT.") public int stringToDate( @UdfParameter( description = "The string representation of a date.") final String formattedDate, @UdfParameter( ...
@Test public void shouldThrowIfFormatInvalid() { // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> udf.stringToDate("2021-12-01", "invalid") ); // Then: assertThat(e.getMessage(), containsString("Failed to parse date '2021-12-01' with formatter 'invalid...
@Override public List<String> listPartitionNames(String dbName, String tblName, TableVersionRange version) { return hmsOps.getPartitionKeys(dbName, tblName); }
@Test public void testGetPartitionKeys() { Assert.assertEquals( Lists.newArrayList("col1"), hudiMetadata.listPartitionNames("db1", "tbl1", TableVersionRange.empty())); }
public void validate(ExternalIssueReport report, Path reportPath) { if (report.rules != null && report.issues != null) { Set<String> ruleIds = validateRules(report.rules, reportPath); validateIssuesCctFormat(report.issues, ruleIds, reportPath); } else if (report.rules == null && report.issues != nul...
@Test public void validate_whenMissingEngineIdField_shouldThrowException() throws IOException { ExternalIssueReport report = read(REPORTS_LOCATION); report.rules[0].engineId = null; assertThatThrownBy(() -> validator.validate(report, reportPath)) .isInstanceOf(IllegalStateException.class) .ha...
public ImmutableSet<EntityDescriptor> resolve(GRN entity) { // TODO: Replace entity excerpt usage with GRNDescriptors once we implemented GRN descriptors for every entity final ImmutableMap<GRN, Optional<String>> entityExcerpts = contentPackService.listAllEntityExcerpts().stream() // TOD...
@Test @DisplayName("Try a stream reference dependency resolve") void resolveStreamReference() { final String TEST_TITLE = "Test Stream Title"; final EntityExcerpt streamExcerpt = EntityExcerpt.builder() .type(ModelTypes.STREAM_V1) .id(ModelId.of("54e3deadbeefdeadb...
public static File openFile(String path, String fileName) { return openFile(path, fileName, false); }
@Test void openFile() { File file = DiskUtils.openFile(testFile.getParent(), testFile.getName()); assertNotNull(file); assertEquals(testFile.getPath(), file.getPath()); assertEquals(testFile.getName(), file.getName()); }
@Override public Optional<SimpleLock> lock(LockConfiguration lockConfiguration) { boolean lockObtained = doLock(lockConfiguration); if (lockObtained) { return Optional.of(new StorageLock(lockConfiguration, storageAccessor)); } else { return Optional.empty(); }...
@Test void shouldNotCacheRecordIfUpdateFailed() { when(storageAccessor.insertRecord(LOCK_CONFIGURATION)).thenReturn(false); when(storageAccessor.updateRecord(LOCK_CONFIGURATION)).thenThrow(LOCK_EXCEPTION); assertThatThrownBy(() -> lockProvider.lock(LOCK_CONFIGURATION)).isSameAs(LOCK_EXCEPTIO...
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) { if (targetClass != null && targetClass != method.getDeclaringClass() && isOverridable(method, targetClass)) { try { if (Modifier.isPublic(method.getModifiers())) { try { ...
@Test public void testGetMostSpecificMethodWhenClassIsNull() throws NoSuchMethodException { Method method = AbstractMap.class.getDeclaredMethod("clone"); Method specificMethod = ClassUtils.getMostSpecificMethod(method, null); assertEquals(AbstractMap.class, specificMethod.getDeclaringClass()...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VectorClock that = (VectorClock) o; return replicaTimestamps.equals(that.replicaTimestamps); }
@Test public void testEquals() { final VectorClock clock = vectorClock(uuidParams[0], 1, uuidParams[1], 2); assertEquals(clock, vectorClock(uuidParams[0], 1, uuidParams[1], 2)); assertEquals(clock, new VectorClock(clock)); }
@Override public String getProcedureTerm() { return null; }
@Test void assertGetProcedureTerm() { assertNull(metaData.getProcedureTerm()); }
@Override public void start(EdgeExplorer explorer, int startNode) { IntArrayDeque stack = new IntArrayDeque(); GHBitSet explored = createBitSet(); stack.addLast(startNode); int current; while (stack.size() > 0) { current = stack.removeLast(); if (!exp...
@Test public void testDFS1() { DepthFirstSearch dfs = new DepthFirstSearch() { @Override protected GHBitSet createBitSet() { return new GHBitSetImpl(); } @Override public boolean goFurther(int v) { counter++; ...
@Override public void execute(Runnable command) { if (command == null) { throw new NullPointerException(); } try { super.execute(command); } catch (RejectedExecutionException rx) { // retry to offer the task into queue. final TaskQueue...
@Disabled("replaced to testEagerThreadPoolFast for performance") @Test void testEagerThreadPool() throws Exception { String name = "eager-tf"; int queues = 5; int cores = 5; int threads = 10; // alive 1 second long alive = 1000; // init queue and executor...
public static Ip6Prefix valueOf(byte[] address, int prefixLength) { return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength); }
@Test public void testValueOfAddressIPv6() { Ip6Address ipAddress; Ip6Prefix ipPrefix; ipAddress = Ip6Address.valueOf("1111:2222:3333:4444:5555:6666:7777:8888"); ipPrefix = Ip6Prefix.valueOf(ipAddress, 120); assertThat(ipPrefix.toString(), is("...
public static Optional<ServiceInstance> getStorageNodeAtHost(ApplicationInstance application, HostName hostName) { Set<ServiceInstance> storageNodesOnHost = application.serviceClusters().stream() .filter(VespaModelUtil::isS...
@Test public void testGetStorageNodeAtHost() { Optional<ServiceInstance> service = VespaModelUtil.getStorageNodeAtHost(application, storage0Host); assertTrue(service.isPresent()); assertEquals(storage0, service.get()); }
public static DateTimeFormatter createDateTimeFormatter(String format, Mode mode) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); boolean formatContainsHourOfAMPM = false; for (Token token : tokenize(format)) { switch (token.getType()) { case ...
@Test(expectedExceptions = PrestoException.class) public void testParserInvalidTokenCreate2() { DateFormatParser.createDateTimeFormatter("yyym/mm/dd", PARSER); }
public ConfigurationProperty create(String key, String value, String encryptedValue, Boolean isSecure) { ConfigurationProperty configurationProperty = new ConfigurationProperty(); configurationProperty.setConfigurationKey(new ConfigurationKey(key)); if (isNotBlank(value) && isNotBlank(encrypte...
@Test public void shouldCreateWithErrorsIfBothPlainAndEncryptedTextInputAreSpecifiedForUnSecuredProperty() { Property key = new Property("key"); key.with(Property.SECURE, false); ConfigurationProperty property = new ConfigurationPropertyBuilder().create("key", "value", "enc_value", false); ...
@Override public Ring<T> createRing(Map<T, Integer> pointsMap) { return _ringFactory.createRing(pointsMap); }
@Test(groups = { "small", "back-end" }) public void testFactoryWithMultiProbe() { RingFactory<String> factory = new DelegatingRingFactory<>(configBuilder("multiProbe", null)); Ring<String> ring = factory.createRing(buildPointsMap(10)); assertTrue(ring instanceof MPConsistentHashRing); }
public static List<String> splitPlainTextParagraphs( List<String> lines, int maxTokensPerParagraph) { return internalSplitTextParagraphs( lines, maxTokensPerParagraph, (text) -> internalSplitLines( text, maxTokensPerParagraph, false, s_plaintextSplitOp...
@Test public void canSplitTextParagraphsOnClosingBrackets() { List<String> input = Arrays.asList( "This is a test of the emergency broadcast system) This is only a test", "We repeat) this is only a test) A unit test", "A small note] And another) And once again] Seriously ...
@Override public void unbindSocialUser(Long userId, Integer userType, Integer socialType, String openid) { // 获得 openid 对应的 SocialUserDO 社交用户 SocialUserDO socialUser = socialUserMapper.selectByTypeAndOpenid(socialType, openid); if (socialUser == null) { throw exception(SOCIAL_USE...
@Test public void testUnbindSocialUser_notFound() { // 调用,并断言 assertServiceException( () -> socialUserService.unbindSocialUser(randomLong(), UserTypeEnum.ADMIN.getValue(), SocialTypeEnum.GITEE.getType(), "test_openid"), SOCIAL_USER_NOT_FOUND); ...
@Override public synchronized Request poll(Task task) { Request poll = priorityQueuePlus.poll(); if (poll != null) { return poll; } poll = noPriorityQueue.poll(); if (poll != null) { return poll; } return priorityQueueMinus.poll(); ...
@Test public void testDifferentPriority() { Request request = new Request("a"); request.setPriority(100); priorityScheduler.push(request,task); request = new Request("b"); request.setPriority(900); priorityScheduler.push(request,task); request = new Request(...
private Main() { // Utility Class. }
@Test public void downloadsDependenciesForGithub() throws Exception { final File pwd = temp.newFolder(); Main.main(String.format("--workdir=%s", pwd.getAbsolutePath())); final Path logstash = pwd.toPath().resolve("logstash").resolve("logstash-main"); assertThat(logstash.toFile().exis...
public void fsck() { final long startTime = Time.monotonicNow(); try { String warnMsg = "Now FSCK to DFSRouter is unstable feature. " + "There may be incompatible changes between releases."; LOG.warn(warnMsg); out.println(warnMsg); String msg = "Federated FSCK started by " + ...
@Test public void testFsck() throws Exception { MountTable addEntry = MountTable.newInstance("/testdir", Collections.singletonMap("ns0", "/testdir")); assertTrue(addMountTable(addEntry)); addEntry = MountTable.newInstance("/testdir2", Collections.singletonMap("ns1", "/testdir2")); asse...
@Override public int getOrder() { return PluginEnum.RESPONSE.getCode(); }
@Test public void testGetOrder() { assertEquals(responsePlugin.getOrder(), PluginEnum.RESPONSE.getCode()); }
@Override public void close() { close(Duration.ofMillis(DEFAULT_CLOSE_TIMEOUT_MS)); }
@Test public void testSuccessfulStartupShutdown() { consumer = newConsumer(); completeShareAcknowledgeOnCloseApplicationEventSuccessfully(); completeShareUnsubscribeApplicationEventSuccessfully(); assertDoesNotThrow(() -> consumer.close()); }
@Override public boolean offerLast(T t) { addLastNode(t); return true; }
@Test public void testOfferLastNull() { LinkedDeque<Object> q = new LinkedDeque<>(); try { q.offerLast(null); Assert.fail("offerLast null should have failed"); } catch (NullPointerException e) { // expected } }
public Map<String, Gauge<Long>> gauges() { Map<String, Gauge<Long>> gauges = new HashMap<>(); final TrafficCounter tc = trafficCounter(); gauges.put(READ_BYTES_1_SEC, new Gauge<Long>() { @Override public Long getValue() { return tc.lastReadBytes(); ...
@Test public void counterReturns4Gauges() { assertThat(throughputCounter.gauges()).hasSize(4); }
@Override public void updateNotice(NoticeSaveReqVO updateReqVO) { // 校验是否存在 validateNoticeExists(updateReqVO.getId()); // 更新通知公告 NoticeDO updateObj = BeanUtils.toBean(updateReqVO, NoticeDO.class); noticeMapper.updateById(updateObj); }
@Test public void testUpdateNotice_success() { // 插入前置数据 NoticeDO dbNoticeDO = randomPojo(NoticeDO.class); noticeMapper.insert(dbNoticeDO); // 准备更新参数 NoticeSaveReqVO reqVO = randomPojo(NoticeSaveReqVO.class, o -> o.setId(dbNoticeDO.getId())); // 更新 noticeSer...
public double maxQueryGrowthRate(Duration window, Instant now) { if (snapshots.isEmpty()) return 0.1; // Find the period having the highest growth rate, where total growth exceeds 30% increase double maxGrowthRate = 0; // In query rate growth per second (to get good resolution) for (int...
@Test public void test_real_data() { // Here we use real data from a production deployment, where significant query rate growth is measured over // a short period (ts0). This should not cause a significant difference in max growth rate compared to a node // measuring approximately the same g...
@Override public Optional<PersistentQueryMetadata> getPersistentQuery(final QueryId queryId) { return Optional.ofNullable(persistentQueries.get(queryId)); }
@Test public void shouldCallListenerOnStateChange() { // Given: final QueryMetadata.Listener queryListener = givenCreateGetListener(registry, "foo"); final QueryMetadata query = registry.getPersistentQuery(new QueryId("foo")).get(); // When: queryListener.onStateChange(query, State.CREATED, State...
@Override public LinkEvent createOrUpdateLink(ProviderId providerId, LinkDescription linkDescription) { final DeviceId dstDeviceId = linkDescription.dst().deviceId(); final NodeId dstNodeId = mastershipService.getMasterFor(dstDeviceId); // Process lin...
@Test public final void testCreateOrUpdateLinkAncillary() { ConnectPoint src = new ConnectPoint(DID1, P1); ConnectPoint dst = new ConnectPoint(DID2, P2); // add Ancillary link LinkEvent event = linkStore.createOrUpdateLink(PIDA, new DefaultLinkDescription(src, ds...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void withNoClosingBraces() throws ScanException { Tokenizer tokenizer = new Tokenizer("a${b"); Parser parser = new Parser(tokenizer.tokenize()); try { parser.parse(); } catch (IllegalArgumentException e) { assertEquals("All tokens consumed but was...
@Override public Result apply(String action, Class<? extends Validatable> aClass, String resource, String resourceToOperateWithin) { if (matchesAction(action) && matchesType(aClass) && matchesResource(resource)) { return Result.DENY; } if (isRequestForElasticAgentProfiles(aClass...
@Test void forAdministerOfAllClusterProfiles() { Deny directive = new Deny("administer", "cluster_profile", "*"); Result viewAllElasticAgentProfiles = directive.apply("view", ElasticProfile.class, "*", null); Result viewAllClusterProfiles = directive.apply("view", ClusterProfile.class, "*",...
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testMapPutIfAbsentNoReadFails() throws Exception { StateTag<MapState<String, Integer>> addr = StateTags.map("map", StringUtf8Coder.of(), VarIntCoder.of()); MapState<String, Integer> mapState = underTest.state(NAMESPACE, addr); final String tag1 = "tag1"; mapState.put(tag1, 1...
@Override public Collection<String> childNames() { return Arrays.asList(ClusterImageBrokersNode.NAME, ClusterImageControllersNode.NAME); }
@Test public void testChildNames() { assertEquals(Arrays.asList("brokers", "controllers"), NODE.childNames()); }
public FEELFnResult<String> invoke(@ParameterName("from") Object val) { if ( val == null ) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( TypeUtil.formatValue(val, false) ); } }
@Test void invokeDurationNanosMillis() { FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofNanos(25)), "PT0.000000025S"); FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofNanos(10000)), "PT0.00001S"); FunctionTestUtil.assertResult(stringFunction.invoke(Duration.ofN...
public static VersionRange parse(String rangeString) { validateRangeString(rangeString); Inclusiveness minVersionInclusiveness = rangeString.startsWith("[") ? Inclusiveness.INCLUSIVE : Inclusiveness.EXCLUSIVE; Inclusiveness maxVersionInclusiveness = rangeString.endsWith("]") ? Inclusiveness...
@Test public void parse_withTheSameRangeEnds_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> VersionRange.parse("[1.0,1.0]")); assertThat(exception) .hasMessageThat() .isEqualTo("Min version in range must be les...
public static String toJson(MetadataUpdate metadataUpdate) { return toJson(metadataUpdate, false); }
@Test public void testSetLocationToJson() { String action = MetadataUpdateParser.SET_LOCATION; String location = "s3://bucket/warehouse/tbl_location"; String expected = String.format("{\"action\":\"%s\",\"location\":\"%s\"}", action, location); MetadataUpdate update = new MetadataUpdate.SetLocation(lo...
@Override public DescribeConfigsResult describeConfigs(Collection<ConfigResource> configResources, final DescribeConfigsOptions options) { // Partition the requested config resources based on which broker they must be sent to with the // null broker being used for config resources which can be obtai...
@Test public void testDescribeConfigsPartialResponse() { ConfigResource topic = new ConfigResource(ConfigResource.Type.TOPIC, "topic"); ConfigResource topic2 = new ConfigResource(ConfigResource.Type.TOPIC, "topic2"); try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaC...
@Override public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() { return new UnbindChangeProcessor(); }
@Test public void leftJoinShouldPropagateChangeFromNullFKToNonNullFKValue() { final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>(); leftJoinProcessor.init(context); context.setRecordMetadata("topic", 0, 0); fina...
public Map<String, String> build() { Map<String, String> builder = new HashMap<>(); configureFileSystem(builder); configureNetwork(builder); configureCluster(builder); configureSecurity(builder); configureOthers(builder); LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]", ...
@Test public void set_discovery_settings_if_cluster_is_enabled() throws Exception { Props props = minProps(CLUSTER_ENABLED); props.set(CLUSTER_ES_HOSTS.getKey(), "1.2.3.4:9000,1.2.3.5:8080"); Map<String, String> settings = new EsSettings(props, new EsInstallation(props), system).build(); assertThat(s...
@Operation(summary = "remove the connection") @DeleteMapping(value = "{id}") public void remove(@PathVariable("id") Long id) { Connection connection = connectionService.getConnectionById(id); connectionService.deleteConnectionById(connection); }
@Test public void removeConnection() { when(connectionServiceMock.getConnectionById(anyLong())).thenReturn(getNewConnection()); controllerMock.remove(1L); verify(connectionServiceMock, times(1)).deleteConnectionById(any(Connection.class)); verify(connectionServiceMock, times(1)).ge...
static Boolean andOperator(Boolean aBoolean, Boolean aBoolean2) { logger.trace("andOperator {} {}", aBoolean, aBoolean2); return aBoolean != null ? aBoolean && aBoolean2 : aBoolean2; }
@Test void andOperator() { Boolean aBoolean = null; boolean aBoolean2 = true; assertThat(KiePMMLCompoundPredicate.andOperator(aBoolean, aBoolean2)).isTrue(); aBoolean2 = false; assertThat(KiePMMLCompoundPredicate.andOperator(aBoolean, aBoolean2)).isFalse(); aBoolean...
public boolean isEnabled() { return enabled; }
@Test public void test_constructor_enabledDefaultBehavior() { ClientTpcConfig config = new ClientTpcConfig(); assertFalse(config.isEnabled()); System.setProperty("hazelcast.client.tpc.enabled", "true"); config = new ClientTpcConfig(); assertTrue(config.isEnabled()); ...
abstract List<String> parseJobID() throws IOException;
@Test public void testParseJar() throws IOException { String errFileName = "src/test/data/status/jar"; JarJobIDParser jarJobIDParser = new JarJobIDParser(errFileName, new Configuration()); List<String> jobs = jarJobIDParser.parseJobID(); Assert.assertEquals(jobs.size(), 1); }
@ScalarOperator(CAST) @SqlType(StandardTypes.INTEGER) public static long castToInteger(@SqlType(StandardTypes.REAL) long value) { try { return DoubleMath.roundToInt(intBitsToFloat((int) value), HALF_UP); } catch (ArithmeticException e) { throw new PrestoExcept...
@Test public void testCastToInteger() { assertFunction("CAST(REAL'754.2008' AS INTEGER)", INTEGER, 754); assertFunction("CAST(REAL'-754.1985' AS INTEGER)", INTEGER, -754); assertFunction("CAST(REAL'9.99' AS INTEGER)", INTEGER, 10); assertFunction("CAST(REAL'-0.0' AS INTEGER)", IN...
@POST @Path("/{connector}/tasks/{task}/restart") @Operation(summary = "Restart the specified task for the specified connector") public void restartTask(final @PathParam("connector") String connector, final @PathParam("task") Integer task, final @Contex...
@Test public void testRestartTaskLeaderRedirect() throws Throwable { ConnectorTaskId taskId = new ConnectorTaskId(CONNECTOR_NAME, 0); final ArgumentCaptor<Callback<Void>> cb = ArgumentCaptor.forClass(Callback.class); expectAndCallbackNotLeaderException(cb).when(herder) .restartT...
public FEELFnResult<BigDecimal> invoke(@ParameterName("from") String from, @ParameterName("grouping separator") String group, @ParameterName("decimal separator") String decimal) { if ( from == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "from", "cannot be null"));...
@Test void invokeNumberWithGroupCharDot() { FunctionTestUtil.assertResult(numberFunction.invoke("9.876", ".", null), BigDecimal.valueOf(9876)); FunctionTestUtil.assertResult(numberFunction.invoke("9.876.000", ".", null), BigDecimal.valueOf(9876000)); }
@Override public double quantile(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } int n = (int) Math.max(Math.sqrt(1 / this.p), 5.0); int nl, nu, inc = 1; if (p < cdf(n)) { do { n = Math.m...
@Test public void testQuantile() { System.out.println("quantile"); ShiftedGeometricDistribution instance = new ShiftedGeometricDistribution(0.3); instance.rand(); assertEquals(1, instance.quantile(0.01), 1E-6); assertEquals(1, instance.quantile(0.1), 1E-6); assertEqua...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { if(containerService.isContainer(folder)) { final Storage.Buckets.Insert request = session.getClient().buckets().insert(session.getHost().getCredentials().getUsername(), ...
@Test public void testCreatePlaceholderVersioningDeleteWithMarker() throws Exception { final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new GoogleStorageDirectoryFeature(session).mkdir(new Path(bucket, new AlphanumericRandomStrin...
public LazyMapEntry init(InternalSerializationService serializationService, Object key, Object value, Extractors extractors, long ttl, boolean changeExpiryOnUpdate) { super.init(serializationService, key, value, extractors); this.modified = false...
@Test public void test_init() { Data keyData = serializationService.toData("keyData"); Data valueData = serializationService.toData("valueData"); entry.init(serializationService, keyData, valueData, null); Object valueObject = entry.getValue(); entry.init(serializationServi...
@Override protected File getFile(HandlerRequest<EmptyRequestBody> handlerRequest) { if (logDir == null) { return null; } // wrapping around another File instantiation is a simple way to remove any path information // - we're // solely interested in the filename ...
@Test void testGetJobManagerCustomLogsNotExistingFile() throws Exception { File actualFile = testInstance.getFile(createHandlerRequest("not-existing")); assertThat(actualFile).isNotNull().doesNotExist(); }
@Override public void store(Measure newMeasure) { saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure); }
@Test public void shouldIgnoreMeasuresOnModules() throws IOException { ProjectDefinition module = ProjectDefinition.create().setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()); ProjectDefinition root = ProjectDefinition.create().addSubProject(module); underTest.store(new DefaultMeasure() .on...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay way, IntsRef relationFlags) { String value = way.getTag("hgv:conditional", ""); int index = value.indexOf("@"); Hgv hgvValue = index > 0 && conditionalWeightToTons(value) == 3.5 ? Hgv.find(value.substring(...
@Test public void testSimpleTags() { EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); ReaderWay readerWay = new ReaderWay(1); readerWay.setTag("highway", "primary"); readerWay.setTag("hgv", "destination"); parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlag...
@Override public Map<TopicPartition, Long> beginningOffsets(Collection<TopicPartition> partitions) { return beginningOffsets(partitions, Duration.ofMillis(defaultApiTimeoutMs)); }
@Test public void testBeginningOffsetsTimeoutException() { consumer = newConsumer(); long timeout = 100; doThrow(new TimeoutException("Event did not complete in time and was expired by the reaper")) .when(applicationEventHandler).addAndGet(any()); Throwable t = assertThr...
public Input<DefaultIssue> create(Component component) { return new RawLazyInput(component); }
@Test void create_whenSeverityAndTypeNotProvided_shouldTakeFromTheRule() { registerRule(RuleKey.of("external_eslint", "S001"), "rule", r -> { r.setType(RuleType.BUG); r.setSeverity(Severity.MAJOR); }); ScannerReport.ExternalIssue reportIssue = createIssue(null, null); reportReader.putExter...
@Override public boolean add(double score, V object) { return get(addAsync(score, object)); }
@Test public void testSort() { RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple"); Assertions.assertTrue(set.add(4, 2)); Assertions.assertTrue(set.add(5, 3)); Assertions.assertTrue(set.add(3, 1)); Assertions.assertTrue(set.add(6, 4)); Assertions.ass...
public ReportEntry createEntry( final long initialBytesLost, final long timestampMs, final int sessionId, final int streamId, final String channel, final String source) { ReportEntry reportEntry = null; final int requiredCapacity = CHANNEL...
@Test void shouldCreateEntry() { final long initialBytesLost = 32; final int timestampMs = 7; final int sessionId = 3; final int streamId = 1; final String channel = "aeron:udp://stuff"; final String source = "127.0.0.1:8888"; assertNotNull(lossReport.cre...
@Override public String getRequestURL() { val url = request.getRequestURL().toString(); var idx = url.indexOf('?'); if (idx != -1) { return url.substring(0, idx); } return url; }
@Test public void testGetRequestUrl() throws Exception { when(request.getRequestURL()).thenReturn(new StringBuffer("https://pac4j.org?name=value&name2=value2")); WebContext context = new JEEContext(request, response); assertEquals("https://pac4j.org", context.getRequestURL()); }
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testAllowedTypeCastingIntoBoolean() throws JsonProcessingException { Map<String, ParamDefinition> allParams = ParamsMergeHelperTest.this.parseParamDefMap( "{'tomerge': {'type': 'BOOLEAN','value': false, 'name': 'tomerge'}}"); Map<String, ParamDefinition> paramsToMerge = ...
@ConstantFunction(name = "bitShiftRight", argTypes = {INT, BIGINT}, returnType = INT) public static ConstantOperator bitShiftRightInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createInt(first.getInt() >> second.getBigint()); }
@Test public void bitShiftRightInt() { assertEquals(1, ScalarOperatorFunctions.bitShiftRightInt(O_INT_10, O_BI_3).getInt()); }
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception { return newGetter(object, parent, modifier, method.getReturnType(), method::invoke, (t, et) -> new MethodGetter(parent, method, modifier, t, et)); }
@Test public void newMethodGetter_whenExtractingFromNonEmpty_Collection_AndReducerSuffixInNotEmpty_thenInferTypeFromCollectionItem() throws Exception { OuterObject object = new OuterObject("name", new InnerObject("inner")); Getter getter = GetterFactory.newMethodGetter(object, null, inne...
public void removeAndFailAll(Throwable cause) { assert executor.inEventLoop(); ObjectUtil.checkNotNull(cause, "cause"); // It is possible for some of the failed promises to trigger more writes. The new writes // will "revive" the queue, so we need to clean them up until the queue is empt...
@Test public void testRemoveAndFailAll() { assertWriteFails(new TestHandler() { @Override public void flush(ChannelHandlerContext ctx) throws Exception { queue.removeAndFailAll(new TestException()); super.flush(ctx); } }, 3); }
@Override public void checkBeforeUpdate(final AlterEncryptRuleStatement sqlStatement) { checkToBeAlteredRules(sqlStatement); checkColumnNames(sqlStatement); checkToBeAlteredEncryptors(sqlStatement); }
@Test void assertCheckSQLStatementWithoutToBeAlteredEncryptors() { EncryptRule rule = mock(EncryptRule.class); when(rule.getAllTableNames()).thenReturn(Collections.singleton("t_encrypt")); executor.setRule(rule); assertThrows(ServiceProviderNotFoundException.class, () -> executor.che...
@Override public synchronized void unregister(P provider) { checkNotNull(provider, "Provider cannot be null"); S service = services.get(provider.id()); if (service instanceof AbstractProviderService) { ((AbstractProviderService) service).invalidate(); services.remove(...
@Test public void voidUnregistration() { TestProviderRegistry registry = new TestProviderRegistry(); registry.unregister(new TestProvider(new ProviderId("of", "foo"))); }
static EndpointConfig endpointConfigFromProperties(HazelcastProperties properties) { EndpointConfig endpointConfig = new EndpointConfig(); endpointConfig.setSocketKeepAlive(properties.getBoolean(ClusterProperty.SOCKET_KEEP_ALIVE)); endpointConfig.setSocketKeepIdleSeconds(properties.getInteger(Cl...
@Test public void testEndpointConfigFromClusterProperty() { Config config = new Config(); config.setProperty(ClusterProperty.SOCKET_KEEP_ALIVE.getName(), "false"); config.setProperty(ClusterProperty.SOCKET_KEEP_IDLE.getName(), "30"); config.setProperty(ClusterProperty.SOCKET_KEEP_COU...