focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void storeAll(Map<K, V> map) { long startNanos = Timer.nanos(); try { delegate.storeAll(map); } finally { storeAllProbe.recordValue(Timer.nanosElapsed(startNanos)); } }
@Test public void storeAll() { Map<String, String> values = new HashMap<>(); values.put("1", "value1"); values.put("2", "value2"); cacheStore.storeAll(values); verify(delegate).storeAll(values); assertProbeCalledOnce("storeAll"); }
public List<R> scanForResourcesPath(Path resourcePath) { requireNonNull(resourcePath, "resourcePath must not be null"); List<R> resources = new ArrayList<>(); pathScanner.findResourcesForPath( resourcePath, canLoad, processResource(DEFAULT_PACKAGE_NAME, NULL_F...
@Test void scanForResourcesDirectory() { File file = new File("src/test/resources/io/cucumber/core/resource"); List<URI> resources = resourceScanner.scanForResourcesPath(file.toPath()); assertThat(resources, containsInAnyOrder( new File("src/test/resources/io/cucumber/core/resour...
public static boolean getBoolean(String key, boolean def) { String value = get(key); if (value == null) { return def; } value = value.trim().toLowerCase(); if (value.isEmpty()) { return def; } if ("true".equals(value) || "yes".equals(valu...
@Test public void testGetBooleanDefaultValueWithPropertyNull() { assertTrue(SystemPropertyUtil.getBoolean("key", true)); assertFalse(SystemPropertyUtil.getBoolean("key", false)); }
public String getStringArgument(String option) { return getStringArgument(option, null); }
@Test public void testGetStringArgument() throws ParseException { String[] args = {"--scan", "missing.file", "--artifactoryUsername", "blue42", "--project", "test"}; CliParser instance = new CliParser(getSettings()); try { instance.parse(args); Assert.fail("invalid ...
@Override public ChannelBuffer copy() { return copy(readerIndex, readableBytes()); }
@Test void copyBoundaryCheck4() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(buffer.capacity(), 1)); }
@Bean("CiConfiguration") public CiConfiguration provide(Configuration configuration, CiVendor[] ciVendors) { boolean disabled = configuration.getBoolean(PROP_DISABLED).orElse(false); if (disabled) { return new EmptyCiConfiguration(); } List<CiVendor> detectedVendors = Arrays.stream(ciVendors) ...
@Test public void empty_configuration_if_no_ci_vendors() { CiConfiguration CiConfiguration = underTest.provide(cli.asConfig(), new CiVendor[0]); assertThat(CiConfiguration.getScmRevision()).isEmpty(); }
@Override public String getIdentifier(UserInfo userInfo, ClientDetailsEntity client) { String sectorIdentifier = null; if (!Strings.isNullOrEmpty(client.getSectorIdentifierUri())) { UriComponents uri = UriComponentsBuilder.fromUriString(client.getSectorIdentifierUri()).build(); sectorIdentifier = uri.getHo...
@Test(expected = IllegalArgumentException.class) public void testGetIdentifier_multipleRedirectError() { String pairwise5 = service.getIdentifier(userInfoRegular, pairwiseClient5); }
public void addOtherTesseractConfig(String key, String value) { if (key == null) { throw new IllegalArgumentException("key must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } Matcher m = ALLOWABLE_OTH...
@Test public void testBadOtherValueControl() { TesseractOCRConfig config = new TesseractOCRConfig(); assertThrows(IllegalArgumentException.class, () -> { config.addOtherTesseractConfig("bad", "bad\u0001bad"); }); }
public URI getHttpPublishUri() { if (httpPublishUri == null) { final URI defaultHttpUri = getDefaultHttpUri(); LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri); return defaultHttpUri; } else { final InetAddress inetAddress = to...
@Test public void testHttpPublishUriIPv6WildcardKeepsPath() throws RepositoryException, ValidationException { final Map<String, String> properties = ImmutableMap.of( "http_bind_address", "[::]:9000", "http_publish_uri", "http://[::]:9000/api/"); jadConfig.setReposito...
@Override public Schema getSourceSchema() { if (schema == null) { try { Schema.Parser parser = new Schema.Parser(); schema = parser.parse(schemaString); } catch (Exception e) { throw new HoodieSchemaException("Failed to parse schema: " + schemaString, e); } } ret...
@Test public void validateOneOfSchemaGeneration() throws IOException { TypedProperties properties = new TypedProperties(); properties.setProperty(ProtoClassBasedSchemaProviderConfig.PROTO_SCHEMA_CLASS_NAME.key(), WithOneOf.class.getName()); ProtoClassBasedSchemaProvider protoToAvroSchemaProvider = new Pro...
protected void subscribeOverride(final ConsumerConfig config, ConfigListener listener) { try { if (overrideObserver == null) { // 初始化 overrideObserver = new ZookeeperOverrideObserver(); } overrideObserver.addConfigListener(config, listener); final ...
@Test public void testOverrideObserver() throws InterruptedException { ConsumerConfig<?> consumerConfig = new ConsumerConfig(); consumerConfig.setInterfaceId(TEST_SERVICE_NAME) .setUniqueId("unique123Id") .setApplication(new ApplicationConfig().setAppName("test-server")) ...
@Deprecated public static MaskTree decodeMaskUriFormat(StringBuilder toparse) throws IllegalMaskException { return decodeMaskUriFormat(toparse.toString()); }
@Test(dataProvider = "invalidArrayRangeProvider") public void invalidArrayRange(String uriMask, String errorMessage) { try { URIMaskUtil.decodeMaskUriFormat(uriMask); fail("Excepted to throw an exception with a message: " + errorMessage); } catch (IllegalMaskException e) { asse...
@PostMapping("delete") public String deleteProduct(@ModelAttribute("product") Product product) { this.productsRestClient.deleteProduct(product.id()); return "redirect:/catalogue/products/list"; }
@Test void deleteProduct_RedirectsToProductsListPage() { // given var product = new Product(1, "Товар №1", "Описание товара №1"); // when var result = this.controller.deleteProduct(product); // then assertEquals("redirect:/catalogue/products/list", result); ...
public List<UserInfo> listUser(String addr, String filter, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException { ListUsersRequestHeader requestHeader = new ListUsersRequestHeader(filter); RemotingCommand request = ...
@Test public void assertListUser() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); setResponseBody(Collections.singletonList(createUserInfo())); List<UserInfo> actual = mqClientAPI.listUser(defaultBrokerAddr, "", defaultTimeout); assertNotNull(ac...
@Override public void start() { Optional<String> passcodeOpt = configuration.get(WEB_SYSTEM_PASS_CODE.getKey()) // if present, result is never empty string .map(StringUtils::trimToNull); if (passcodeOpt.isPresent()) { logState("enabled"); configuredPasscode = passcodeOpt.get(); } ...
@Test public void passcode_is_disabled_if_blank_configuration() { configurePasscode(""); underTest.start(); assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled"); }
@Override public CompletableFuture<JobStatus> getJobTerminationFuture() { return jobTerminationFuture; }
@Test void testInitialRequirementLowerBoundBeyondAvailableSlotsCausesImmediateFailure() throws Exception { final JobGraph jobGraph = createJobGraph(); final DefaultDeclarativeSlotPool declarativeSlotPool = createDeclarativeSlotPool(jobGraph.getJobID()); final in...
@Override public Object evaluate(final Map<String, Object> requestData, final PMMLRuntimeContext context) { throw new KiePMMLException("KiePMMLModelWithSources is not meant to be used for actual evaluation"); }
@Test void evaluate() { assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> { kiePMMLModelWithSources.evaluate(Collections.EMPTY_MAP, new PMMLRuntimeContextTest()); }); }
public void ensureActiveGroup() { while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) { log.warn("still waiting to ensure active group"); } }
@Test public void testWakeupAfterJoinGroupReceived() throws Exception { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.prepareResponse(body -> { boolean isJoinGroupRequest = body instanceof JoinGroupRequest; if...
public static <K, V> AsMap<K, V> asMap() { return new AsMap<>(false); }
@Test @Category(ValidatesRunner.class) public void testMapAsEntrySetSideInput() { final PCollectionView<Map<String, Integer>> view = pipeline .apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3))) .apply(View.asMap()); PCollection<KV<String, Integer>> output = ...
public static Integer[] getPreselectedTagsArray(Note note, List<Tag> tags) { List<Integer> t = new ArrayList<>(); for (String noteTag : TagsHelper.retrieveTags(note).keySet()) { for (Tag tag : tags) { if (tag.getText().equals(noteTag)) { t.add(tags.indexOf(tag)); break; ...
@Test public void getPreselectedTagsArray() { final Tag anotherTag = new Tag("#anotherTag", 1); Note anotherNote = new Note(); anotherNote.setContent(TAG1.getText() + " " + TAG2.getText() + " " + anotherTag); note.setContent(note.getContent().replace(TAG4.toString(), "")); List<Tag> tags = Arrays...
public static FlinkJobServerDriver fromParams(String[] args) { return fromConfig(parseArgs(args)); }
@Test(timeout = 30_000) public void testJobServerDriverWithoutExpansionService() throws Exception { FlinkJobServerDriver driver = null; Thread driverThread = null; final PrintStream oldErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream newErr = new PrintStream(...
@VisibleForTesting void authenticateLoginCredentials() throws Exception { KettleClientEnvironment.init(); if ( client == null ) { ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE ); client = Client.cr...
@Test public void authenticateLoginCredentials() throws Exception { RepositoryCleanupUtil util = mock( RepositoryCleanupUtil.class ); doCallRealMethod().when( util ).authenticateLoginCredentials(); setInternalState( util, "url", "http://localhost:8080/pentaho" ); setInternalState( util, "username", "...
static Object parseCell(String cell, Schema.Field field) { Schema.FieldType fieldType = field.getType(); try { switch (fieldType.getTypeName()) { case STRING: return cell; case INT16: return Short.parseShort(cell); case INT32: return Integer.parseInt(c...
@Test public void givenValidByteCell_parses() { Byte byteNum = Byte.parseByte("4"); DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("4", byteNum); Schema schema = Schema.builder().addByteField("a_byte").addInt32Field("an_integer").build(); assertEquals( cellToExpectedValue.getValue()...
public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException { try { copyBytes(in, out, buffSize); if(close) { out.close(); out = null; in.close(); in = null; } } finally { ...
@Test public void testCopyBytesWithCountShouldThrowOutTheStreamClosureExceptions() throws Exception { InputStream inputStream = Mockito.mock(InputStream.class); OutputStream outputStream = Mockito.mock(OutputStream.class); Mockito.doReturn(-1).when(inputStream).read(new byte[4096], 0, 1); Mockit...
public String getBindingActualTable(final String dataSource, final String logicTable, final String otherLogicTable, final String otherActualTable) { Optional<ShardingTable> otherShardingTable = Optional.ofNullable(shardingTables.get(otherLogicTable)); int index = otherShardingTable.map(optional -> optio...
@Test void assertGetBindingActualTablesFailureWhenLogicTableNotFound() { assertThrows(BindingTableNotFoundException.class, () -> createBindingTableRule().getBindingActualTable("ds0", "No_Logic_Table", "LOGIC_TABLE", "table_1")); }
StringBuilder codeForComplexFieldExtraction(Descriptors.FieldDescriptor desc, String fieldNameInCode, String javaFieldType, int indent, int varNum, String decoderMethod, String additionalExtractions) { StringBuilder code = new StringBuilder(); if (StringUtils.isBlank(additionalExtractions)) { additi...
@Test public void testCodeForComplexFieldExtractionNonRepeated() { MessageCodeGen messageCodeGen = new MessageCodeGen(); // Message type Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(NESTED_MESSAGE); String fieldNameInCode = ProtobufInterna...
public static Schema fromTableSchema(TableSchema tableSchema) { return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build()); }
@Test public void testFromTableSchema_map_array() { Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_MAP_TYPE); assertEquals(MAP_ARRAY_TYPE, beamSchema); }
public static Rank rank(Query query, QueryChain... ranks) { return new Rank(query, ranks); }
@Test void rank() { String q = Q.select("*") .from("sd1") .where(Q.rank( Q.p("f1").contains("v1"), Q.p("f2").contains("v2"), Q.p("f3").eq(3)) ) .build(); assertEqu...
public static void renameKey(Map<String, Object> map, String originalKey, String newKey) { if (map.containsKey(originalKey)) { final Object value = map.remove(originalKey); map.put(newKey, value); } }
@Test public void renameKeyHandlesEmptyMap() { final Map<String, Object> map = new HashMap<>(); MapUtils.renameKey(map, "foo", "bar"); assertThat(map).isEmpty(); }
@Override public String convert(ILoggingEvent event) { Map<String, String> mdcPropertyMap = event.getMDCPropertyMap(); if (mdcPropertyMap == null) { return defaultValue; } if (key == null) { return outputMDCForAllKeys(mdcPropertyMap); } else { String value = mdcPropertyMap.get...
@Test public void testConvertWithOneEntry() { String k = "MDCConverterTest_k"+diff; String v = "MDCConverterTest_v"+diff; MDC.put(k, v); ILoggingEvent le = createLoggingEvent(); String result = converter.convert(le); assertEquals(k+"="+v, result); }
@Override public AlterReplicaLogDirsResult alterReplicaLogDirs(Map<TopicPartitionReplica, String> replicaAssignment, final AlterReplicaLogDirsOptions options) { final Map<TopicPartitionReplica, KafkaFutureImpl<Void>> futures = new HashMap<>(replicaAssignment.size()); for (TopicPartitionReplica repl...
@Test public void testAlterReplicaLogDirsUnrequested() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { createAlterLogDirsResponse(env, env.cluster().nodeById(0), Errors.NONE, 1, 2); TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic", 1, 0); ...
public boolean hasOperationPermissionDefined() { return !operationConfig.equals(new OperationConfig()); }
@Test public void shouldReturnTrueIfOperationPermissionDefined() { Authorization authorization = new Authorization(new OperationConfig(new AdminUser(new CaseInsensitiveString("baby")))); assertThat(authorization.hasOperationPermissionDefined(), is(true)); }
@Override public ConnectorInfo connectorInfo(String connector) { final ClusterConfigState configState = configBackingStore.snapshot(); if (!configState.contains(connector)) return null; Map<String, String> config = configState.rawConnectorConfig(connector); return new C...
@Test public void testConnectorInfo() { AbstractHerder herder = testHerder(); when(plugins.newConnector(anyString())).thenReturn(new SampleSourceConnector()); when(herder.plugins()).thenReturn(plugins); when(configStore.snapshot()).thenReturn(SNAPSHOT); ConnectorInfo info ...
static void checkNotInDisallowedList(String clsName) { if (DEFAULT_DISALLOWED_LIST_SET.contains(clsName)) { throw new InsecureException(String.format("%s hit disallowed list", clsName)); } }
@Test public void testCheckHitDisallowedList() { // Hit the disallowed list. Assert.assertThrows( InsecureException.class, () -> DisallowedList.checkNotInDisallowedList("java.rmi.server.UnicastRemoteObject")); Assert.assertThrows( InsecureException.class, () -> ...
@Override public void recover() { final List<MappedFile> mappedFiles = this.mappedFileQueue.getMappedFiles(); if (!mappedFiles.isEmpty()) { int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } MappedFile mappedFile = mappe...
@Test public void testLoad() throws IOException { scq = new SparseConsumeQueue(topic, queueId, path, BatchConsumeQueue.CQ_STORE_UNIT_SIZE, defaultMessageStore); String file1 = UtilAll.offset2FileName(111111); String file2 = UtilAll.offset2FileName(222222); long phyOffset = 10; ...
@Override public String render(String text) { if (StringUtils.isBlank(text)) { return ""; } if (regex.isEmpty() || link.isEmpty()) { Comment comment = new Comment(); comment.escapeAndAdd(text); return comment.render(); } try { ...
@Test // #2324 public void shouldRenderAllPossibleMatches() throws Exception { String link = "http://mingle05/projects/cce/cards/${ID}"; String regex = "#(\\d+)"; trackingTool = new DefaultCommentRenderer(link, regex); String result = trackingTool.render("#111, #222: checkin mes...
@Override public double quantile(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } return Beta.inverseRegularizedIncompleteBetaFunction(alpha, beta, p); }
@Test public void testQuantile() { System.out.println("quantile"); BetaDistribution instance = new BetaDistribution(2, 5); instance.rand(); assertEquals(0.008255493, instance.quantile(0.001), 1E-5); assertEquals(0.09259526, instance.quantile(0.1), 1E-5); assertEquals(...
public boolean hasPermission(NacosUser nacosUser, Permission permission) { //update password if (AuthConstants.UPDATE_PASSWORD_ENTRY_POINT.equals(permission.getResource().getName())) { return true; } List<RoleInfo> roleInfoList = getRoles(nacosUser.getUserName()); ...
@Test void hasPermission() { Permission permission = new Permission(); permission.setAction("rw"); permission.setResource(Resource.EMPTY_RESOURCE); NacosUser nacosUser = new NacosUser(); nacosUser.setUserName("nacos"); boolean res = nacosRoleService.hasPermission(naco...
public static Map<String, ResourceModel> buildResourceModels(final Set<Class<?>> restliAnnotatedClasses) { Map<String, ResourceModel> rootResourceModels = new HashMap<>(); Map<Class<?>, ResourceModel> resourceModels = new HashMap<>(); for (Class<?> annotatedClass : restliAnnotatedClasses) { pro...
@Test(dataProvider = "finderSupportedResourceTypeData") public void testFinderSupportedResourceType(Class<?> resourceClass) { try { RestLiApiBuilder.buildResourceModels(Collections.singleton(resourceClass)); } catch (Exception exception) { Assert.fail(String.format("Unexpected except...
@Override public Collection<DatabasePacket> execute() throws SQLException { new BackendTransactionManager(connectionSession.getDatabaseConnectionManager()).rollback(); connectionSession.setAutoCommit(true); connectionSession.setDefaultIsolationLevel(null); connectionSession.setIsolat...
@Test void assertExecute() throws SQLException { ConnectionSession connectionSession = mock(ConnectionSession.class); ProxyDatabaseConnectionManager databaseConnectionManager = mock(ProxyDatabaseConnectionManager.class); when(connectionSession.getDatabaseConnectionManager()).thenReturn(datab...
public void onLeadershipChange(Set<Partition> partitionsBecomeLeader, Set<Partition> partitionsBecomeFollower, Map<String, Uuid> topicIds) { LOGGER.debug("Received leadership changes for leaders: {} and followers: {}", partitionsBecomeLeader,...
@Test void testLeadershipChangesWithoutRemoteLogManagerConfiguring() { assertThrows(KafkaException.class, () -> { remoteLogManager.onLeadershipChange( Collections.singleton(mockPartition(leaderTopicIdPartition)), Collections.singleton(mockPartition(followerTopicIdPartition)), top...
@PostMapping( path = "/api/-/namespace/create", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE ) @Operation(summary = "Create a namespace") @ApiResponses({ @ApiResponse( responseCode = "201", description = "Suc...
@Test public void testCreateNamespace() throws Exception { mockAccessToken(); mockMvc.perform(post("/api/-/namespace/create?token={token}", "my_token") .contentType(MediaType.APPLICATION_JSON) .content(namespaceJson(n -> { n.name = "foobar"; }))) .andE...
@InvokeOnHeader(Web3jConstants.SHH_NEW_FILTER) void shhNewFilter(Message message) throws IOException { String data = message.getHeader(Web3jConstants.DATA, configuration::getData, String.class); List<String> topics = message.getHeader(Web3jConstants.TOPICS, configuration::getTopics, List.class); ...
@Test public void shhNewFilterTest() throws Exception { ShhNewFilter response = Mockito.mock(ShhNewFilter.class); Mockito.when(mockWeb3j.shhNewFilter(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getFilterId()).thenReturn(BigInt...
public static void updateLong(Checksum checksum, long input) { checksum.update((byte) (input >> 56)); checksum.update((byte) (input >> 48)); checksum.update((byte) (input >> 40)); checksum.update((byte) (input >> 32)); checksum.update((byte) (input >> 24)); checksum.updat...
@Test public void testUpdateLong() { final long value = Integer.MAX_VALUE + 1; final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(value); Checksum crc1 = Crc32C.create(); Checksum crc2 = Crc32C.create(); Checksums.updateLong(crc1, value); crc2....
@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 shouldThrowIfQueryFails() { // Given: final StateQueryResult<?> partitionResult = new StateQueryResult<>(); partitionResult.addResult(PARTITION, QueryResult.forFailure(FailureReason.STORE_EXCEPTION, "Boom")); when(kafkaStreams.query(any(StateQueryRequ...
@Override protected TableRecords getUndoRows() { return sqlUndoLog.getBeforeImage(); }
@Test public void getUndoRows() { Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage()); }
public DataMap toDataMap() { DataMap dataMap = new DataMap(_keys.size()); for (Map.Entry<String, ValueAndTypeInfoPair> keyParts : _keys.entrySet()) { String key = keyParts.getKey(); ValueAndTypeInfoPair valueAndTypeInfoPair = keyParts.getValue(); Object value = valueAndTypeInfoPair.getVa...
@Test public void testToDataMap() { CompoundKey compoundKey = new CompoundKey(); compoundKey.append("foo", "foo-value"); compoundKey.append("bar", 1); compoundKey.append("baz", 7L); DataMap dataMap = compoundKey.toDataMap(); Assert.assertEquals(dataMap.get("foo"), compoundKey.getPart("foo")...
@Override public boolean test(Pickle pickle) { URI picklePath = pickle.getUri(); if (!lineFilters.containsKey(picklePath)) { return true; } for (Integer line : lineFilters.get(picklePath)) { if (Objects.equals(line, pickle.getLocation().getLine()) ...
@Test void matches_at_least_one_line() { LinePredicate predicate = new LinePredicate(singletonMap( featurePath, asList(3, 4))); assertTrue(predicate.test(firstPickle)); assertTrue(predicate.test(secondPickle)); assertTrue(predicate.test(thirdPickle)); ...
public static Optional<Object> doLogin(final String username, final String password, final String url) throws IOException { Map<String, Object> loginMap = new HashMap<>(2); loginMap.put(Constants.LOGIN_NAME, username); loginMap.put(Constants.PASS_WORD, password); String result = OkHttpTo...
@Test public void testDoLoginError() throws IOException { final String userName = "userName"; final String password = "password"; Map<String, Object> loginMap = new HashMap<>(2); loginMap.put(Constants.LOGIN_NAME, userName); loginMap.put(Constants.PASS_WORD, password); ...
@Override public List<DataLayoutStrategy> generate() { return Collections.singletonList(generateCompactionStrategy()); }
@Test void testStrategySanityCheck() throws Exception { final String testTable = "db.test_table_sanity_check"; try (SparkSession spark = getSparkSession()) { spark.sql("USE openhouse"); spark.sql( String.format( "create table %s (id int, data string, ts timestamp) partition...
@Override public <T> void storeObject( String accountName, ObjectType objectType, String objectKey, T obj, String filename, boolean isAnUpdate) { if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) { var draftRecord = new SqlCanaryArchive(); draftRecord.setId(o...
@Test public void testStoreObjectWhenCanaryArchive() { var testAccountName = UUID.randomUUID().toString(); var testObjectType = ObjectType.CANARY_RESULT_ARCHIVE; var testObjectKey = UUID.randomUUID().toString(); var testCanaryExecutionStatusResponse = createTestCanaryExecutionStatusResponse(); s...
@Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void invokeAny_withTimeout() throws Exception { newManagedExecutorService().invokeAny(Collections.singleton(() -> null), 1, TimeUnit.SECONDS); }
public static SecretKey generateKey(String algorithm) { return generateKey(algorithm, -1); }
@Test public void generateSm4KeyTest(){ // https://github.com/dromara/hutool/issues/2150 assertEquals(16, KeyUtil.generateKey("sm4").getEncoded().length); assertEquals(32, KeyUtil.generateKey("sm4", 256).getEncoded().length); }
public static boolean shouldLoadInIsolation(String name) { return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches()); }
@Test public void testClientConfigProvider() { assertFalse(PluginUtils.shouldLoadInIsolation( "org.apache.kafka.common.config.provider.ConfigProvider") ); assertTrue(PluginUtils.shouldLoadInIsolation( "org.apache.kafka.common.config.provider.FileConfigProvider...
@Override public void doAdmissionChecks(Function.FunctionDetails functionDetails){ final String overriddenJobName = getOverriddenName(functionDetails); KubernetesRuntime.doChecks(functionDetails, overriddenJobName); validateMinResourcesRequired(functionDetails); validateMaxResourcesR...
@Test public void testAdmissionChecks() throws Exception { factory = createKubernetesRuntimeFactory(null, null, null, null, false); FunctionDetails functionDetails = createFunctionDetails(); factory.doAdmissionChecks(functionDetails); }
public void processOnce() throws IOException { // set status of query to OK. ctx.getState().reset(); executor = null; // reset sequence id of MySQL protocol final MysqlChannel channel = ctx.getMysqlChannel(); channel.setSequenceId(0); // read packet from channel ...
@Test public void testQueryFail(@Mocked StmtExecutor executor) throws Exception { ConnectContext ctx = initMockContext(mockChannel(queryPacket), GlobalStateMgr.getCurrentState()); ConnectProcessor processor = new ConnectProcessor(ctx); // Mock statement executor new Expectations() ...
public MapWithProtoValuesFluentAssertion<M> ignoringRepeatedFieldOrderForValues() { return usingConfig(config.ignoringRepeatedFieldOrder()); }
@Test public void testCompareMultipleMessageTypes() { // Don't run this test twice. if (!testIsRunOnce()) { return; } expectThat( ImmutableMap.of( 2, TestMessage2.newBuilder().addRString("foo").addRString("bar").build(), 3, ...
@Override public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) { Set<RuleDescriptionSectionDto> advancedSections = rule.ruleDescriptionSections().stream() .map(this::toRuleDescriptionSectionDto) .collect(Collectors.toSet()); return addLegacySectionToAdvancedSections(ad...
@Test public void generateSections_whenContextSpecificSectionsAndNonContextSpecificSection_createsTwoSectionsAndDefault() { when(rule.ruleDescriptionSections()).thenReturn(List.of(SECTION_1, SECTION_3_WITH_CTX_2)); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule); ...
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) { try { RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination); ClientPropertiesBean reqParams = new ClientPropertiesBean(req); req.setAttribute("properties", reqParams); requestDispatcher.fo...
@Test void testDoGet() throws Exception { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class); RequestDispatcher mockDispatcher = Mockito.mock(RequestDispatcher.class); StringWriter stringWriter = new StringWriter(...
public static Versions parse(String input, Versions defaultVersions) { if (input == null) { return defaultVersions; } String trimmedInput = input.trim(); if (trimmedInput.isEmpty()) { return defaultVersions; } if (trimmedInput.equals(NONE_STRING)) ...
@Test public void testVersionsParse() { assertEquals(Versions.NONE, Versions.parse(null, Versions.NONE)); assertEquals(Versions.ALL, Versions.parse(" ", Versions.ALL)); assertEquals(Versions.ALL, Versions.parse("", Versions.ALL)); assertEquals(newVersions(4, 5), Versions.parse(" 4-5 ...
static void configureEncryption( S3FileIOProperties s3FileIOProperties, PutObjectRequest.Builder requestBuilder) { configureEncryption( s3FileIOProperties, requestBuilder::serverSideEncryption, requestBuilder::ssekmsKeyId, requestBuilder::sseCustomerAlgorithm, requestBu...
@Test public void testConfigureServerSideKmsEncryption() { S3FileIOProperties s3FileIOProperties = new S3FileIOProperties(); s3FileIOProperties.setSseType(S3FileIOProperties.SSE_TYPE_KMS); s3FileIOProperties.setSseKey("key"); S3RequestUtil.configureEncryption( s3FileIOProperties, this:...
@Override public void onTaskFinished(TaskAttachment attachment) { if (attachment instanceof BrokerPendingTaskAttachment) { onPendingTaskFinished((BrokerPendingTaskAttachment) attachment); } else if (attachment instanceof BrokerLoadingTaskAttachment) { onLoadingTaskFinished((B...
@Test public void testCommitRateExceeded(@Injectable BrokerLoadingTaskAttachment attachment1, @Injectable LoadTask loadTask1, @Mocked GlobalStateMgr globalStateMgr, @Injectable Database database, ...
public static String getUserRole(String token) { return (String) getTokenBody(token).get(ROLE_CLAIMS); }
@Test public void getUserRole() { String userRole = JwtTokenUtil.getUserRole(token); Assert.isTrue(role.equals(userRole)); }
@Override public boolean addWord(String word, int frequency) { synchronized (mResourceMonitor) { if (isClosed()) { Logger.d( TAG, "Dictionary (type " + this.getClass().getName() + ") " + this.getDictionaryName() ...
@Test public void testAddWord() throws Exception { mDictionaryUnderTest.loadDictionary(); assertTrue(mDictionaryUnderTest.addWord("new", 23)); Assert.assertEquals("new", mDictionaryUnderTest.wordRequestedToAddedToStorage); Assert.assertEquals(23, mDictionaryUnderTest.wordFrequencyRequestedToAddedToSt...
public static String encodingParams(Map<String, String> params, String encoding) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); if (null == params || params.isEmpty()) { return null; } for (Map.Entry<String, String> entry : params.en...
@Test void testEncodingParamsMap() throws UnsupportedEncodingException { Map<String, String> params = new LinkedHashMap<>(); params.put("a", ""); params.put("b", "x"); params.put("uriChar", "="); params.put("chinese", "测试"); assertEquals("b=x&uriChar=%3D&chinese=%E6%B...
public static ClusterMembership from(String stringValue, Version vespaVersion, Optional<DockerImage> dockerImageRepo) { return from(stringValue, vespaVersion, dockerImageRepo, ZoneEndpoint.defaultEndpoint); }
@Test void testServiceInstanceWithGroupAndRetireFromString() { assertContentServiceWithGroupAndRetire(ClusterMembership.from("content/id1/4/37/retired/stateful", Vtag.currentVersion, Optional.empty())); }
@VisibleForTesting public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics) { if (rowCount == 0) { return Domain.none(type); } if (columnStatistics == null) { return Domain.all(type); } if (columnStatistics.hasN...
@Test public void testBoolean() { assertEquals(getDomain(BOOLEAN, 0, null), Domain.none(BOOLEAN)); assertEquals(getDomain(BOOLEAN, 10, null), Domain.all(BOOLEAN)); assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(null, null)), Domain.none(BOOLEAN)); assertEquals(getDomain(B...
@SuppressWarnings("FutureReturnValueIgnored") public void start() { running.set(true); configFetcher.start(); memoryMonitor.start(); streamingWorkerHarness.start(); sampler.start(); workerStatusReporter.start(); activeWorkRefresher.start(); }
@Test public void testOutputKeyTooLargeException() throws Exception { KvCoder<String, String> kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()); List<ParallelInstruction> instructions = Arrays.asList( makeSourceInstruction(kvCoder), makeDoFnInstruction(new Excep...
@Deprecated public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) { return prune(segments, query, new SegmentPrunerStatistics()); }
@Test public void emptySegmentsAreNotInvalid() { SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf); IndexSegment indexSegment = mockIndexSegment(0, "col1", "col2"); SegmentPrunerStatistics stats = new SegmentPrunerStatistics(); List<IndexSegment> indexes = new ArrayList<>(); ...
@SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) getBeanFactory().getBean(name); }
@Test public void getBeanTest(){ final Demo2 testDemo = SpringUtil.getBean("testDemo"); assertEquals(12345, testDemo.getId()); assertEquals("test", testDemo.getName()); }
public void isNotEmpty() { if (actual == null) { failWithActual(simpleFact("expected a non-empty string")); } else if (actual.isEmpty()) { failWithoutActual(simpleFact("expected not to be empty")); } }
@Test public void stringIsNotEmpty() { assertThat("abc").isNotEmpty(); }
public Map<String, String> match(String text) { final HashMap<String, String> result = MapUtil.newHashMap(true); int from = 0; String key = null; int to; for (String part : patterns) { if (StrUtil.isWrap(part, "${", "}")) { // 变量 key = StrUtil.sub(part, 2, part.length() - 1); } else { to = t...
@Test public void matcherTest2(){ // 当有无匹配项的时候,按照全不匹配对待 final StrMatcher strMatcher = new StrMatcher("${name}-${age}-${gender}-${country}-${province}-${city}-${status}"); final Map<String, String> match = strMatcher.match("小明-19-男-中国-河南-郑州"); assertEquals(0, match.size()); }
@Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("version", version) .add("type", type) .add("length", length) .toString(); }
@Test public void testToStringBmp() throws Exception { Bmp bmp = deserializer.deserialize(headerBytes, 0, headerBytes.length); String str = bmp.toString(); assertTrue(StringUtils.contains(str, "version=" + version)); assertTrue(StringUtils.contains(str, "type=" + type)); ass...
public String getBaseUrl() { String url = config.get(SERVER_BASE_URL).orElse(""); if (isEmpty(url)) { url = computeBaseUrl(); } // Remove trailing slashes return StringUtils.removeEnd(url, "/"); }
@Test public void base_url_is_http_localhost_specified_port_when_port_is_set() { settings.setProperty(PORT_PORPERTY, 951); assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:951"); }
public static List<Criterion> parse(String filter) { return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false) .map(FilterParser::parseCriterion) .toList(); }
@Test public void metric_key_with_and_string() { List<Criterion> criterion = FilterParser.parse("ncloc > 10 and operand = 5"); assertThat(criterion).hasSize(2).extracting(Criterion::getKey, Criterion::getValue).containsExactly(tuple("ncloc", "10"), tuple("operand", "5")); }
@Override public T remove(Object key) { if (key instanceof StructLike || key == null) { StructLikeWrapper wrapper = wrappers.get(); T value = wrapperMap.remove(wrapper.set((StructLike) key)); wrapper.set(null); // don't hold a reference to the key. return value; } return null; }
@Test public void testRemove() { Record gRecord = GenericRecord.create(STRUCT_TYPE); Record record = gRecord.copy(ImmutableMap.of("id", 1, "data", "aaa")); Map<StructLike, String> map = StructLikeMap.create(STRUCT_TYPE); map.put(record, "1-aaa"); assertThat(map).hasSize(1).containsEntry(record, "...
@Override public int deleteTopics(final Set<String> deleteTopics) { if (deleteTopics == null || deleteTopics.isEmpty()) { return 0; } int deleteCount = 0; for (String topic : deleteTopics) { ConcurrentMap<Integer, ConsumeQueueInterface> queueTable = this.cons...
@Test public void testDeleteTopics() { MessageStoreConfig messageStoreConfig = messageStore.getMessageStoreConfig(); ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueueInterface>> consumeQueueTable = ((DefaultMessageStore) messageStore).getConsumeQueueTable(); for (int i = ...
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) { SinkConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!existingC...
@Test public void testMergeDifferentLogTopic() { SinkConfig sinkConfig = createSinkConfig(); SinkConfig newSinkConfig = createUpdatedSinkConfig("logTopic", "Different"); SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig); assertEquals( ...
@Override public boolean next() throws SQLException { if (skipAll) { return false; } if (!paginationContext.getActualRowCount().isPresent()) { return getMergedResult().next(); } return ++rowNumber <= paginationContext.getActualRowCount().get() && getMe...
@Test void assertNextWithoutRowCount() throws SQLException { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); MySQLSelectStatement selectStatement = new MySQLSelectStatement(); selectStatement.setProjections(new ProjectionsSegment(0, 0)); sele...
public MessageReceiptHandle removeOne(String msgID) { Map<HandleKey, HandleData> handleMap = this.receiptHandleMap.get(msgID); if (handleMap == null) { return null; } Set<HandleKey> keys = handleMap.keySet(); for (HandleKey key : keys) { MessageReceiptHand...
@Test public void testRemoveOne() { String handle1 = createHandle(); AtomicReference<MessageReceiptHandle> removeHandleRef = new AtomicReference<>(); AtomicInteger count = new AtomicInteger(); receiptHandleGroup.put(msgID, createMessageReceiptHandle(handle1, msgID)); int thr...
public AbilityStatus getConnectionAbility(AbilityKey abilityKey) { if (currentConnection != null) { return currentConnection.getConnectionAbility(abilityKey); } // return null if connection is not ready return null; }
@Test void testGetConnectionAbilityWithReadyConnection() { when(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)).thenReturn(AbilityStatus.SUPPORTED); rpcClient.currentConnection = connection; AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1); ...
public String getStoreMode() { return storeMode; }
@Test public void testGetStoreMode() { Assertions.assertEquals("file", parameterParser.getStoreMode()); }
@Override @Transactional(rollbackFor = Exception.class) public void deleteCodegen(Long tableId) { // 校验是否已经存在 if (codegenTableMapper.selectById(tableId) == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } // 删除 table 表定义 codegenTableMapper.deleteById(tabl...
@Test public void testDeleteCodegen_success() { // mock 数据 CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene())); codegenTableMapper.insert(table); CodegenColumnDO column = randomPojo(CodegenColumnDO.class, o -> o....
public static boolean isCompositeURI(URI uri) { String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); if (ssp.indexOf('(') == 0 && checkParenthesis(ssp)) { return true; } return false; }
@Test public void testIsCompositeURIWithQueryAndSlashes() throws URISyntaxException { URI[] compositeURIs = new URI[] { new URI("test://(part1://host?part1=true)?outside=true"), new URI("broker://(tcp://localhost:61616)?name=foo") }; for (URI uri : compositeURIs) { assertTrue(uri + " mus...
public static List<UpdateRequirement> forUpdateTable( TableMetadata base, List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != base, "Invalid table metadata: null"); Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Bui...
@Test public void setDefaultPartitionSpec() { int specId = 3; when(metadata.defaultSpecId()).thenReturn(specId); List<UpdateRequirement> requirements = UpdateRequirements.forUpdateTable( metadata, ImmutableList.of( new MetadataUpdate.SetDefaultPartitionSpec(...
public static void smooth(PointList geometry, double maxWindowSize) { if (geometry.size() <= 2) { // geometry consists only of tower nodes, there are no pillar nodes to be smoothed in between return; } // calculate the distance between all points once here to avoid repea...
@Test public void testManyPoints() { /** * used to cross validate this implementation as it was ported from an internal kotlin prototype */ PointList pl = new PointList(27, true); pl.add(10.153564, 47.324976, 1209.5); pl.add(10.15365, 47.32499, 1209.3); pl.a...
public static SchemaAndValue parseString(String value) { if (value == null) { return NULL_SCHEMA_AND_VALUE; } if (value.isEmpty()) { return new SchemaAndValue(Schema.STRING_SCHEMA, value); } ValueParser parser = new ValueParser(new Parser(value)); ...
@Test public void shouldNotParseUnquotedArrayElementsAsStrings() { SchemaAndValue schemaAndValue = Values.parseString("[foo]"); assertEquals(Type.STRING, schemaAndValue.schema().type()); assertEquals("[foo]", schemaAndValue.value()); }
public static RepositoryMetadataStore getInstance() { return repositoryMetadataStore; }
@Test public void shouldAnswerIfKeyHasGivenOption() throws Exception { PackageConfigurations repositoryConfigurationPut = new PackageConfigurations(); repositoryConfigurationPut.add(new PackageConfiguration("key-one").with(PackageConfiguration.SECURE, true).with(PackageConfiguration.REQUIRED, true))...
@Override public Connector build(Server server, MetricRegistry metrics, String name, @Nullable ThreadPool threadPool) { final HttpConfiguration httpConfig = buildHttpConfiguration(); final HttpConnectionFactory httpConnectionFactory = buildHttpConnectionFactory(httpConfig); final SslContex...
@Test void testBuild() throws Exception { final HttpsConnectorFactory https = new HttpsConnectorFactory(); https.setBindHost("127.0.0.1"); https.setPort(8443); https.setKeyStorePath("/etc/app/server.ks"); https.setKeyStoreType("JKS"); https.setKeyStorePassword("corre...
void logRun(long runIndex, boolean runSucceeded, Duration pollInterval, Instant runStartTime, Instant runEndTime) { if (runSucceeded && exceptionCounter > 0) { --exceptionCounter; } Duration actualRunDuration = Duration.between(runStartTime, runEndTime); if (actualRunDuration...
@Test void ifThreeConsecutiveRunsTookTooLongANotificationIsShown() { statistics.logRun(2, true, pollInterval, now().minusSeconds(45), now().minusSeconds(30)); statistics.logRun(3, true, pollInterval, now().minusSeconds(30), now().minusSeconds(15)); statistics.logRun(4, true, pollInterval, no...
@Override @Nonnull public ListIterator<T> listIterator(final int initialIndex) { final Iterator<T> initialIterator; try { initialIterator = iterator(initialIndex); } catch (NoSuchElementException ex) { throw new IndexOutOfBoundsException(); } return new ...
@Test public void testForwardIterationException() { // note: no "expected = NoSuchElementException", because we want to make sure the exception occurs only during // the last call to next() ListIterator<Integer> iter = list.listIterator(0); for (int i=0; i<100; i++) { it...
@Override public double quantile(double p) { if (p < 0.0 || p > 1.0) { throw new IllegalArgumentException("Invalid p: " + p); } if (p < Math.exp(-lambda)) { return 0; } int n = (int) Math.max(Math.sqrt(lambda), 5.0); int nl, nu, inc = 1; ...
@Test public void testQuantile() { System.out.println("quantile"); PoissonDistribution instance = new PoissonDistribution(3.5); instance.rand(); assertEquals(0, instance.quantile(0.01), 1E-7); assertEquals(1, instance.quantile(0.1), 1E-7); assertEquals(2, instance.qua...
public boolean canSchedule(SchedulerGroupAccountant accountant) { return accountant.totalReservedThreads() < getTableThreadsHardLimit(); }
@Test public void testCanSchedule() throws Exception { ResourceManager rm = getResourceManager(2, 5, 1, 3); SchedulerGroupAccountant accountant = mock(SchedulerGroupAccountant.class); when(accountant.totalReservedThreads()).thenReturn(3); assertFalse(rm.canSchedule(accountant)); when(accou...
@Subscribe public void onScriptCallbackEvent(ScriptCallbackEvent event) { // ROE uncharge uses the same script as destroy if (!"destroyOnOpKey".equals(event.getEventName())) { return; } final int yesOption = client.getIntStack()[client.getIntStackSize() - 1]; if (yesOption == 1) { checkDestroyWid...
@Test public void testUncharge() { when(client.getIntStack()).thenReturn(new int[]{1, RING_OF_ENDURANCE}); when(client.getIntStackSize()).thenReturn(1); when(client.getTickCount()).thenReturn(1); Widget enduranceWidget = mock(Widget.class); when(client.getWidget(ComponentID.DESTROY_ITEM_NAME)).thenReturn(e...
public static double conversion(String expression) { return (new Calculator()).calculate(expression); }
@Test public void conversationTest6() { final double conversion = Calculator.conversion("-((2.12-2) * 100)"); assertEquals(-1D * (2.12 - 2) * 100, conversion, 0.01); }
public void skipValue() throws IOException { int count = 0; do { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } switch (p) { case PEEKED_BEGIN_ARRAY: push(JsonScope.EMPTY_ARRAY); count++; break; case PEEKED_BEGIN_OBJECT: ...
@Test public void testStrictNonExecutePrefixWithSkipValue() { JsonReader reader = new JsonReader(reader(")]}'\n []")); var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue()); assertStrictError(e, "line 1 column 1 path $"); }
@Override public boolean releaseTaskManager(ResourceID taskManagerId, Exception cause) { assertHasBeenStarted(); if (registeredTaskManagers.remove(taskManagerId)) { internalReleaseTaskManager(taskManagerId, cause); return true; } return false; }
@Test void testReleaseTaskManager() throws Exception { try (DeclarativeSlotPoolService declarativeSlotPoolService = createDeclarativeSlotPoolService()) { final ResourceID knownTaskManager = ResourceID.generate(); declarativeSlotPoolService.registerTaskManager(knownTas...
@Override public Database getDb(String name) { ConnectorMetadata metadata = metadataOfDb(name); return metadata.getDb(name); }
@Test void testGetDb(@Mocked ConnectorMetadata connectorMetadata) { new Expectations() { { connectorMetadata.getDb("test_db"); result = null; times = 1; } }; CatalogConnectorMetadata catalogConnectorMetadata = new Catal...
public static long producerRecordSizeInBytes(final ProducerRecord<byte[], byte[]> record) { return recordSizeInBytes( record.key() == null ? 0 : record.key().length, record.value() == null ? 0 : record.value().length, record.topic(), record.headers() ); ...
@Test public void shouldComputeSizeInBytesForProducerRecordWithNullValue() { final ProducerRecord<byte[], byte[]> record = new ProducerRecord<>( TOPIC, 1, 0L, KEY, null, HEADERS ); assertThat(producerRecordSizeInBytes(re...
public static long checkPositive(long n, String name) { if (n <= 0) { throw new IllegalArgumentException(name + ": " + n + " (expected: > 0)"); } return n; }
@Test(expected = IllegalArgumentException.class) public void checkPositiveMustFailIfArgumentIsZero() { RangeUtil.checkPositive(0, "var"); }