focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static RLESparseResourceAllocation merge(ResourceCalculator resCalc, Resource clusterResource, RLESparseResourceAllocation a, RLESparseResourceAllocation b, RLEOperator operator, long start, long end) throws PlanningException { NavigableMap<Long, Resource> cumA = a.getRangeOverlappi...
@Test @Ignore public void testMergeSpeed() throws PlanningException { for (int j = 0; j < 100; j++) { TreeMap<Long, Resource> a = new TreeMap<>(); TreeMap<Long, Resource> b = new TreeMap<>(); Random rand = new Random(); long startA = 0; long startB = 0; for (int i = 0; i < ...
<C extends ProcessingContext> Span nextSpan(C context, Headers headers) { TraceContextOrSamplingFlags extracted = extractor.extract(headers); // Clear any propagation keys present in the headers if (!extracted.equals(emptyExtraction)) { clearHeaders(headers); } Span result = tracer.nextSpan(ex...
@Test void nextSpan_uses_current_context() { ProcessorContext<String, String> fakeProcessorContext = processorV2ContextSupplier.get(); Span child; try (Scope scope = tracing.currentTraceContext().newScope(parent)) { child = kafkaStreamsTracing.nextSpan(fakeProcessorContext, new RecordHeaders()); }...
@Override public <K> boolean isMine(K id, Function<K, Long> hasher) { return Objects.equals(localNodeId, getLeader(id, hasher)); }
@Test public void testIsMine() { // We'll own only the first partition setUpLeadershipService(1); replay(leadershipService); Key myKey = new ControllableHashKey(0); Key notMyKey = new ControllableHashKey(1); assertTrue(partitionManager.isMine(myKey, Key::hash)); ...
public long toLong() { long mac = 0; for (int i = 0; i < 6; i++) { final long t = (this.address[i] & 0xffL) << (5 - i) * 8; mac |= t; } return mac; }
@Test public void testToLong() throws Exception { assertEquals(MAC_ONOS_LONG, MAC_ONOS.toLong()); }
public Object createArray(String fqn, int[] dimensions) { Class<?> clazz = null; Object returnObject = null; try { clazz = TypeUtil.forName(fqn); returnObject = Array.newInstance(clazz, dimensions); } catch (Exception e) { logger.log(Level.WARNING, "Class FQN does not exist: " + fqn, e); throw new P...
@Test public void testCreateArray() { Object array1 = rEngine.createArray("int", new int[] { 2 }); int[] array1int = (int[]) array1; assertEquals(2, array1int.length); array1 = rEngine.createArray("java.lang.String", new int[] { 3, 4 }); String[][] array1String = (String[][]) array1; assertEquals(3, array...
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBuildSchemaKTableWhenKTableSource() { // Given: final KsqlTable<String> table = new KsqlTable<>("sqlExpression", SourceName.of("datasource"), REAL_SCHEMA, Optional.of(TIMESTAMP_COLUMN), false, new KsqlTopic( "topic2", KeyF...
public Date parseString(String dateString) throws ParseException { if (dateString == null || dateString.isEmpty()) { return null; } Matcher xep82WoMillisMatcher = xep80DateTimeWoMillisPattern.matcher(dateString); Matcher xep82Matcher = xep80DateTimePattern.matcher(dateString)...
@Test public void testExceptionContainsOffendingValue() throws Exception { // Setup fixture final String testValue = "This is not a valid date value"; // Execute system under test try { xmppDateTimeFormat.parseString(testValue); // Verify results ...
public List<List<String>> cells() { return raw; }
@Test void cells_col_is_immutable() { assertThrows(UnsupportedOperationException.class, () -> createSimpleTable().cells().get(0).remove(0)); }
public static Set<ConfigKey<?>> getAllConfigsProduced(Class<? extends ConfigProducer> producerClass, String configId) { // TypeToken is @Beta in guava, so consider implementing a simple recursive method instead. TypeToken<? extends ConfigProducer>.TypeSet interfaces = TypeToken.of(producerClass).getType...
@Test void getAllConfigsProduced_includes_configs_directly_implemented_by_producer() { Set<ConfigKey<?>> configs = getAllConfigsProduced(SimpleProducer.class, "foo"); assertEquals(1, configs.size()); assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", Simple...
protected Properties getConfiguration() { return config; }
@Test public void testGetConfiguration() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn(""); Mockito.when(config.getInitParameter("...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public NodeInfo get() { return getNodeInfo(); }
@Test public void testNodeInfoDefault() throws JSONException, Exception { WebResource r = resource(); ClientResponse response = r.path("ws").path("v1").path("node").path("info") .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, response.getType(...
@Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final CompositePropertySource compositePropertySource = new CompositePropertySource(SOURCE_NAME); compositePropertySource.addPropertySource(new OriginRegistrySwitchSource(SOURCE_NAME));...
@Test public void test() { final SpringEnvironmentProcessor springEnvironmentProcessor = new SpringEnvironmentProcessor(); final ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class); final MutablePropertySources propertySources = new MutablePropertySources(); ...
public Iterable<TimestampedValue<T>> readRange(Instant minTimestamp, Instant limitTimestamp) { checkState( !isClosed, "OrderedList user state is no longer usable because it is closed for %s", requestTemplate.getStateKey()); // Store pendingAdds whose sort key is in the query range and v...
@Test public void testReadRange() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient( timestampedValueCoder, ImmutableMap.of( createOrderedListStateKey("A", 1), asList(A1, B1), createOrderedListStateKey("A", 4), Collectio...
@Override public int getattr(String path, FileStat stat) { return AlluxioFuseUtils.call( LOG, () -> getattrInternal(path, stat), FuseConstants.FUSE_GETATTR, "path=%s", path); }
@Test @DoraTestTodoItem(action = DoraTestTodoItem.Action.FIX, owner = "LuQQiu") @Ignore public void getattrWithDelay() throws Exception { String path = "/foo/bar"; AlluxioURI expectedPath = BASE_EXPECTED_URI.join("/foo/bar"); // set up status FileInfo info = new FileInfo(); info.setLength(0);...
static byte[] readPrivateKey(Path path) throws KeyException { final byte[] bytes; try { bytes = Files.readAllBytes(path); } catch (IOException e) { throw new KeyException("Couldn't read private key from file: " + path, e); } final String content = new Str...
@Test(expected = KeyException.class) public void readPrivateKeyFailsOnInvalidFile() throws Exception { final File file = temporaryFolder.newFile(); PemReader.readPrivateKey(file.toPath()); }
@POST @Timed @ApiOperation(value = "Create index set") @RequiresPermissions(RestPermissions.INDEXSETS_CREATE) @Consumes(MediaType.APPLICATION_JSON) @AuditEvent(type = AuditEventTypes.INDEX_SET_CREATE) @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), }) ...
@Test @Ignore("Currently doesn't work with @RequiresPermissions") public void saveDenied() { notPermitted(); final IndexSetConfig indexSetConfig = IndexSetConfig.create( "title", "description", true, true, "prefix", ...
public List<Stream> match(Message message) { final Set<Stream> result = Sets.newHashSet(); final Set<String> blackList = Sets.newHashSet(); for (final Rule rule : rulesList) { if (blackList.contains(rule.getStreamId())) { continue; } final St...
@Test public void testGreaterMatch() throws Exception { final StreamMock stream = getStreamMock("test"); final StreamRuleMock rule = new StreamRuleMock(ImmutableMap.of( "_id", new ObjectId(), "field", "testfield", "value", "1", "type", ...
public static boolean hasCause(Throwable t, Class<? extends Throwable> exceptionClass) { if (t.getClass().isAssignableFrom(exceptionClass)) return true; if (t.getCause() != null) { return hasCause(t.getCause(), exceptionClass); } return false; }
@Test void hasCauseReturnsFalseIfExceptionDoesNotHaveGivenCause() { final boolean hasInterruptedExceptionAsCause = Exceptions.hasCause(new RuntimeException(new IllegalStateException()), InterruptedException.class); assertThat(hasInterruptedExceptionAsCause).isFalse(); }
public static JSONArray parseArray(String jsonStr) { return new JSONArray(jsonStr); }
@Test public void parseNumberToJSONArrayTest2() { final JSONArray json = JSONUtil.parseArray(123L, JSONConfig.create().setIgnoreError(true)); assertNotNull(json); }
@Override public CreateTopicsResult createTopics(final Collection<NewTopic> newTopics, final CreateTopicsOptions options) { final Map<String, KafkaFutureImpl<TopicMetadataAndConfig>> topicFutures = new HashMap<>(newTopics.size()); final CreatableTopicCollec...
@Test public void testCreateTopicsRetryThrottlingExceptionWhenEnabled() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse( expectCreateTopicsReques...
public DataSource getDatasource() { return jt.getDataSource(); }
@Test void testGetDataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl("test.jdbc.url"); when(jt.getDataSource()).thenReturn(dataSource); assertEquals(dataSource.getJdbcUrl(), ((HikariDataSource) service.getDatasource()).getJdbcUrl()); ...
public <V> Future<Iterable<Map.Entry<ByteString, V>>> valuePrefixFuture( ByteString prefix, String stateFamily, Coder<V> valueCoder) { // First request has no continuation position. StateTag<ByteString> stateTag = StateTag.<ByteString>of(Kind.VALUE_PREFIX, prefix, stateFamily).toBuilder().build();...
@Test public void testReadTagValuePrefix() throws Exception { Future<Iterable<Map.Entry<ByteString, Integer>>> future = underTest.valuePrefixFuture(STATE_KEY_PREFIX, STATE_FAMILY, INT_CODER); Mockito.verifyNoMoreInteractions(mockWindmill); Windmill.KeyedGetDataRequest.Builder expectedRequest = ...
public List<Partition> getPartitions(Connection connection, Table table) { JDBCTable jdbcTable = (JDBCTable) table; String query = getPartitionQuery(table); try (PreparedStatement ps = connection.prepareStatement(query)) { ps.setString(1, jdbcTable.getDbName()); ps.setStr...
@Test public void testGetPartitionsWithCache() { try { JDBCCacheTestUtil.openCacheEnable(connectContext); JDBCMetadata jdbcMetadata = new JDBCMetadata(properties, "catalog", dataSource); JDBCTable jdbcTable = new JDBCTable(100000, "tbl1", Arrays.asList(new Column("d", Typ...
public static String formatTimestampMillis(long millis) { return Instant.ofEpochMilli(millis).toString().replace("Z", "+00:00"); }
@Test public void formatTimestampMillis() { String timestamp = "1970-01-01T00:00:00.001+00:00"; assertThat(DateTimeUtil.formatTimestampMillis(1L)).isEqualTo(timestamp); assertThat(ZonedDateTime.parse(timestamp).toInstant().toEpochMilli()).isEqualTo(1L); timestamp = "1970-01-01T00:16:40+00:00"; as...
@SuppressWarnings("deprecation") @Override public Handle newHandle() { return new HandleImpl(minIndex, maxIndex, initialIndex, minCapacity, maxCapacity); }
@Test public void doesSetCorrectMinBounds() { AdaptiveRecvByteBufAllocator recvByteBufAllocator = new AdaptiveRecvByteBufAllocator(81, 95, 95); RecvByteBufAllocator.ExtendedHandle handle = (RecvByteBufAllocator.ExtendedHandle) recvByteBufAllocator.newHandle(); handle.reset(co...
public void setService(Class<? extends Service> klass) throws ServerException { ensureOperational(); Check.notNull(klass, "serviceKlass"); if (getStatus() == Status.SHUTTING_DOWN) { throw new IllegalStateException("Server shutting down"); } try { Service newService = klass.newInstance();...
@Test(expected = IllegalStateException.class) @TestDir public void illegalState3() throws Exception { Server server = new Server("server", TestDirHelper.getTestDir().getAbsolutePath(), new Configuration(false)); server.setService(null); }
public static Set<X509Certificate> filterValid( X509Certificate... certificates ) { final Set<X509Certificate> results = new HashSet<>(); if (certificates != null) { for ( X509Certificate certificate : certificates ) { if ( certificate == null ) ...
@Test public void testFilterValidWithValidAndInvalidCerts() throws Exception { // Setup fixture. final X509Certificate valid = KeystoreTestUtils.generateValidCertificate().getCertificate(); final X509Certificate invalid = KeystoreTestUtils.generateExpiredCertificate().getCertificate(); ...
public static int length(Object obj) { if (obj == null) { return 0; } if (obj instanceof CharSequence) { return ((CharSequence) obj).length(); } if (obj instanceof Collection) { return ((Collection<?>) obj).size(); } if (obj instanceof Map) { return ((Map<?, ?>) obj).size(); } int count; ...
@Test public void lengthTest() { int[] array = new int[]{1, 2, 3, 4, 5}; int length = ObjectUtil.length(array); assertEquals(5, length); Map<String, String> map = new HashMap<>(); map.put("a", "a1"); map.put("b", "b1"); map.put("c", "c1"); length = ObjectUtil.length(map); assertEquals(3, length); }
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void deleteChatPhoto() { BaseResponse response = bot.execute(new DeleteChatPhoto(groupId)); if (!response.isOk()) { assertEquals(400, response.errorCode()); assertEquals("Bad Request: CHAT_NOT_MODIFIED", response.description()); } }
@Override protected Mono<Void> handleSelectorIfNull(final String pluginName, final ServerWebExchange exchange, final ShenyuPluginChain chain) { return WebFluxResultUtils.noSelectorResult(pluginName, exchange); }
@Test public void handleSelectorIfNullTest() { ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.class); SpringBeanUtils.getInstance().setApplicationContext(context); when(context.getBean(ShenyuResult.class)).thenReturn(new DefaultShenyuResult()); StepVerif...
public static String normalize(String url) { return normalize(url, false); }
@Test public void normalizeTest3() { String url = "http://www.hutool.cn//aaa/\\bbb?a=1&b=2"; String normalize = URLUtil.normalize(url, true); assertEquals("http://www.hutool.cn//aaa//bbb?a=1&b=2", normalize); url = "www.hutool.cn//aaa/bbb?a=1&b=2"; normalize = URLUtil.normalize(url, true); assertEquals("h...
public T put(String key, T value) { return delegate.put(key.toLowerCase(), value); }
@Test public void testPut() throws Exception { String someKey = "someKey"; Object someValue = mock(Object.class); Object anotherValue = mock(Object.class); when(someMap.put(someKey.toLowerCase(), someValue)).thenReturn(anotherValue); assertEquals(anotherValue, caseInsensitiveMapWrapper.put(someK...
@Override public PathAttributes toAttributes(final DavResource resource) { final PathAttributes attributes = super.toAttributes(resource); final Map<QName, String> properties = resource.getCustomPropsNS(); if(null != properties) { if(properties.containsKey(OC_FILEID_CUSTOM_NAMESP...
@Test public void testCustomModified_Modified() { final NextcloudAttributesFinderFeature f = new NextcloudAttributesFinderFeature(null); final DavResource mock = mock(DavResource.class); Map<QName, String> map = new HashMap<>(); map.put(DAVTimestampFeature.LAST_MODIFIED_CUSTOM_NAMES...
@Override public int encode(PortNumber resource) { return (int) resource.toLong(); }
@Test public void testEncode() { assertThat(sut.encode(PortNumber.portNumber(100)), is(100)); }
@Override public boolean unRegistry() { return zkServiceManager.chooseService().unRegistry(); }
@Test public void unRegistry() { Mockito.when(zkService34.unRegistry()).thenReturn(true); Assert.assertTrue(zkDiscoveryClient.unRegistry()); }
public static <T> void padLeft(List<T> list, int minLen, T padObj) { Objects.requireNonNull(list); if (list.isEmpty()) { padRight(list, minLen, padObj); return; } for (int i = list.size(); i < minLen; i++) { list.add(0, padObj); } }
@Test public void testPadLeft() { List<String> srcList = CollUtil.newArrayList(); List<String> answerList = CollUtil.newArrayList("a", "b"); CollUtil.padLeft(srcList, 1, "b"); CollUtil.padLeft(srcList, 2, "a"); assertEquals(srcList, answerList); srcList = CollUtil.newArrayList("a", "b"); answerList = Co...
@Override public void touch(final Local file) throws AccessDeniedException { try { try { Files.createFile(Paths.get(file.getAbsolute())); } catch(NoSuchFileException e) { final Local parent = file.getParent(); new DefaultLoc...
@Test public void testTouch() throws Exception { Local parent = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random()); Local l = new Local(parent, UUID.randomUUID().toString()); final DefaultLocalTouchFeature f = new DefaultLocalTouchFeature(); ...
public static Write write() { return new AutoValue_MongoDbIO_Write.Builder() .setMaxConnectionIdleTime(60000) .setBatchSize(1024L) .setSslEnabled(false) .setIgnoreSSLCertificate(false) .setSslInvalidHostNameAllowed(false) .setOrdered(true) .build(); }
@Test public void testUpdate() { final String collectionName = "testUpdate"; final int numElements = 100; Document doc = Document.parse("{\"id\":1,\"scientist\":\"Updated\",\"country\":\"India\"}"); database.getCollection(collectionName).insertMany(createDocuments(numElements, true)); assertEqual...
@Override public Object getNativeDataType( Object object ) throws KettleValueException { return getString( object ); }
@Test public void testGetNativeData_emptyIsNull() throws Exception { meta.setNullsAndEmptyAreDifferent( false ); assertEquals( BASE_VALUE, meta.getNativeDataType( BASE_VALUE ) ); assertEquals( TEST_VALUE, meta.getNativeDataType( TEST_VALUE ) ); assertEquals( null, meta.getNativeDataType( null ) ); ...
public String namespaceProperties(Namespace ns) { return SLASH.join("v1", prefix, "namespaces", RESTUtil.encodeNamespace(ns), "properties"); }
@Test public void testNamespacePropertiesWithSlash() { Namespace ns = Namespace.of("n/s"); assertThat(withPrefix.namespaceProperties(ns)) .isEqualTo("v1/ws/catalog/namespaces/n%2Fs/properties"); assertThat(withoutPrefix.namespaceProperties(ns)).isEqualTo("v1/namespaces/n%2Fs/properties"); }
@VisibleForTesting WorkerIdentity get(String key, int index) { NavigableMap<Integer, WorkerIdentity> map = mActiveNodesByConsistentHashing; Preconditions.checkState(map != null, "Hash provider is not properly initialized"); return get(map, key, index); }
@Test public void uninitializedThrowsException() { ConsistentHashProvider provider = new ConsistentHashProvider( 1, WORKER_LIST_TTL_MS, NUM_VIRTUAL_NODES); assertThrows(IllegalStateException.class, () -> provider.get(OBJECT_KEY, 0)); }
public static Object eval(String expression, Map<String, Object> context) { return eval(expression, context, ListUtil.empty()); }
@Test public void mvelTest(){ final ExpressionEngine engine = new MvelEngine(); final Dict dict = Dict.create() .set("a", 100.3) .set("b", 45) .set("c", -199.100); final Object eval = engine.eval("a-(b-c)", dict, null); assertEquals(-143.8, (double)eval, 0); }
public void run() { validate(); if (!super.getNotification().hasErrors()) { LOGGER.info("Register worker in backend system"); } }
@Test void runWithMissingDOB() { RegisterWorkerDto workerDto = createValidWorkerDto(); workerDto.setupWorkerDto("name", "occupation", null); RegisterWorker registerWorker = new RegisterWorker(workerDto); // Run the registration process registerWorker.run(); // Verif...
public synchronized void awaitUpdate(final int lastVersion, final long timeoutMs) throws InterruptedException { long currentTimeMs = time.milliseconds(); long deadlineMs = currentTimeMs + timeoutMs < 0 ? Long.MAX_VALUE : currentTimeMs + timeoutMs; time.waitObject(this, () -> { // Thr...
@Test public void testMetadataUpdateWaitTime() throws Exception { long time = 0; metadata.updateWithCurrentRequestVersion(responseWithCurrentTopics(), false, time); assertTrue(metadata.timeToNextUpdate(time) > 0, "No update needed."); // first try with a max wait time of 0 and ensure...
@Override public void close() { internal.close(); }
@Test public void shouldDelegateAndRemoveMetricsOnClose() { assertThat(storeMetrics(), not(empty())); store.close(); verify(inner).close(); assertThat(storeMetrics(), empty()); }
public RelDataType createRelDataTypeFromSchema(Schema schema) { Builder builder = new Builder(this); boolean enableNullHandling = schema.isEnableColumnBasedNullHandling(); for (Map.Entry<String, FieldSpec> entry : schema.getFieldSpecMap().entrySet()) { builder.add(entry.getKey(), toRelDataType(entry.g...
@Test(dataProvider = "relDataTypeConversion") public void testScalarTypes(FieldSpec.DataType dataType, RelDataType scalarType, boolean columnNullMode) { TypeFactory typeFactory = new TypeFactory(); Schema testSchema = new Schema.SchemaBuilder() .addSingleValueDimension("col", dataType) .setEna...
public static double microdegreesToDegrees(int coordinate) { return coordinate / CONVERSION_FACTOR; }
@Test public void intToDoubleTest() { double degrees = LatLongUtils.microdegreesToDegrees(MICRO_DEGREES); Assert.assertEquals(DEGREES, degrees, 0); }
private RemotingCommand getConsumerRunningInfo(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { final RemotingCommand response = RemotingCommand.createResponseCommand(null); final GetConsumerRunningInfoRequestHeader requestHeader = (GetConsumerRun...
@Test public void testGetConsumerRunningInfo() throws Exception { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); RemotingCommand request = mock(RemotingCommand.class); when(request.getCode()).thenReturn(RequestCode.GET_CONSUMER_RUNNING_INFO); ConsumerRunningInfo consu...
public long getBlockLen() { return block_len; }
@Test public void testGetBlockLen() { assertEquals(TestParameters.VP_RES_TBL_BLOCK_LENGTH, chmLzxcResetTable.getBlockLen()); }
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testJadNewPbWithLeagueTask() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your TzTok-Jad kill count is: <col=ff0000>2</col>.", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Congratulations, you've complete...
private CoordinatorResult<ConsumerGroupHeartbeatResponseData, CoordinatorRecord> consumerGroupHeartbeat( String groupId, String memberId, int memberEpoch, String instanceId, String rackId, int rebalanceTimeoutMs, String clientId, String clientHost, ...
@Test public void testMemberIdGeneration() { MockPartitionAssignor assignor = new MockPartitionAssignor("range"); GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder() .withConsumerGroupAssignors(Collections.singletonList(assignor)) .withMeta...
public static int degreeToInt(double deg) { if (deg >= Double.MAX_VALUE) return Integer.MAX_VALUE; if (deg <= -Double.MAX_VALUE) return -Integer.MAX_VALUE; return (int) Math.round(deg * DEGREE_FACTOR); }
@Test void degreeToInt() { int storedInt = 444_494_395; double lat = Helper.intToDegree(storedInt); assertEquals(44.4494395, lat); assertEquals(storedInt, Helper.degreeToInt(lat)); }
@Override public <T> Future<T> submit(Callable<T> task) { submitted.mark(); return delegate.submit(new InstrumentedCallable<>(task)); }
@Test public void testSubmitRunnable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); assertThat(completed.getCount()).isZero(); assertThat(duration.getCount()).isZero(); assertThat(scheduledOnce.getCount()).isZero(); ...
@Nonnull public static <V> Set<V> findDuplicates(@Nonnull final Collection<V>... collections) { final Set<V> merged = new HashSet<>(); final Set<V> duplicates = new HashSet<>(); for (Collection<V> collection : collections) { for (V o : collection) { if (!merge...
@Test public void testMultipleCollectionsWithoutDuplicates() throws Exception { // Setup test fixture. final List<String> input1 = Arrays.asList("a", "b"); final List<String> input2 = Arrays.asList("c", "d"); final List<String> input3 = Arrays.asList("e", "f", "g"); // E...
@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 testGetJobManagerCustomLogsValidFilenameWithLongInvalidPath() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("foobar/../../%s", VALID_LOG_FILENAME))); assertThat(actualFile).isNotNull(); String...
@Override public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo, Set<String> authScopes) { Map<String, Object> result = newLinkedHashMap(); OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication(); result.put(ACTIVE, true); if (...
@Test public void shouldAssembleExpectedResultForRefreshTokenWithoutUserInfo() throws ParseException { // given OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L), oauth2AuthenticationWithUser(oauth2Request("clientId", scopes("foo", "bar")), "name")); Set<String> authScopes = scope...
@Override public List<String> getChildren(String path) { try { return client.getChildren().forPath(path); } catch (NoNodeException e) { return null; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
@Test void testChildrenPath() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); curatorClient.create(path + "/provider1", false, true); curatorClient.create(path + "/provider2", false, true); List<String> children ...
public static String jaasConfig(String moduleName, Map<String, String> options) { StringJoiner joiner = new StringJoiner(" "); for (Entry<String, String> entry : options.entrySet()) { String key = Objects.requireNonNull(entry.getKey()); String value = Objects.requireNonNull(entry...
@Test public void testConfigWithNullOptionValue() { String moduleName = "ExampleModule"; Map<String, String> options = new HashMap<>(); options.put("option1", null); assertThrows(NullPointerException.class, () -> AuthenticationUtils.jaasConfig(moduleName, options)); }
static KiePMMLMapValues getKiePMMLMapValues(final MapValues mapValues) { DATA_TYPE dataType = mapValues.getDataType() != null ? DATA_TYPE.byName(mapValues.getDataType().value()) : null; KiePMMLMapValues.Builder builder = KiePMMLMapValues.builder(UUID.randomUUID().toString(), ...
@Test void getKiePMMLMapValues() { MapValues toConvert = getRandomMapValues(); KiePMMLMapValues retrieved = KiePMMLMapValuesInstanceFactory.getKiePMMLMapValues(toConvert); commonVerifyKiePMMLMapValues(retrieved, toConvert); }
public WorkflowInstance getWorkflowInstanceRun(String workflowId, long instanceId, long runId) { WorkflowInstance ret = withMetricLogError( () -> withRetryableQuery( runId == Constants.LATEST_ONE ? GET_LATEST_WORKFLOW_INSTANCE_RUN_QUERY...
@Test public void testGetWorkflowInstanceRun() { WorkflowInstance instanceRun = instanceDao.getWorkflowInstanceRun( wfi.getWorkflowId(), wfi.getWorkflowInstanceId(), wfi.getWorkflowRunId()); instanceRun.setModifyTime(null); assertEquals(wfi, instanceRun); }
@Override public void openExisting(final ProcessorContext context, final long streamTime) { metricsRecorder.init(ProcessorContextUtils.metricsImpl(context), context.taskId()); super.openExisting(context, streamTime); }
@Test public void shouldUpdateSegmentFileNameFromOldDateFormatToNewFormat() throws Exception { final long segmentInterval = 60_000L; // the old segment file's naming system maxes out at 1 minute granularity. segments = new TimestampedSegments(storeName, METRICS_SCOPE, NUM_SEGMENTS * segmentInterval...
@Override public void notifyClientConnected(final MqttConnectMessage msg) { for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) { LOG.debug("Sending MQTT CONNECT message to interceptor. CId={}, interceptorId={}", msg.payload().clientIdentif...
@Test public void testNotifyClientConnected() throws Exception { interceptor.notifyClientConnected(MqttMessageBuilders.connect().build()); interval(); assertEquals(40, n.get()); }
public RSA() { super(ALGORITHM_RSA); }
@Test public void rsaTest() { final RSA rsa = new RSA(); // 获取私钥和公钥 assertNotNull(rsa.getPrivateKey()); assertNotNull(rsa.getPrivateKeyBase64()); assertNotNull(rsa.getPublicKey()); assertNotNull(rsa.getPrivateKeyBase64()); // 公钥加密,私钥解密 final byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", Ch...
static <T extends Type> String encodeDynamicArray(DynamicArray<T> value) { int size = value.getValue().size(); String encodedLength = encode(new Uint(BigInteger.valueOf(size))); String valuesOffsets = encodeArrayValuesOffsets(value); String encodedValues = encodeArrayValues(value); ...
@Test public void testDynamicStringsArray() { DynamicArray<Utf8String> array = new DynamicArray<>( Utf8String.class, new Utf8String("web3j"), new Utf8String("arrays"), new Utf8String("encoding"));...
public static Expression convert(Predicate[] predicates) { Expression expression = Expressions.alwaysTrue(); for (Predicate predicate : predicates) { Expression converted = convert(predicate); Preconditions.checkArgument( converted != null, "Cannot convert Spark predicate to Iceberg expres...
@Test public void testEqualToNull() { String col = "col"; NamedReference namedReference = FieldReference.apply(col); LiteralValue value = new LiteralValue(null, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue = new org.apache.spark.sql.connector.ex...
public static boolean compareRows(List<Row> l1, List<Row> l2) { return compareRows(l1, l2, false); }
@Test void testCompareRowsUnordered() { final List<Row> originalList = Arrays.asList( Row.of("a", 12, false), Row.of("b", 12, false), Row.of("b", 12, false), Row.of("b", 12, true)); { ...
public static Collection<DatabasePacket> buildQueryResponsePackets(final QueryResponseHeader queryResponseHeader, final int characterSet, final int statusFlags) { Collection<DatabasePacket> result = new LinkedList<>(); List<QueryHeader> queryHeaders = queryResponseHeader.getQueryHeaders(); resul...
@SuppressWarnings({"unchecked", "rawtypes"}) @Test void assertBuildQueryResponsePacketsWithBinaryColumnType() { QueryHeader nonBinaryHeader = new QueryHeader("s", "t", "columnLabel1", "columnName1", 5, "VARCHAR", 1, 1, false, false, false, false); QueryHeader binaryHeader = new QueryHeader("s", ...
@Override public boolean confirm(String key) { return cache.replace(key, false, true); }
@Test void testConfirm() { // add first key and confirm assertTrue(repo.add(key01)); assertTrue(repo.confirm(key01)); // try to confirm a key that isn't there assertFalse(repo.confirm(key02)); }
public static HttpBodyOutput write(List<? extends FormMultipart.FormPart> parts) { return write("blob:" + UUID.randomUUID(), parts); }
@Test void testMultipart() { var e = """ --boundary\r content-disposition: form-data; name="field1"\r content-type: text/plain; charset=utf-8\r \r value1\r --boundary\r content-disposition: form-data; name="field2"; filename...
@Override public Double dist(V firstMember, V secondMember, GeoUnit geoUnit) { return get(distAsync(firstMember, secondMember, geoUnit)); }
@Test public void testDist() { RGeo<String> geo = redisson.getGeo("test"); geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"), new GeoEntry(15.087269, 37.502669, "Catania")); assertThat(geo.dist("Palermo", "Catania", GeoUnit.METERS)).isEqualTo(166274.1516D); }
@Override public void apply(IntentOperationContext<DomainIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); List<DomainIntent> uninstallIntents = context.intentsToUninstall(); List<DomainIntent> installI...
@Test public void testUninstall() { List<Intent> intentsToUninstall = createDomainIntents(); List<Intent> intentsToInstall = Lists.newArrayList(); IntentData toUninstall = new IntentData(createP2PIntent(), IntentState.WITHDRAWING, ...
static int encode( final UnsafeBuffer encodingBuffer, final int offset, final int captureLength, final int length, final DirectBuffer srcBuffer, final int srcOffset) { final int encodedLength = encodeLogHeader(encodingBuffer, offset, captureLength, length); ...
@Test void encodeBufferBuggerThanMaxCaptureSize() { final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[MAX_EVENT_LENGTH * 2]); final int offset = 256; final int srcOffset = 20; final int length = MAX_EVENT_LENGTH + 1000; srcBuffer.setMemory(srcOffset, length, (byte)...
@Override public String getFingerprint(Schema schema) { return schema.toString(); }
@Test public void testDifferentFPs() { String fp1 = reg.getFingerprint(schema1); String fp2 = reg.getFingerprint(schema2); assertNotEquals(fp1, fp2); }
public static FallbackMethod create(String fallbackMethodName, Method originalMethod, Object[] args, Object original, Object proxy) throws NoSuchMethodException { MethodMeta methodMeta = new MethodMeta( fallbackMethodName, originalMethod.getParamet...
@Test public void shouldFailIf2FallBackMethodsHandleSameException() throws Throwable { FallbackMethodTest target = new FallbackMethodTest(); Method testMethod = target.getClass().getMethod("testMethod", String.class); assertThatThrownBy(() -> FallbackMethod .create("returnMismatc...
public FEELFnResult<List> invoke(@ParameterName("list") List list, @ParameterName("start position") BigDecimal start) { return invoke( list, start, null ); }
@Test void invokeLengthOutOfListBounds() { FunctionTestUtil.assertResultError(sublistFunction.invoke(Arrays.asList(1, 2), BigDecimal.ONE, BigDecimal.valueOf(3)), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(sublis...
public static ResourceModel processResource(final Class<?> resourceClass) { return processResource(resourceClass, null); }
@Test(expectedExceptions = ResourceConfigException.class) public void failsOnEmptyBatchFinderMethodBatchParamParameter() { @RestLiCollection(name = "batchFinderWithEmptyBatchParam") class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> { @BatchFinder(value = "batchFinderWithEmptyBa...
@Override public void deleteDictType(Long id) { // 校验是否存在 DictTypeDO dictType = validateDictTypeExists(id); // 校验是否有字典数据 if (dictDataService.getDictDataCountByDictType(dictType.getType()) > 0) { throw exception(DICT_TYPE_HAS_CHILDREN); } // 删除字典类型 ...
@Test public void testDeleteDictType_hasChildren() { // mock 数据 DictTypeDO dbDictType = randomDictTypeDO(); dictTypeMapper.insert(dbDictType);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbDictType.getId(); // mock 方法 when(dictDataService.getDictDataCountByDictType(...
static void checkNearCacheNativeMemoryConfig(InMemoryFormat inMemoryFormat, NativeMemoryConfig nativeMemoryConfig, boolean isEnterprise) { if (!isEnterprise) { return; } if (inMemoryFormat != NATIVE) { return; } ...
@Test public void checkNearCacheNativeMemoryConfig_shouldNotThrowExceptionWithNativeMemoryConfig_NATIVE_onEE() { NativeMemoryConfig nativeMemoryConfig = new NativeMemoryConfig() .setEnabled(true); checkNearCacheNativeMemoryConfig(NATIVE, nativeMemoryConfig, true); }
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } checkNoComponentAnnotations(stepClass); if (hasCucumberContextConfiguration(stepClass)) { checkOnlyOneClassHasCucumberContextConfiguration(step...
@Test void shouldFailIfClassWithAnnotationAnnotatedWithSpringComponentAnnotationsIsFound() { final ObjectFactory factory = new SpringFactory(); Executable testMethod = () -> factory.addClass(WithControllerAnnotation.class); CucumberBackendException actualThrown = assertThrows(CucumberBacken...
public Date getEndOfNextNthPeriod(Date now, int numPeriods) { Calendar cal = this; cal.setTime(now); roundDownTime(cal, this.datePattern); switch (this.periodicityType) { case TOP_OF_MILLISECOND: cal.add(Calendar.MILLISECOND, numPeriods); break; case TOP_OF_SECOND: ...
@Test public void testVaryingNumberOfDailyPeriods() { RollingCalendar rc = new RollingCalendar("yyyy-MM-dd"); final long MILLIS_IN_DAY = 24 * 3600 * 1000; for (int p = 20; p > -100; p--) { long now = 1223325293589L; // Mon Oct 06 22:34:53 CEST 2008 Date nowDate = new Date(now); Date res...
public static <T> Class<? extends T> getMapperClass(Class<T> clazz) { try { List<ClassLoader> classLoaders = collectClassLoaders( clazz.getClassLoader() ); return getMapperClass( clazz, classLoaders ); } catch ( ClassNotFoundException e ) { throw new RuntimeE...
@Test public void shouldReturnImplementationClass() { Class<? extends Foo> mapperClass = Mappers.getMapperClass( Foo.class ); assertThat( mapperClass ).isNotNull(); assertThat( mapperClass ).isNotExactlyInstanceOf( Foo.class ); }
@Override public long getMaxJournalId() { long ret = -1; if (bdbEnvironment == null) { return ret; } List<Long> dbNames = bdbEnvironment.getDatabaseNamesWithPrefix(prefix); if (dbNames == null || dbNames.isEmpty()) { return ret; } int ...
@Test public void testGetMaxJournalId(@Mocked CloseSafeDatabase closeSafeDatabase, @Mocked BDBEnvironment environment, @Mocked Database database) throws Exception { BDBJEJournal journal = new BDBJEJournal(environment); // faile...
public Date parseString(String dateString) throws ParseException { if (dateString == null || dateString.isEmpty()) { return null; } Matcher xep82WoMillisMatcher = xep80DateTimeWoMillisPattern.matcher(dateString); Matcher xep82Matcher = xep80DateTimePattern.matcher(dateString)...
@Test public void testFormatNoSecondFractions() throws Exception { // Setup fixture final String testValue = "2015-03-19T22:54:15+00:00"; // Thu, 19 Mar 2015 22:54:15 GMT // Execute system under test final Date result = xmppDateTimeFormat.parseString(testValue); // Veri...
public static Gson instance() { return SingletonHolder.INSTANCE; }
@Test void serializesCharsets() { assertThatJson(Serialization.instance().toJson(StandardCharsets.UTF_8)).isEqualTo("UTF-8"); //noinspection CharsetObjectCanBeUsed assertThatJson(Serialization.instance().toJson(Charset.forName("ascii"))).isEqualTo("US-ASCII"); }
public void runOnStateAppliedFilters(Job job) { new JobPerformingFilters(job, jobDefaultFilters).runOnStateAppliedFilters(); }
@Test void jobFiltersAreExecutedIfJobHasStateChange() { // GIVEN Job aJob = anEnqueuedJob().build(); aJob.getStateChangesForJobFilters(); // clear // WHEN aJob.startProcessingOn(backgroundJobServer); jobFilterUtils.runOnStateAppliedFilters(List.of(aJob)); //...
protected void generateChildEipStatistics(ChildEip childEip, ChildEipStatistic childEipStatistic) { childEip.getEipAttributeMap().forEach((key, value) -> { if (value instanceof EipAttribute) { EipAttribute eipAttribute = (EipAttribute) value; EipStatistic eipStati...
@Test public void testGenerateChildEipStatistics() { }
public void stop() { status = GameStatus.STOPPED; }
@Test void testStop() { gameLoop.stop(); Assertions.assertEquals(GameStatus.STOPPED, gameLoop.status); }
protected Function<Object, ValueWrapper> createExtractorFunction(ExpressionEvaluator expressionEvaluator, FactMappingValue expectedResult, ScesimModelDescriptor scesimModelDescriptor...
@Test public void createExtractorFunction() { String personName = "Test"; FactMappingValue factMappingValue = new FactMappingValue(personFactIdentifier, firstNameGivenExpressionIdentifier, personName); Function<Object, ValueWrapper> extractorFunction = runnerHelper.createExtractorFunction(ex...
public List<String> getServices() throws PolarisException { if (CollectionUtils.isEmpty(polarisDiscoveryHandler.getServices().getServices())) { return Collections.emptyList(); } return polarisDiscoveryHandler.getServices().getServices().stream() .map(ServiceInfo::getService).collect(Collectors.toList()); ...
@Test public void testGetServices() throws PolarisException { ServiceInfo mockServiceInfo = mock(ServiceInfo.class); when(mockServiceInfo.getService()).thenReturn(SERVICE_PROVIDER); ServicesResponse mockServicesResponse = mock(ServicesResponse.class); when(mockServicesResponse.getServices()).thenReturn(singlet...
public NodeState getWantedState() { NodeState retiredState = new NodeState(node.getType(), State.RETIRED); // Don't let configure retired state override explicitly set Down and Maintenance. if (configuredRetired && wantedState.above(retiredState)) { return retiredState; } ...
@Test void maintenance_wanted_state_overrides_config_retired_state() { ClusterFixture fixture = ClusterFixture.forFlatCluster(3) .markNodeAsConfigRetired(1) .proposeStorageNodeWantedState(1, State.MAINTENANCE); NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node...
public Collection<ServerPluginInfo> loadPlugins() { Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>(); for (ServerPluginInfo bundled : getBundledPluginsMetadata()) { failIfContains(bundledPluginsByKey, bundled, plugin -> MessageException.of(format("Found two versions of the...
@Test public void fail_if_external_plugin_has_same_key_has_bundled_plugin() throws IOException { File jar = createJar(fs.getInstalledExternalPluginsDir(), "plugin1", "main", null); createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledExternalPlugi...
@Override public Result apply(ApplyNode applyNode, Captures captures, Context context) { if (applyNode.getSubqueryAssignments().size() != 1) { return Result.empty(); } RowExpression expression = getOnlyElement(applyNode.getSubqueryAssignments().getExpressions()); if ...
@Test public void testDoesNotFireOnNoCorrelation() { tester().assertThat(new TransformUncorrelatedInPredicateSubqueryToSemiJoin()) .on(p -> p.apply( Assignments.of(), emptyList(), p.values(), ...
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { if ( isJettyMode() && !request.getContextPath().startsWith( CONTEXT_PATH ) ) { return; } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "ExecuteTransServlet.Lo...
@Ignore("Unable to run this test without PowerMock") @Test public void doGetRepositoryAuthenticationFailTest() throws Exception { HttpServletRequest mockHttpServletRequest = mock( HttpServletRequest.class ); HttpServletResponse mockHttpServletResponse = mock( HttpServletResponse.class ); RepositoriesMeta ...
static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { List<String> basePath = getPathComponents(canonicalBaseFile); List<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); //if the roots aren't the same (i.e. different drives on a ...
@Test public void pathUtilTest8() { File[] roots = File.listRoots(); File basePath = new File(roots[0] + "some" + File.separatorChar); File relativePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar); String path = PathUtil.getRelativeFileInternal(b...
public static <E> void setMax(E obj, AtomicLongFieldUpdater<E> updater, long value) { for (; ; ) { long current = updater.get(obj); if (current >= value) { return; } if (updater.compareAndSet(obj, current, value)) { return; ...
@Test public void setMax() { setMax(8, 7); setMax(9, 9); setMax(10, 11); }
public static String maskPassword(String key, String value) { if (key.contains("PASSWORD")) { return "********"; } else { return value; } }
@Test public void testMaskedPasswords() { String noPassword = "SOME_VARIABLE"; String passwordAtTheEnd = "SOME_PASSWORD"; String passwordInTheMiddle = "SOME_PASSWORD_TO_THE_BIG_SECRET"; assertThat(Util.maskPassword(noPassword, "123456"), is("123456")); assertThat(Util.mask...
public static ValidateTopicResult validateTopic(String topic) { if (UtilAll.isBlank(topic)) { return new ValidateTopicResult(false, "The specified topic is blank."); } if (isTopicOrGroupIllegal(topic)) { return new ValidateTopicResult(false, "The specified topic contain...
@Test public void testTopicValidator_Pass() { TopicValidator.ValidateTopicResult res = TopicValidator.validateTopic("TestTopic"); assertThat(res.isValid()).isTrue(); assertThat(res.getRemark()).isEmpty(); }
@Override public Response execute(Request request, Options options) throws IOException { EnhancedPluginContext enhancedPluginContext = new EnhancedPluginContext(); HttpHeaders requestHeaders = new HttpHeaders(); request.headers().forEach((s, strings) -> requestHeaders.addAll(s, new ArrayList<>(strings))); URI...
@Test public void testExecute() throws IOException { // mock Client.class Client delegate = mock(Client.class); doAnswer(invocation -> { Request request = invocation.getArgument(0); if (request.httpMethod().equals(Request.HttpMethod.GET)) { return Response.builder().request(request).status(200).build()...
@Override public final int size() { // NOTE: because indices are on even numbers we cannot use the size util. /* * It is possible for a thread to be interrupted or reschedule between the read of the producer * and consumer indices, therefore protection is required to ensure size is within valid ran...
@Test(dataProvider = "empty") public void size_whenEmpty(MpscGrowableArrayQueue<Integer> queue) { assertThat(queue.size()).isEqualTo(0); }
public static Builder newBuilder() { return new AutoValue_SplunkEvent.Builder(); }
@Test public void testEquals() { String event = "test-event"; String host = "test-host"; String index = "test-index"; String source = "test-source"; String sourceType = "test-source-type"; Long time = 123456789L; JsonObject fields = new JsonObject(); fields.addProperty("test-key", "te...