focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void init(String keyId, String applicationKey, String exportService) throws BackblazeCredentialsException, IOException { // Fetch all the available buckets and use that to find which region the user is in ListBucketsResponse listBucketsResponse = null; String userRegion = null; // The Key ...
@Test public void testInitErrorCreatingBucket() throws BackblazeCredentialsException, IOException { createEmptyBucketList(); when(s3Client.createBucket(any(CreateBucketRequest.class))) .thenThrow(AwsServiceException.builder().build()); BackblazeDataTransferClient client = createDefaultClient(); ...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_contains_otherTypes() { // Expected value is Double assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3.0f)) .usingTolerance(DEFAULT_TOLERANCE) .contains(2.0); // Expected value is Integer assertThat(array(1.0f, 2.0f + 0.5f * DEFAULT_TOLERANCE, 3....
public static Dish createDish(Recipe recipe) { Map<Product, BigDecimal> calculatedRecipeToGram = new HashMap<>(); recipe.getIngredientsProportion().forEach(((product, proportion) -> { calculatedRecipeToGram.put(product, recipe.getBasePortionInGrams() .multiply(proportion....
@Test void testCreateDish() { }
public static <T extends Comparable<? super T>> T max(T[] numberArray) { return ArrayUtil.max(numberArray); }
@Test public void maxTest() { final int max = NumberUtil.max(5,4,3,6,1); assertEquals(6, max); }
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) { if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) { return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(), schemaDefinition.getSchema...
@Test public void testAllowNullSchema() throws JSONException { AvroSchema<Foo> avroSchema = AvroSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).build()); assertEquals(avroSchema.getSchemaInfo().getType(), SchemaType.AVRO); Schema.Parser parser = new Schema.Parser(); par...
@Override public void startBundle(Receiver... receivers) throws Exception { checkArgument( receivers.length == outputTupleTagsToReceiverIndices.size(), "unexpected number of receivers for DoFn"); this.receivers = receivers; if (hasStreamingSideInput) { // There is non-trivial setup ...
@Test @SuppressWarnings("AssertionFailureIgnored") public void testUnexpectedNumberOfReceivers() throws Exception { TestDoFn fn = new TestDoFn(Collections.emptyList()); DoFnInfo<?, ?> fnInfo = DoFnInfo.forFn( fn, WindowingStrategy.globalDefault(), null /* side inp...
public static TypeInformation<?> readTypeInfo(String typeString) { final List<Token> tokens = tokenize(typeString); final TokenConverter converter = new TokenConverter(typeString, tokens); return converter.convert(); }
@Test void testSyntaxError3() { assertThatThrownBy(() -> TypeStringUtils.readTypeInfo("ROW<f0 INVALID, f1 TINYINT>")) .isInstanceOf(ValidationException.class); // invalid type }
public static void checkTopic(String topic) throws MQClientException { if (UtilAll.isBlank(topic)) { throw new MQClientException("The specified topic is blank", null); } if (topic.length() > TOPIC_MAX_LENGTH) { throw new MQClientException( String.format("...
@Test public void testCheckTopic_HasIllegalCharacters() { String illegalTopic = "TOPIC&*^"; try { Validators.checkTopic(illegalTopic); failBecauseExceptionWasNotThrown(MQClientException.class); } catch (MQClientException e) { assertThat(e).hasMessageStarti...
public static byte[] generateScalarCallStub(Class<?> clazz, Method method) { final BatchCallEvaluateGenerator generator = new BatchCallEvaluateGenerator(clazz, method); generator.declareCallStubClazz(); generator.genBatchUpdateSingle(); generator.finish(); return generator.getByt...
@Test public void testScalarCallStub() throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { Class<?> clazz = ScalarAdd.class; final String genClassName = CallStubGenerator.CLAZZ_NAME.replace("/", "."); Method m = clazz.getMetho...
@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); ...
public static Duration parse(final String text) { try { final String[] parts = text.split("\\s"); if (parts.length != 2) { throw new IllegalArgumentException("Expected 2 tokens, got: " + parts.length); } final long size = parseNumeric(parts[0]); return buildDuration(size, part...
@Test public void shouldThrowOnUnknownTimeUnit() { // Then: // When: final Exception e = assertThrows( IllegalArgumentException.class, () -> parse("10 Green_Bottles") ); // Then: assertThat(e.getMessage(), containsString("Unknown time unit: 'GREEN_BOTTLES'")); }
@Override public void open(ExecutionContext ctx) throws Exception { super.open(ctx); equaliser = genRecordEqualiser.newInstance(ctx.getRuntimeContext().getUserCodeClassLoader()); }
@Test public void testWithGenerateUpdateBeforeAndStateTtl() throws Exception { ProcTimeMiniBatchDeduplicateKeepLastRowFunction func = createFunction(true, true, minTime.toMilliseconds()); OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createTestHarness(func); ...
public String toHumanReadableString() { if (humanReadableStr == null) { humanReadableStr = formatToHumanReadableString(); } return humanReadableStr; }
@Test void testToHumanReadableString() { assertThat(new MemorySize(0L).toHumanReadableString()).isEqualTo("0 bytes"); assertThat(new MemorySize(1L).toHumanReadableString()).isEqualTo("1 bytes"); assertThat(new MemorySize(1024L).toHumanReadableString()).isEqualTo("1024 bytes"); assert...
@Override public KsMaterializedQueryResult<WindowedRow> get( final GenericKey key, final int partition, final Range<Instant> windowStartBounds, final Range<Instant> windowEndBounds, final Optional<Position> position ) { try { final Instant lower = calculateLowerBound(windowSt...
@Test @SuppressWarnings("unchecked") public void shouldReturnValuesForOpenStartBounds_fetchAll() { // Given: final Range<Instant> start = Range.open( NOW, NOW.plusSeconds(10) ); final StateQueryResult<KeyValueIterator<Windowed<GenericKey>, ValueAndTimestamp<GenericRow>>> partitionResult...
@Override public long estimateCount(Sketch<?> sketch) { if (sketch instanceof NormalSketch) { return estimateCount((NormalSketch) sketch); } else { return estimateCount((SparseSketch) sketch); } }
@Test public void requireThatEstimateIsReasonableForFullNormalSketch() { HyperLogLogEstimator estimator = new HyperLogLogEstimator(10); NormalSketch sketch = new NormalSketch(10); // Fill sketch with 23 - highest possible zero prefix for precision 10. Arrays.fill(sketch.data(), (byte...
public CompletableFuture<QueryRouteResponse> queryRoute(ProxyContext ctx, QueryRouteRequest request) { CompletableFuture<QueryRouteResponse> future = new CompletableFuture<>(); try { validateTopic(request.getTopic()); List<org.apache.rocketmq.proxy.common.Address> addressList = t...
@Test public void testQueryRoute() throws Throwable { ConfigurationManager.getProxyConfig().setGrpcServerPort(8080); ArgumentCaptor<List<org.apache.rocketmq.proxy.common.Address>> addressListCaptor = ArgumentCaptor.forClass(List.class); when(this.messagingProcessor.getTopicRouteDataForProxy(...
public static String createApiFileUrl(String baseUrl, ExtensionVersion extVersion, String fileName) { var extension = extVersion.getExtension(); var namespaceName = extension.getNamespace().getName(); return createApiFileUrl(baseUrl, namespaceName, extension.getName(), extVersion.getTargetPlatfo...
@Test public void testCreateApiFileUrlUniversalTarget() throws Exception { var baseUrl = "http://localhost/"; assertThat(UrlUtil.createApiFileUrl(baseUrl, "foo", "bar", "universal", "0.1.0", "foo.bar-0.1.0.vsix")) .isEqualTo("http://localhost/api/foo/bar/0.1.0/file/foo.bar-0.1.0.vsix...
public void addToIfExists(EnvironmentVariableContext context) { if (context.hasProperty(getName())) { addTo(context); } }
@Test void addToIfExists_shouldNotAddEnvironmentVariableToEnvironmentVariableContextWhenVariableIDoesNotExistInContext() { final EnvironmentVariableContext environmentVariableContext = mock(EnvironmentVariableContext.class); final EnvironmentVariable environmentVariable = new EnvironmentVariable("fo...
@Override public void profilePushId(String pushTypeKey, String pushId) { }
@Test public void profilePushId() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } }); ...
@ApiOperation(value = "Update a user’s info", tags = { "Users" }, nickname = "updateUserInfo") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the user was found and the info has been updated."), @ApiResponse(code = 400, message = "Indicates the value was missing from t...
@Test public void testCreateUserInfoExceptions() throws Exception { User savedUser = null; try { User newUser = identityService.newUser("testuser"); newUser.setFirstName("Fred"); newUser.setLastName("McDonald"); newUser.setEmail("no-reply@flowable.org"...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void createForumTopic() { Integer color = 7322096; String emoji = "5434144690511290129"; CreateForumTopicResponse createResponse = bot.execute( new CreateForumTopic(forum, "test_topic").iconColor(color).iconCustomEmojiId(emoji) ); assertTrue(creat...
@Override public void handle(final RoutingContext routingContext) { // We must set it to allow chunked encoding if we're using http1.1 if (routingContext.request().version() == HttpVersion.HTTP_1_1) { routingContext.response().putHeader(TRANSFER_ENCODING, CHUNKED_ENCODING); } else if (routingContext...
@Test public void shouldSucceed_pullQuery() { // Given: final QueryStreamArgs req = new QueryStreamArgs("select * from foo;", Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap()); givenRequest(req); // When: handler.handle(routingContext); endHandler.getValue().hand...
public @Nullable DirectoryEntry get(Name name) { int index = bucketIndex(name, table.length); DirectoryEntry entry = table[index]; while (entry != null) { if (name.equals(entry.name())) { return entry; } entry = entry.next; } return null; }
@Test public void testGet() { assertThat(root.get(Name.simple("foo"))).isEqualTo(entry(root, "foo", dir)); assertThat(dir.get(Name.simple("foo"))).isNull(); assertThat(root.get(Name.simple("Foo"))).isNull(); }
public static boolean isBlank(String str) { return str == null || isEmpty(str.trim()); }
@Test public void testIsBlank() { assertTrue(StringUtil.isBlank(null)); assertTrue(StringUtil.isBlank("")); assertTrue(StringUtil.isBlank(" ")); assertFalse(StringUtil.isBlank("A String")); }
@Override public void decorate(final ShardingRule shardingRule, final ConfigurationProperties props, final SQLRewriteContext sqlRewriteContext, final RouteContext routeContext) { SQLStatementContext sqlStatementContext = sqlRewriteContext.getSqlStatementContext(); if (!isAlterOrDropIndexStatement(sq...
@Test void assertDecorateWhenInsertStatementNotContainsShardingTable() { SQLRewriteContext sqlRewriteContext = mock(SQLRewriteContext.class); InsertStatementContext insertStatementContext = mock(InsertStatementContext.class, RETURNS_DEEP_STUBS); when(insertStatementContext.getTablesContext()...
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull22() { // Arrange final int type = 27; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Heartbeat", actual); }
public double bps() { return bps; }
@Test public void testBps() { Bandwidth expected = Bandwidth.bps(one); assertEquals(one, expected.bps(), 0.0); }
public Optional<PluginMatchingResult<ServiceFingerprinter>> getServiceFingerprinter( NetworkService networkService) { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.SERVICE_FINGERPRINT)) .filter(entry -> hasMatchingServiceName(networkService,...
@Test public void getServiceFingerprinter_whenFingerprinterHasMatch_returnsMatch() { NetworkService httpService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtocol.TCP) .setServiceNa...
public static Map<String, Map<String, Field>> rowListToMap(List<Row> rowList, List<String> primaryKeyList) { // {value of primaryKey, value of all columns} Map<String, Map<String, Field>> rowMap = new HashMap<>(); for (Row row : rowList) { //ensure the order of column Lis...
@Test public void testRowListToMapWithMultipPk(){ List<String> primaryKeyList = new ArrayList<>(); primaryKeyList.add("id1"); primaryKeyList.add("id2"); List<Row> rows = new ArrayList<>(); Field field1 = new Field("id1", 1, "1"); Field field11 = new Field("id2", 1, "...
public static <T> Partition<T> of( int numPartitions, PartitionWithSideInputsFn<? super T> partitionFn, Requirements requirements) { Contextful ctfFn = Contextful.fn( (T element, Contextful.Fn.Context c) -> partitionFn.partitionFor(element, numPartitions, c), ...
@Test @Category(NeedsRunner.class) public void testPartitionFnOutputTypeDescriptorRaw() throws Exception { PCollectionList<String> output = pipeline.apply(Create.of("hello")).apply(Partition.of(1, (element, numPartitions) -> 0)); thrown.expect(CannotProvideCoderException.class); pipeline.getCo...
public static String validateSubject(String claimName, String claimValue) throws ValidateException { return validateString(claimName, claimValue); }
@Test public void testValidateSubject() { String expected = "jdoe"; String actual = ClaimValidationUtils.validateSubject("sub", expected); assertEquals(expected, actual); }
@Override public boolean next() throws SQLException { if (getCurrentQueryResult().next()) { return true; } if (!queryResults.hasNext()) { return false; } setCurrentQueryResult(queryResults.next()); boolean hasNext = getCurrentQueryResult().next...
@Test void assertNextForResultSetsAllEmpty() throws SQLException { List<QueryResult> queryResults = Arrays.asList(mock(QueryResult.class, RETURNS_DEEP_STUBS), mock(QueryResult.class, RETURNS_DEEP_STUBS), mock(QueryResult.class, RETURNS_DEEP_STUBS)); ShardingDQLResultMerger resultMerger = new Shardin...
public Command create( final ConfiguredStatement<? extends Statement> statement, final KsqlExecutionContext context) { return create(statement, context.getServiceContext(), context); }
@Test public void shouldValidateResumeQuery() { // Given: givenResume(); // When: commandFactory.create(configuredStatement, executionContext); // Then: verify(executionContext).getPersistentQuery(QUERY_ID); verify(query1).resume(); }
@Override public Optional<Code> remove(String code) { return Optional.ofNullable(store.asMap().remove(code)); }
@Test void remove_nonExisting() { Cache<String, Code> cache = Caffeine.newBuilder().build(); var sut = new CaffeineCodeRepo(cache); // when var c1 = sut.remove("x"); // then assertTrue(c1.isEmpty()); }
protected void handleInboundMessage(Object msg) { inboundMessages().add(msg); }
@Test public void testHandleInboundMessage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); EmbeddedChannel channel = new EmbeddedChannel() { @Override protected void handleInboundMessage(Object msg) { latch.countDown(); ...
public static void checkArgument(boolean expression, Object errorMessage) { if (Objects.isNull(errorMessage)) { throw new IllegalArgumentException("errorMessage cannot be null."); } if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); ...
@Test void testCheckArgument3Args1false3null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG, null); }); }
@Override public boolean addTopicConfig(final String topicName, final Map<String, ?> overrides) { final ConfigResource resource = new ConfigResource(ConfigResource.Type.TOPIC, topicName); final Map<String, String> stringConfigs = toStringConfigs(overrides); try { final Map<String, String> existing...
@Test public void shouldRetryAddingTopicConfig() { // Given: givenTopicConfigs( "peter", overriddenConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "12345"), defaultConfigEntry(TopicConfig.COMPRESSION_TYPE_CONFIG, "snappy") ); final Map<String, ?> overrides = ImmutableMap.of( ...
@CanIgnoreReturnValue public final Ordered containsExactly() { return containsExactlyEntriesIn(ImmutableMap.of()); }
@Test public void containsExactlyExtraKeyAndMissingKey_failsWithSameToStringForKeys() { expectFailureWhenTestingThat(ImmutableMap.of(1L, "jan", 2, "feb")) .containsExactly(1, "jan", 2, "feb"); assertFailureKeys( "missing keys", "for key", "expected value", "unexpected k...
public static HostAndPort toHostAndPort(NetworkEndpoint networkEndpoint) { switch (networkEndpoint.getType()) { case IP: return HostAndPort.fromHost(networkEndpoint.getIpAddress().getAddress()); case IP_PORT: return HostAndPort.fromParts( networkEndpoint.getIpAddress().getAdd...
@Test public void toHostAndPort_withIpAddress_returnsHostWithIp() { NetworkEndpoint ipV4Endpoint = NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.IP) .setIpAddress( IpAddress.newBuilder().setAddress("1.2.3.4").setAddressFamily(AddressFamily.IPV4)) ...
public static int getVCores(Configuration conf) { if (!isHardwareDetectionEnabled(conf)) { return getConfiguredVCores(conf); } // is this os for which we can determine cores? ResourceCalculatorPlugin plugin = ResourceCalculatorPlugin.getResourceCalculatorPlugin(null, conf); if (plugin ...
@Test public void testGetVCores() { ResourceCalculatorPlugin plugin = new TestResourceCalculatorPlugin(); YarnConfiguration conf = new YarnConfiguration(); conf.setFloat(YarnConfiguration.NM_PCORES_VCORES_MULTIPLIER, 1.25f); int ret = NodeManagerHardwareUtils.getVCores(plugin, conf); Assert.ass...
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { SQLStatement dalStatement = sqlStatementContext.getSq...
@Test void assertMergeForShowCreateTableStatement() throws SQLException { DALStatement dalStatement = new MySQLShowCreateTableStatement(); SQLStatementContext sqlStatementContext = mockSQLStatementContext(dalStatement); ShardingDALResultMerger resultMerger = new ShardingDALResultMerger(Defau...
@Override public HttpResponse validateAndCreate(@JsonBody JSONObject request) { String accessToken = (String) request.get("accessToken"); if(accessToken == null){ throw new ServiceException.BadRequestException("accessToken is required"); } accessToken = accessToken.trim(...
@Test public void validateAndCreate() throws Exception { validateAndCreate("12345"); }
@Override public Map<String, String> discoverLocalMetadata() { if (memberMetadata.isEmpty()) { memberMetadata.put(PartitionGroupMetaData.PARTITION_GROUP_ZONE, gcpClient.getAvailabilityZone()); } return memberMetadata; }
@Test public void discoverLocalMetadata() { // given given(gcpClient.getAvailabilityZone()).willReturn(ZONE); // when Map<String, String> result1 = gcpDiscoveryStrategy.discoverLocalMetadata(); Map<String, String> result2 = gcpDiscoveryStrategy.discoverLocalMetadata(); ...
public ClusterStateBundle.FeedBlock inferContentClusterFeedBlockOrNull(ContentCluster cluster) { if (!feedBlockEnabled) { return null; } var nodeInfos = cluster.getNodeInfos(); var exhaustions = enumerateNodeResourceExhaustionsAcrossAllNodes(nodeInfos); if (exhaustion...
@Test void no_feed_block_returned_when_no_resources_lower_than_limit() { var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8))); var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.49), usage("memory", 0.79)), forNode(2, usa...
public Map<String, Object> getContext(Map<String, Object> modelMap, Class<? extends SparkController> controller, String viewName) { Map<String, Object> context = new HashMap<>(modelMap); context.put("currentGoCDVersion", CurrentGoCDVersion.getInstance().getGocdDistVersion()); context.put("railsA...
@Test void shouldShowAnalyticsDashboard() { Map<String, Object> modelMap = new HashMap<>(); when(securityService.isUserAdmin(any(Username.class))).thenReturn(true); CombinedPluginInfo combinedPluginInfo = new CombinedPluginInfo(analyticsPluginInfo()); when(pluginInfoFinder.allPluginI...
@Override public void validateSmsCode(SmsCodeValidateReqDTO reqDTO) { validateSmsCode0(reqDTO.getMobile(), reqDTO.getCode(), reqDTO.getScene()); }
@Test public void validateSmsCode_success() { // 准备参数 SmsCodeValidateReqDTO reqDTO = randomPojo(SmsCodeValidateReqDTO.class, o -> { o.setMobile("15601691300"); o.setScene(randomEle(SmsSceneEnum.values()).getScene()); }); // mock 数据 SqlConstants.init(Db...
Map<Long, Map<Integer, InformationElementDefinition>> buildPenToIedsMap(JsonNode jsonNode) { final long enterpriseNumber = jsonNode.get("enterprise_number").asLong(); ImmutableMap.Builder<Integer, InformationElementDefinition> iedBuilder = ImmutableMap.builder(); jsonNode.path("information_elem...
@Test public void buildPenToIedsMap() throws IOException { // Standard Definition file InformationElementDefinitions definitions = new InformationElementDefinitions( Resources.getResource("ipfix-iana-elements.json") ); // Load the custom definition file String...
public void close() { try { httpTlsClient.close(); } catch (Exception ignore) { // Ignore } try { httpNonTlsClient.close(); } catch (Exception ignore) { // Ignore } if (vertx != null && ownedVertx) { vertx.close(); } }
@Test public void shouldFailToStartClientRequestWithNullKeystorePassword() throws Exception { ksqlClient.close(); stopServer(); // Given: startServerWithTls(); // When: final KsqlRestClientException e = assertThrows( KsqlRestClientException.class, () -> startClientWithTlsAndT...
public static void processEnvVariables(Map<String, String> inputProperties) { processEnvVariables(inputProperties, System.getenv()); }
@Test void jsonEnvVariablesShouldNotOverrideGenericEnv() { var inputProperties = new HashMap<String, String>(); EnvironmentConfig.processEnvVariables(inputProperties, Map.of("SONAR_SCANNER_FOO", "value1", "SONAR_SCANNER_JSON_PARAMS", "{\"sonar.scanner.foo\":\"should not override\", \"key2\":\"va...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testCoordinatedSerializationException() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStreamSource<Integer> source = env.fromData(1, 2, 3); env.addOperator( new OneInputTransformation<>( source....
public boolean isAbsolute() { return isUriPathAbsolute(); }
@Test (timeout = 30000) public void testIsAbsolute() { assertTrue(new Path("/").isAbsolute()); assertTrue(new Path("/foo").isAbsolute()); assertFalse(new Path("foo").isAbsolute()); assertFalse(new Path("foo/bar").isAbsolute()); assertFalse(new Path(".").isAbsolute()); if (Path.WINDOWS) { ...
public Promise<T> fulfillInAsync(final Callable<T> task, Executor executor) { executor.execute(() -> { try { fulfill(task.call()); } catch (Exception ex) { fulfillExceptionally(ex); } }); return this; }
@Test void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask() throws InterruptedException, ExecutionException { promise.fulfillInAsync(new NumberCrunchingTask(), executor); assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, promise.get()); assertTrue(promise.isDone()); assertFalse(promi...
@VisibleForTesting static BlobKey createKey(BlobType type) { if (type == PERMANENT_BLOB) { return new PermanentBlobKey(); } else { return new TransientBlobKey(); } }
@Test void testToFromStringTransientKey() { testToFromString(BlobKey.createKey(TRANSIENT_BLOB)); }
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testReadCommittedWithCompactedTopic() { buildFetcher(OffsetResetStrategy.EARLIEST, new StringDeserializer(), new StringDeserializer(), Integer.MAX_VALUE, IsolationLevel.READ_COMMITTED); ByteBuffer buffer = ByteBuffer.allocate(1024); long pid1 = 1L; ...
public DLQEntry pollEntry(long timeout) throws IOException, InterruptedException { byte[] bytes = pollEntryBytes(timeout); if (bytes == null) { return null; } return DLQEntry.deserialize(bytes); }
@Test public void testReaderFindSegmentHoleAfterSimulatingRetentionPolicyClean() throws IOException, InterruptedException { final int eventsPerSegment = prepareFilledSegmentFiles(3); assertEquals(319, eventsPerSegment); int remainingEventsInSegment = eventsPerSegment; try (DeadLett...
public void setMaxFetchKBSec(int rate) { kp.put("maxFetchKBSec",rate); }
@Test public void testMaxFetchKBSec() throws Exception { CrawlURI curi = makeCrawlURI("http://localhost:7777/200k"); fetcher().setMaxFetchKBSec(100); // if the wire logger is enabled, it can slow things down enough to make // this test failed, so disable it temporarily ...
public PrimitiveValue maxValue() { return maxValue; }
@Test void shouldReturnDefaultMaxValueWhenSpecified() throws Exception { final String testXmlString = "<types>" + " <type name=\"testTypeDefaultCharMaxValue\" primitiveType=\"char\"/>" + "</types>"; final Map<String, Type> map = parseTestXmlWithMap("/types...
@Override public void destroy() { super.destroy(); try { ExecutorUtil.cancelScheduledFuture(cleanFuture); } catch (Throwable t) { logger.warn(REGISTRY_SOCKET_EXCEPTION, "", "", t.getMessage(), t); } try { multicastSocket.leaveGroup(multicas...
@Test void testDestroy() { MulticastSocket socket = registry.getMulticastSocket(); assertFalse(socket.isClosed()); // then destroy, the multicast socket will be closed registry.destroy(); socket = registry.getMulticastSocket(); assertTrue(socket.isClosed()); }
public String toBaseMessageIdString(Object messageId) { if (messageId == null) { return null; } else if (messageId instanceof String) { String stringId = (String) messageId; // If the given string has a type encoding prefix, // we need to escape it as an ...
@Test public void testToBaseMessageIdStringThrowsIAEWithUnexpectedType() { try { messageIdHelper.toBaseMessageIdString(new Object()); fail("expected exception not thrown"); } catch (IllegalArgumentException iae) { // expected } }
public void evaluate(List<AuthorizationContext> contexts) { if (CollectionUtils.isEmpty(contexts)) { return; } contexts.forEach(this.authorizationStrategy::evaluate); }
@Test public void evaluate6() { if (MixAll.isMac()) { return; } this.authConfig.setAuthorizationWhitelist("10"); this.evaluator = new AuthorizationEvaluator(this.authConfig); Subject subject = Subject.of("User:test"); Resource resource = Resource.ofTopic(...
public static Env transformEnv(String envName) { final String envWellFormName = getWellFormName(envName); if (Env.exists(envWellFormName)) { return Env.valueOf(envWellFormName); } // cannot be found or blank name return Env.UNKNOWN; }
@Test public void testTransformEnvNotExist() { assertEquals(Env.UNKNOWN, Env.transformEnv("notexisting")); assertEquals(Env.LOCAL, Env.transformEnv("LOCAL")); }
@Override public String put(String key, String value) { if (value == null) throw new IllegalArgumentException("Null value not allowed as an environment variable: " + key); return super.put(key, value); }
@Test public void overrideOrderCalculatorMultiple() { EnvVars env = new EnvVars(); EnvVars overrides = new EnvVars(); overrides.put("A", "Noreference"); overrides.put("B", "${A}"); overrides.put("C", "${A}${B}"); OverrideOrderCalculator calc = new OverrideOrderCalcul...
public static <T> ClassPluginDocumentation<T> of(JsonSchemaGenerator jsonSchemaGenerator, RegisteredPlugin plugin, Class<? extends T> cls, Class<T> baseCls) { return new ClassPluginDocumentation<>(jsonSchemaGenerator, plugin, cls, baseCls, null); }
@SuppressWarnings("unchecked") @Test void trigger() throws URISyntaxException { Helpers.runApplicationContext(throwConsumer((applicationContext) -> { JsonSchemaGenerator jsonSchemaGenerator = applicationContext.getBean(JsonSchemaGenerator.class); PluginScanner pluginScanner = ne...
@Override public boolean cleanExpiredConsumerQueue( String cluster) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, MQClientException, InterruptedException { return defaultMQAdminExtImpl.cleanExpiredConsumerQueue(cluster); }
@Test public void testCleanExpiredConsumerQueue() throws InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException { boolean result = defaultMQAdminExt.cleanExpiredConsumerQueue("default-cluster"); assertThat(result).isFalse(); }
@Override public ServerId create() { return ServerId.of(computeDatabaseId(), serverIdGenerator.generate()); }
@Test public void create_from_scratch_fails_with_ISE_if_JDBC_property_not_set() { expectMissingJdbcUrlISE(() -> underTest.create()); }
@Override public CucumberOptionsAnnotationParser.CucumberOptions getOptions(Class<?> clazz) { CucumberOptions annotation = clazz.getAnnotation(CucumberOptions.class); if (annotation != null) { return new JunitCucumberOptions(annotation); } warnWhenTestNGCucumberOptionsAre...
@Test void testObjectFactory() { io.cucumber.core.options.CucumberOptionsAnnotationParser.CucumberOptions options = this.optionsProvider .getOptions(ClassWithCustomObjectFactory.class); assertNotNull(options); assertEquals(TestObjectFactory.class, options.objectFactory()); ...
public static File getPluginFile(final String path) { String pluginPath = getPluginPath(path); return new File(pluginPath); }
@Test public void testGetPluginPathByCustomPath() { File jarFile = ShenyuPluginPathBuilder.getPluginFile("/testpath"); assertNotNull(jarFile); }
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldThrowOnMapOfNullValues() { // Given: Expression expression = new CreateMapExpression( ImmutableMap.of( new StringLiteral("foo"), new NullLiteral() ) ); // When: final Exception e = assertThrows( KsqlException.class, (...
@Override public String ping(RedisClusterNode node) { return execute(node, RedisCommands.PING); }
@Test public void testClusterPing() { RedisClusterNode master = getFirstMaster(); String res = connection.ping(master); assertThat(res).isEqualTo("PONG"); }
public static boolean isNotEmpty(Collection<?> collection) { return !isEmpty(collection); }
@SuppressWarnings("ConstantValue") @Test public void isNotEmptyTest() { assertFalse(CollUtil.isNotEmpty((Collection<?>) null)); }
public static void setPort(int port) { XID.port = port; }
@Test public void testSetPort() { XID.setPort(8080); assertThat(XID.getPort()).isEqualTo(8080); }
@POST @Path("getByPath") @ZeppelinApi public Response getNoteByPath(String message, @QueryParam("reload") boolean reload) throws IOException { // notePath may contains special character like space. // it should be in http body instead of in url // to avoid problem of ur...
@Test void testGetNoteByPath() throws IOException { LOG.info("Running testGetNoteByPath"); String note1Id = null; try { String notePath = "dir1/note1"; note1Id = notebook.createNote(notePath, anonymous); notebook.processNote(note1Id, note1 -> { n...
@Override public CodegenTableDO getCodegenTable(Long id) { return codegenTableMapper.selectById(id); }
@Test public void testGetCodegenTable() { // mock 数据 CodegenTableDO tableDO = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(tableDO); // 准备参数 Long id = tableDO.getId(); // 调用 CodegenTableDO res...
public void completeTx(SendRequest req) throws InsufficientMoneyException, CompletionException { lock.lock(); try { checkArgument(!req.completed, () -> "given SendRequest has already been completed"); log.info("Completing send tx with {} outputs totalling {} ...
@Test public void opReturnOneOutputWithValueTest() throws Exception { // Tests basic send of transaction with one output that destroys coins and has an OP_RETURN. receiveATransaction(wallet, myAddress); Transaction tx = new Transaction(); Coin messagePrice = CENT; Script scri...
@Override public long checksum() { if (this.checksum == 0) { this.checksum = CrcUtil.crc64(AsciiStringUtil.unsafeEncode(toString())); } return this.checksum; }
@Test public void testChecksum() { PeerId peer = new PeerId("192.168.1.1", 8081, 1); long c = peer.checksum(); assertTrue(c != 0); assertEquals(c, peer.checksum()); }
public DirectoryEntry lookUp( File workingDirectory, JimfsPath path, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); DirectoryEntry result = lookUp(workingDirectory, path, options, 0); if (result == null) { // an intermediate file in the path...
@Test public void testLookup_absolute_nonDirectoryIntermediateFile() throws IOException { try { lookup("/work/one/eleven/twelve"); fail(); } catch (NoSuchFileException expected) { } try { lookup("/work/one/eleven/twelve/thirteen/fourteen"); fail(); } catch (NoSuchFileExcep...
public static InternalLogger getInstance(Class<?> clazz) { return getInstance(clazz.getName()); }
@Test public void testInfoWithException() { final InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.info("a", e); verify(mockLogger).info("a", e); }
@Override public IMetaverseNode createResourceNode( IExternalResourceInfo resource ) throws MetaverseException { return createFileNode( resource.getName(), getDescriptor() ); }
@Test public void testCreateResourceNode() throws Exception { IExternalResourceInfo res = mock( IExternalResourceInfo.class ); when( res.getName() ).thenReturn( "file:///Users/home/tmp/xyz.xml" ); IMetaverseNode resourceNode = analyzer.createResourceNode( res ); assertNotNull( resourceNode ); asse...
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) { if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) { return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(), schemaDefinition.getSchema...
@Test public void testNotAllowNullSchema() throws JSONException { AvroSchema<Foo> avroSchema = AvroSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).withAlwaysAllowNull(false).build()); assertEquals(avroSchema.getSchemaInfo().getType(), SchemaType.AVRO); Schema.Parser parser = ne...
@Override public void isNotEqualTo(@Nullable Object expected) { super.isNotEqualTo(expected); }
@Test public void isNotEqualTo_WithoutToleranceParameter_Success_Shorter() { assertThat(array(2.2d, 3.3d)).isNotEqualTo(array(2.2d)); }
protected boolean isListEmpty(ArrayNode json) { for (JsonNode node : json) { if (!isNodeEmpty(node)) { return false; } } return true; }
@Test public void isListEmpty_noNode() { ArrayNode json = new ArrayNode(factory); assertThat(expressionEvaluator.isListEmpty(json)).isTrue(); }
@Override public KeyValueIterator<Windowed<K>, V> backwardFetch(final K key) { Objects.requireNonNull(key, "key cannot be null"); return new MeteredWindowedKeyValueIterator<>( wrapped().backwardFetch(keyBytes(key)), fetchSensor, iteratorDurationSensor, ...
@Test public void shouldThrowNullPointerOnBackwardFetchIfKeyIsNull() { setUpWithoutContext(); assertThrows(NullPointerException.class, () -> store.backwardFetch(null)); }
@Override public BroadcastRuleConfiguration swapToObject(final YamlBroadcastRuleConfiguration yamlConfig) { return new BroadcastRuleConfiguration(yamlConfig.getTables()); }
@Test void assertSwapToObject() { YamlBroadcastRuleConfiguration yamlRuleConfig = new YamlBroadcastRuleConfiguration(); yamlRuleConfig.getTables().add("t_address"); YamlBroadcastRuleConfigurationSwapper swapper = new YamlBroadcastRuleConfigurationSwapper(); BroadcastRuleConfiguration...
@Override public void setFlushNetworkPolicy(int networkType) { }
@Test public void setFlushNetworkPolicy() { mSensorsAPI.setFlushNetworkPolicy(SensorsDataAPI.NetworkType.TYPE_5G); }
@Override public PipelineConfig get(int i) { if (i < 0) throw new IndexOutOfBoundsException(); int start = 0; for (PipelineConfigs part : this.parts) { int end = start + part.size(); if (i < end) return part.get(i - start); sta...
@Test public void shouldReturnPipelinesInOrder() { PipelineConfig pipeline1 = PipelineConfigMother.pipelineConfig("pipeline1"); PipelineConfig pipeline3 = PipelineConfigMother.pipelineConfig("pipeline3"); PipelineConfig pipeline5 = PipelineConfigMother.pipelineConfig("pipeline5"); Pi...
@Nullable @Override public Message decode(@Nonnull RawMessage rawMessage) { final byte[] payload = rawMessage.getPayload(); final JsonNode event; try { event = objectMapper.readTree(payload); if (event == null || event.isMissingNode()) { throw new ...
@Test public void decodeMessagesHandlesGenericBeatWithCloudDigitalOcean() throws Exception { final Message message = codec.decode(messageFromJson("generic-with-cloud-digital-ocean.json")); assertThat(message).isNotNull(); assertThat(message.getMessage()).isEqualTo("-"); assertThat(me...
public Timestamp insert(PartitionMetadata row) { final TransactionResult<Void> transactionResult = runInTransaction(transaction -> transaction.insert(row), "InsertsPartitionMetadata"); return transactionResult.getCommitTimestamp(); }
@Test public void testInsert() { when(databaseClient.readWriteTransaction(anyObject())).thenReturn(readWriteTransactionRunner); when(databaseClient.readWriteTransaction()).thenReturn(readWriteTransactionRunner); when(readWriteTransactionRunner.run(any())).thenReturn(null); when(readWriteTransactionRun...
public static HoodieWriteConfig.Builder newBuilder() { return new Builder(); }
@Test public void testAutoAdjustCleanPolicyForNonBlockingConcurrencyControl() { TypedProperties props = new TypedProperties(); props.setProperty(HoodieTableConfig.TYPE.key(), HoodieTableType.MERGE_ON_READ.name()); props.setProperty(KeyGeneratorOptions.RECORDKEY_FIELD_NAME.key(), "uuid"); HoodieWriteCo...
public <T> void notifyReadyAsync(Callable<T> callable, BiConsumer<T, Throwable> handler) { workerExecutor.execute( () -> { try { T result = callable.call(); executorToNotify.execute(() -> handler.accept(result, null)); ...
@Test public void testBasic() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); AtomicInteger result = new AtomicInteger(0); notifier.notifyReadyAsync( () -> 1234, (v, e) -> { result.set(v); lat...
List<Cell> adjacentCells(int y, int x) { var adjacent = new ArrayList<Cell>(); if (y == 0) { adjacent.add(this.cells[1][x]); } if (x == 0) { adjacent.add(this.cells[y][1]); } if (y == cells.length - 1) { adjacent.add(this.cells[cells.length - 2][x]); } if (x == cells.le...
@Test void adjacentCellsTest() { var cg = new CandyGame(3, new CellPool(9)); var arr1 = cg.adjacentCells(0, 0); var arr2 = cg.adjacentCells(1, 2); var arr3 = cg.adjacentCells(1, 1); assertTrue(arr1.size() == 2 && arr2.size() == 3 && arr3.size() == 4); }
public FEELFnResult<Boolean> invoke(@ParameterName( "point" ) Comparable point, @ParameterName( "range" ) Range range) { if ( point == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "point", "cannot be null")); } if ( range == null ) { ret...
@Test void invokeParamSingleAndRange() { FunctionTestUtil.assertResult( finishesFunction.invoke( "f", new RangeImpl( Range.RangeBoundary.CLOSED, "a", "f", Range.RangeBoundary.CLOSED )), Boolean.TRUE ); FunctionTestUtil.assertResult( finishesFunction.invoke( "a", ...
public static Schema getPinotSchemaFromPinotSchemaWithComplexTypeHandling(Descriptors.Descriptor protoSchema, @Nullable Map<String, FieldSpec.FieldType> fieldTypeMap, @Nullable TimeUnit timeUnit, List<String> fieldsToUnnest, String delimiter) { Schema pinotSchema = new Schema(); for (Descriptors.Fi...
@Test(dataProvider = "scalarCases") public void testExtractSchemaWithCompositeTypeHandling( String fieldName, FieldSpec.DataType type, boolean isSingleValue) { Descriptors.Descriptor desc = CompositeTypes.CompositeMessage.getDescriptor(); FieldSpec schema = ProtoBufSchemaUtils.getPinotSchemaFromPinotSch...
public static KTableHolder<GenericKey> build( final KGroupedTableHolder groupedTable, final TableAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedTable, aggregate, buildContext, ...
@Test public void shouldBuildAggregateCorrectly() { // When: final KTableHolder<GenericKey> result = aggregate.build(planBuilder, planInfo); // Then: assertThat(result.getTable(), is(aggregatedWithResults)); final InOrder inOrder = Mockito.inOrder(groupedTable, aggregated, aggregatedWithResults);...
public static String prettyMethodSignature(ClassSymbol origin, MethodSymbol m) { StringBuilder sb = new StringBuilder(); if (m.isConstructor()) { Name name = m.owner.enclClass().getSimpleName(); if (name.isEmpty()) { // use the superclass name of anonymous classes name = m.owner.encl...
@Test public void prettyMethodSignature() throws Exception { FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix()); Path source = fileSystem.getPath("Test.java"); Files.write( source, ImmutableList.of( "class Test {", // " void f() {", " ...
static void encodeSubscriptionRemoval( final UnsafeBuffer encodingBuffer, final int offset, final int captureLength, final int length, final String channel, final int streamId, final long id) { int encodedLength = encodeLogHeader(encodingBuffer, offset...
@Test void encodeSubscriptionRemovalShouldTruncateChannelIfItExceedsMaxMessageLength() { final char[] data = new char[MAX_EVENT_LENGTH * 3 + 5]; fill(data, 'a'); final int offset = 0; final int length = SIZE_OF_INT * 2 + SIZE_OF_LONG + data.length; final int captureLength...
@Override public Stream<HoodieBaseFile> getAllBaseFiles(String partitionPath) { return execute(partitionPath, preferredView::getAllBaseFiles, (path) -> getSecondaryView().getAllBaseFiles(path)); }
@Test public void testGetAllBaseFiles() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; String partitionPath = "/table2"; when(primary.getAllBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getAllBaseFiles(partitionPath); assertE...
public static Builder builder() { return new Builder(); }
@Test public void testFailures() { assertThatThrownBy(() -> LoadTableResponse.builder().build()) .isInstanceOf(NullPointerException.class) .hasMessage("Invalid metadata: null"); }
public BufferPool get() { WeakReference<BufferPool> ref = threadLocal.get(); if (ref == null) { BufferPool pool = bufferPoolFactory.create(serializationService); ref = new WeakReference<>(pool); strongReferences.put(Thread.currentThread(), pool); threadLoc...
@Test public void get_whenSameThread_samePoolInstance() { BufferPool pool1 = bufferPoolThreadLocal.get(); BufferPool pool2 = bufferPoolThreadLocal.get(); assertSame(pool1, pool2); }
@Override public List<DictDataDO> getDictDataList(Integer status, String dictType) { List<DictDataDO> list = dictDataMapper.selectListByStatusAndDictType(status, dictType); list.sort(COMPARATOR_TYPE_AND_SORT); return list; }
@Test public void testGetDictDataList() { // mock 数据 DictDataDO dictDataDO01 = randomDictDataDO().setDictType("yunai").setSort(2) .setStatus(CommonStatusEnum.ENABLE.getStatus()); dictDataMapper.insert(dictDataDO01); DictDataDO dictDataDO02 = randomDictDataDO().setDict...
@Override public MetadataStore create(String metadataURL, MetadataStoreConfig metadataStoreConfig, boolean enableSessionWatcher) throws MetadataStoreException { return new LocalMemoryMetadataStore(metadataURL, metadataStoreConfig); }
@Test public void testNotifyEvent() throws Exception { TestMetadataEventSynchronizer sync = new TestMetadataEventSynchronizer(); @Cleanup MetadataStore store1 = MetadataStoreFactory.create("memory:local", MetadataStoreConfig.builder().synchronizer(sync).build()); Str...