focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public void add(McastRoute route) { checkNotNull(route, "Route cannot be null"); store.storeRoute(route, McastStore.Type.ADD); }
@Test public void testAdd() { manager.add(r1); validateEvents(McastEvent.Type.ROUTE_ADDED); }
public void append(ByteBuffer record, DataType dataType) throws InterruptedException { if (dataType.isEvent()) { writeEvent(record, dataType); } else { writeRecord(record, dataType); } }
@Test void testAppendDataRequestBuffer() throws Exception { CompletableFuture<Void> requestBufferFuture = new CompletableFuture<>(); HsMemoryDataManagerOperation memoryDataManagerOperation = TestingMemoryDataManagerOperation.builder() .setRequestBufferFromPool...
public synchronized long nextId() { long timestamp = timeGen(); //闰秒 if (timestamp < lastTimestamp) { long offset = lastTimestamp - timestamp; if (offset <= 5) { try { wait(offset << 1); timestamp = timeGen(); ...
@Test void nextId() { Sequence sequence = new Sequence(null); long id = sequence.nextId(); LocalDateTime now = LocalDateTime.now(); System.out.println(sequence.nextId() + "---" + now); long timestamp = Sequence.parseIdTimestamp(id); Instant instant = Instant.ofEpochM...
@Override protected MessageFormat resolveCode(String code, Locale locale) { List<JsonObject> langs = getLanguageMap(locale); String value = getValue(code, langs); if (value == null) { // if we haven't found anything, try the default locale langs = getLanguageMap(fallbackLocale); value = getValue(code...
@Test public void verifyWhenLocaleDoesNotExist_cannotResolveCode() { MessageFormat mf = jsonMessageSource.resolveCode("test", localeThatDoesNotHaveAFile); assertNull(mf); }
@Override public JsonSchema convert(URI basePath, Descriptors.Descriptor schema) { Map<String, FieldSchema> definitions = new HashMap<>(); RefFieldSchema rootRef = registerObjectAndReturnRef(schema, definitions); return JsonSchema.builder() .id(basePath.resolve(schema.getFullName())) .type...
@Test void testSchemaConvert() throws Exception { String protoSchema = """ syntax = "proto3"; package test; import "google/protobuf/timestamp.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/wrappers.pr...
@Override public void close() { JOrphanUtils.closeQuietly(isr); JOrphanUtils.closeQuietly(fis); JOrphanUtils.closeQuietly(reader); }
@Test public void testClose() { CsvSampleReader reader = new CsvSampleReader(tempCsv, metadata); reader.close(); try { reader.readSample(); fail("Stream should be closed."); } catch (SampleException expected) { // All is well } }
public static GcsPath fromComponents(@Nullable String bucket, @Nullable String object) { return new GcsPath(null, bucket, object); }
@Test(expected = IllegalArgumentException.class) public void testInvalidBucket() { GcsPath.fromComponents("invalid/", ""); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException { ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); }
@Test void givenTypePolygonAndConfigWithPolygonDefined_whenOnMsg_thenFalse() throws TbNodeException { // GIVEN var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration(); config.setFetchPerimeterInfoFromMessageMetadata(false); config.setPolygonsDefinition(GeoUti...
@Override public Set<DeviceId> getPhysicalDevices(NetworkId networkId, DeviceId deviceId) { checkNotNull(networkId, "Network ID cannot be null"); checkNotNull(deviceId, "Virtual device ID cannot be null"); Set<VirtualPort> virtualPortSet = getVirtualPorts(networkId, deviceId); Set<De...
@Test public void testGetPhysicalDevices() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); manager.registerTenantId(TenantId.tenantId(tenantIdValue2)); VirtualNetwork virtualNetwork1 = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); Vi...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseMiui10WithChromeTest() { final String uaStr = "Mozilla/5.0 (Linux; Android 9; MIX 3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36"; final UserAgent ua = UserAgentUtil.parse(uaStr); assertEquals("Chrome", ua.getBrowser().toString()); assertEquals("70.0.3...
@VisibleForTesting Set<String> extractFields(List<ResultMessage> hits) { Set<String> filteredFields = Sets.newHashSet(); hits.forEach(hit -> { final Message message = hit.getMessage(); for (String field : message.getFieldNames()) { if (!Message.FILTERED_FIELD...
@Test public void extractFieldsForTwoMessagesContainingDifferentFields() throws Exception { final ResultMessage r1 = mock(ResultMessage.class); final Message m1 = mock(Message.class); when(m1.getFieldNames()).thenReturn(ImmutableSet.of( "message", "source", ...
public @NonNull String fastTail(int numChars, Charset cs) throws IOException { try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { long len = raf.length(); // err on the safe side and assume each char occupies 4 bytes // additional 1024 byte margin is to bring us ...
@Test public void shortTail() throws Exception { File f = tmp.newFile(); Files.writeString(f.toPath(), "hello", Charset.defaultCharset()); TextFile t = new TextFile(f); assertEquals("hello", t.fastTail(35)); }
public static long toLong(String str, long defaultValue) { if (str == null) { return defaultValue; } try { return Long.parseLong(str); } catch (NumberFormatException nfe) { return defaultValue; } }
@Test void testToLong() { assertEquals(1L, NumberUtils.toLong(null, 1L)); assertEquals(1L, NumberUtils.toLong("", 1L)); assertEquals(1L, NumberUtils.toLong("1", 0L)); }
public static String reformatParams(Object[] params) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < params.length; i++) { if (i > 0) { sb.append(", "); } sb.append(reformatParam(params[i])); } return sb.toString(); }
@Test public void reformatParams() { String formattedParams = SqlLogFormatter.reformatParams(new Object[] {"foo", 42, null, true}); assertThat(formattedParams).isEqualTo("foo, 42, [null], true"); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void test4483Response() { Reader reader = new Reader(new OpenAPI()); OpenAPI openAPI = reader.read(Ticket4483Resource.class); String yaml = "openapi: 3.0.1\n" + "tags:\n" + "- name: Dummy\n" + " description: Dummy resource for te...
@Override @TpsControl(pointName = "ConfigPublish") @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) @ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class) public ConfigPublishResponse handle(ConfigPublishRequest request, RequestMeta meta) throws NacosException { ...
@Test void testBetaPublishCas() throws NacosException, InterruptedException { String dataId = "testBetaPublishCas"; String group = "group"; String tenant = "tenant"; String content = "content"; ConfigPublishRequest configPublishRequest = new ConfigPublishRequest(); ...
static int calculateChecksum(ByteBuf data) { return calculateChecksum(data, data.readerIndex(), data.readableBytes()); }
@Test public void testCalculateChecksum() { ByteBuf input = Unpooled.wrappedBuffer(new byte[] { 'n', 'e', 't', 't', 'y' }); assertEquals(maskChecksum(0xd6cb8b55L), calculateChecksum(input)); input.release(); }
public Exchange unmarshallExchange(CamelContext camelContext, byte[] buffer, String deserializationFilter) throws IOException, ClassNotFoundException { return unmarshallExchange(camelContext, new ByteArrayInputStream(buffer), deserializationFilter); }
@Test public void shouldFailWithRejected() throws IOException, ClassNotFoundException { Employee emp = new Employee("Mickey", "Mouse"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(emp); oo...
public static boolean contains(int[] replicas, int value) { for (int replica : replicas) { if (replica == value) return true; } return false; }
@Test public void testContains() { assertTrue(Replicas.contains(new int[] {3, 0, 1}, 0)); assertFalse(Replicas.contains(new int[] {}, 0)); assertTrue(Replicas.contains(new int[] {1}, 1)); }
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_keysHidden_keysexposed() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("keysexposed", config); assertThat(config.inputFlags).isEqualTo(KEYSHIDDEN_NO); }
@SuppressWarnings("unchecked") public DataObjectToObjectCache<V> clone() throws CloneNotSupportedException { DataObjectToObjectCache<V> cloned = (DataObjectToObjectCache<V>) super.clone(); cloned._cache = (HashMap<DataObjectKey, V>) _cache.clone(); return cloned; }
@Test public void testClone() throws CloneNotSupportedException { IdentityHashMap<Object, DataTemplate<?>> controlCache = new IdentityHashMap<>(); DataObjectToObjectCache<DataTemplate<?>> testCache = new DataObjectToObjectCache<>(); populateTestData(controlCache, testCache); testCache = testCache.c...
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 testCheckArgument2Args1true2null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(true, null); }); }
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeTransitionFilter edgeTransitionFilter, boolean excludeSingleEdgeComponents) { return new EdgeBasedTarjanSCC(graph, edgeTransitionFilter, excludeSingleEdgeComponents).findComponentsRecursive(); }
@Test public void oneWayBridges() { // 0 - 1 -> 2 - 3 // | | // 4 - 5 -> 6 - 7 g.edge(0, 1).setDistance(1).set(speedEnc, 10, 10); g.edge(1, 2).setDistance(1).set(speedEnc, 10, 0); g.edge(2, 3).setDistance(1).set(speedEnc, 10, 10); g.edge(2,...
public boolean isFiller() { if(filler == null) return false; return !this.getFiller().equals(Filler.NONE); }
@Test void isFiller_false() { product.setFiller(Filler.NONE); assertFalse(product.isFiller()); }
public List<PropertyMetadata<?>> getSessionProperties() { return sessionProperties; }
@Test public void testEmptyConfigNodeSelectionStrategyConfig() { ConnectorSession connectorSession = new TestingConnectorSession( new HiveCommonSessionProperties( new HiveCommonClientConfig().setNodeSelectionStrategy(NodeSelectionStrategy.valueOf("NO_PREFERENCE"))...
@Override public long sum() { return get(sumAsync(60, TimeUnit.SECONDS)); }
@Test public void testSum() { RLongAdder adder1 = redisson.getLongAdder("test1"); RLongAdder adder2 = redisson.getLongAdder("test1"); RLongAdder adder3 = redisson.getLongAdder("test1"); adder1.add(2); adder2.add(4); adder3.add(1); Assertions....
@Override public void checkBeforeUpdate(final SetDefaultSingleTableStorageUnitStatement sqlStatement) { checkStorageUnitExist(sqlStatement); }
@Test void assertCheckWithLogicDataSource() { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); DataSourceMapperRuleAttribute ruleAttribute = mock(DataSourceMapperRuleAttribute.class, RETURNS_DEEP_STUBS); when(ruleAttribute.getDataSourceMapper().keySet...
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException( "The level of the root logger cannot be set to null"); } level = newLevel; if (newLe...
@Test public void testEnabled_Debug() throws Exception { root.setLevel(Level.DEBUG); checkLevelThreshold(loggerTest, Level.DEBUG); }
@Override public void check(final String databaseName, final ShardingRuleConfiguration ruleConfig, final Map<String, DataSource> dataSourceMap, final Collection<ShardingSphereRule> builtRules) { checkShardingAlgorithms(ruleConfig.getShardingAlgorithms().values()); checkKeyGeneratorAlgorithms(ruleCon...
@SuppressWarnings("unchecked") @Test void assertCheckTableConfigurationFailed() { ShardingRuleConfiguration ruleConfig = createRuleConfiguration(); ruleConfig.setTables(Collections.singletonList(createShardingTableRuleConfiguration(null, null, null))); ruleConfig.setAutoTables(Collection...
public Set<String> getValues() { return values; }
@Test void requireThatValueSetIsMutable() { FeatureSet node = new FeatureSet("key"); node.getValues().add("valueA"); assertValues(List.of("valueA"), node); node = new FeatureSet("key", "valueA"); node.getValues().add("valueB"); assertValues(List.of("valueA", "valueB"...
public abstract WriteOperation<DestinationT, OutputT> createWriteOperation();
@Test public void testFileBasedWriterWithWritableByteChannelFactory() throws Exception { final String testUid = "testId"; ResourceId root = getBaseOutputDirectory(); WriteOperation<Void, String> writeOp = SimpleSink.makeSimpleSink( root, "file", "-SS-of-NN", "txt", new DrunkWritabl...
@Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns...
@Test void shouldCorsFilterDeactivatedForNullAllowedOrigins() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); mockMvc .perform(get("/...
public AuditEventProcessor(PluginMgr pluginMgr) { this.pluginMgr = pluginMgr; }
@Test public void testAuditEventProcessor() throws IOException { AuditEventProcessor processor = GlobalStateMgr.getCurrentState().getAuditEventProcessor(); long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { AuditEvent event = new AuditEvent.AuditEventBuild...
byte[] removeEscapedEnclosures( byte[] field, int nrEnclosuresFound ) { byte[] result = new byte[field.length - nrEnclosuresFound]; int resultIndex = 0; for ( int i = 0; i < field.length; i++ ) { result[resultIndex++] = field[i]; if ( field[i] == enclosure[0] && i + 1 < field.length && field[i +...
@Test public void testRemoveEscapedEnclosuresWithTwoByThemselves() { CsvInputData csvInputData = new CsvInputData(); csvInputData.enclosure = "\"".getBytes(); String result = new String( csvInputData.removeEscapedEnclosures( "\"\"\"\"".getBytes(), 2 ) ); assertEquals( "\"\"", result ); }
public List<Stream> match(Message message) { final Set<Stream> result = Sets.newHashSet(); final Set<String> blackList = Sets.newHashSet(); for (final Rule rule : rulesList) { if (blackList.contains(rule.getStreamId())) { continue; } final St...
@Test public void testExactMatch() throws Exception { final StreamMock stream = getStreamMock("test"); final StreamRuleMock rule = new StreamRuleMock(ImmutableMap.of( "_id", new ObjectId(), "field", "testfield", "value", "testvalue", "t...
public Map<String, ParamDefinition> generatedStaticWorkflowParamDefs(Workflow workflow) { Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>(); Map<String, ParamDefinition> defaultWorkflowParams = defaultParamManager.getDefaultWorkflowParams(); // merge default workflow params Param...
@Test public void testStaticWorkflowParamMerge() { workflow.getParams().put("p1", ParamDefinition.buildParamDefinition("p1", "d1")); when(defaultParamManager.getDefaultWorkflowParams()) .thenReturn(singletonMap("p2", ParamDefinition.buildParamDefinition("p2", "d2"))); Map<String, ParamDefinition> ...
public void wakeup() { commandConsumer.wakeup(); }
@Test public void shouldWakeUp() { // When: commandTopic.wakeup(); //Then: verify(commandConsumer).wakeup(); }
@Override public ImportResult importItem(UUID jobId, IdempotentImportExecutor idempotentExecutor, AD authData, MediaContainerResource data) throws Exception { PhotosContainerResource photosResource = MediaContainerResource.mediaToPhoto(data); ImportResult photosResult = photosImporter .importIte...
@Test public void shouldHandleVariousInputs() throws Exception { assertEquals(ImportResult.OK, mediaImporter.importItem(null, null, null, new MediaContainerResource(null, null, null))); assertEquals(ImportResult.OK, mediaImporter .importItem(null, null, null, new MediaContainerReso...
static AnnotatedClusterState generatedStateFrom(final Params params) { final ContentCluster cluster = params.cluster; final ClusterState workingState = ClusterState.emptyState(); final Map<Node, NodeStateReason> nodeStateReasons = new HashMap<>(); for (final NodeInfo nodeInfo : cluster....
@Test void distributor_nodes_are_not_implicitly_transitioned_to_maintenance_mode() { final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp(); final ClusterStateGenerator.Params params = fixture.generatorParams() .currentTimeInMillis(10_000) ...
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test public void testDecodeMultipleDynamicStruct2() { String rawInput = "0x00000000000000000000000000000000000000000000000000000000000000c0" + "0000000000000000000000000000000000000000000000000000000000000180" + "000000000000000000000000000000...
@Override public MatchType convert(@NotNull String type) { if (type.contains(DELIMITER)) { String[] matchType = type.split(DELIMITER); return new MatchType(RateLimitType.valueOf(matchType[0].toUpperCase()), matchType[1]); } return new MatchType(RateLimitType.valueOf(t...
@Test @SuppressWarnings("deprecation") public void testConvertStringTypeMethodOnly() { MatchType matchType = target.convert("httpmethod"); assertThat(matchType).isNotNull(); assertThat(matchType.getType()).isEqualByComparingTo(RateLimitType.HTTPMETHOD); assertThat(matchType.getMa...
public void ensureFolder(String parentPath, String name) throws IOException, InvalidTokenException { Map<String, Object> rawFolder = new LinkedHashMap<>(); rawFolder.put("name", name); String url; try { url = getUriBuilder() .setPath(API_PATH_PREFIX + "/mounts/primar...
@Test public void testEnsureFolderTokenExpired() throws Exception { when(credentialFactory.refreshCredential(credential)) .then( (InvocationOnMock invocation) -> { final Credential cred = invocation.getArgument(0); cred.setAccessToken("acc1"); return c...
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldSupportUdfParameterAnnotation() { final UdfFactory substring = FUNC_REG.getUdfFactory(FunctionName.of("somefunction")); final KsqlScalarFunction function = substring.getFunction( ImmutableList.of( SqlArgument.of(SqlTypes.STRING), SqlArgument.of(SqlTypes....
@ProtoFactory public static MediaType fromString(String tree) { if (tree == null || tree.isEmpty()) throw CONTAINER.missingMediaType(); Matcher matcher = TREE_PATTERN.matcher(tree); return parseSingleMediaType(tree, matcher, false); }
@Test(expected = EncodingException.class) public void testWrongQuoting() { MediaType.fromString("application/json;charset= \"UTF-8"); }
public @NonNull String fastTail(int numChars, Charset cs) throws IOException { try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { long len = raf.length(); // err on the safe side and assume each char occupies 4 bytes // additional 1024 byte margin is to bring us ...
@Test public void tail() throws Exception { File f = tmp.newFile(); FileUtils.copyURLToFile(getClass().getResource("ascii.txt"), f); String whole = Files.readString(f.toPath(), Charset.defaultCharset()); TextFile t = new TextFile(f); String tailStr = whole.substring(whole.len...
@Udf(description = "Converts a string representation of a date in the given format" + " into a DATE value.") public Date parseDate( @UdfParameter( description = "The string representation of a date.") final String formattedDate, @UdfParameter( description = "The format pattern sh...
@Test public void shouldThrowOnUnsupportedFields() { // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> udf.parseDate("2021-12-01 05:40:34", "yyyy-MM-dd HH:mm:ss")); // Then: assertThat(e.getMessage(), is("Failed to parse date '2021-12-01 05:40:34' with form...
static boolean isMulticastAddress(final String hostAndPort) { ParseResult result = tryParseIpV4(hostAndPort); if (null != result) { final String host = result.host; for (int i = 0, dotIndex = 0, end = host.length() - 1; i <= end; i++) { fin...
@Test void shouldThrowNullPointerExceptionIfValueIsNull() { assertThrowsExactly(NullPointerException.class, () -> SocketAddressParser.isMulticastAddress(null)); }
@Override public ConnectHeaders duplicate() { return new ConnectHeaders(this); }
@Test public void shouldDuplicateAndAlwaysReturnEquivalentButDifferentObject() { assertEquals(headers, headers.duplicate()); assertNotSame(headers, headers.duplicate()); }
@Override public String name() { return name; }
@Test public void testNotExposeTableProperties() { Configuration conf = new Configuration(); conf.set("iceberg.hive.table-property-max-size", "0"); HiveTableOperations ops = new HiveTableOperations(conf, null, null, catalog.name(), DB_NAME, "tbl"); TableMetadata metadata = mock(TableMetadata.c...
@Override public void replay( long offset, long producerId, short producerEpoch, CoordinatorRecord record ) throws RuntimeException { ApiMessageAndVersion key = record.key(); ApiMessageAndVersion value = record.value(); switch (key.version()) { ...
@Test public void testReplayGroupMetadataWithNullValue() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class); CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class); ...
@Override public void register(ConnectRestExtensionContext restPluginContext) { log.trace("Registering JAAS basic auth filter"); restPluginContext.configurable().register(new JaasBasicAuthFilter(configuration.get())); log.trace("Finished registering JAAS basic auth filter"); }
@SuppressWarnings("unchecked") @Test public void testJaasConfigurationNotOverwritten() { ArgumentCaptor<JaasBasicAuthFilter> jaasFilter = ArgumentCaptor.forClass(JaasBasicAuthFilter.class); Configurable<? extends Configurable<?>> configurable = mock(Configurable.class); when(configurable...
@Override @DSTransactional // 多数据源,使用 @DSTransactional 保证本地事务,以及数据源的切换 public void updateTenant(TenantSaveReqVO updateReqVO) { // 校验存在 TenantDO tenant = validateUpdateTenant(updateReqVO.getId()); // 校验租户名称是否重复 validTenantNameDuplicate(updateReqVO.getName(), updateReqVO.getId()); ...
@Test public void testUpdateTenant_notExists() { // 准备参数 TenantSaveReqVO reqVO = randomPojo(TenantSaveReqVO.class); // 调用, 并断言异常 assertServiceException(() -> tenantService.updateTenant(reqVO), TENANT_NOT_EXISTS); }
private synchronized boolean validateClientAcknowledgement(long h) { if (h < 0) { throw new IllegalArgumentException("Argument 'h' cannot be negative, but was: " + h); } if (h > MASK) { throw new IllegalArgumentException("Argument 'h' cannot be larger than 2^32 -1, but wa...
@Test public void testValidateClientAcknowledgement_rollover_edgecase5() throws Exception { // Setup test fixture. final long MAX = new BigInteger( "2" ).pow( 32 ).longValue() - 1; final long h = 3; final long oldH = MAX - 2; final Long lastUnackedX = 4L; // Exec...
@Override public Collection<DelayMeasurementStatHistory> getDmHistoricalStats( MdId mdName, MaIdShort maName, MepId mepId, SoamId dmId) throws SoamConfigException, CfmConfigException { MepEntry mep = cfmMepService.getMep(mdName, maName, mepId); if (mep == null || mep....
@Test public void testGetDmHistoryStats() throws CfmConfigException, SoamConfigException { expect(deviceService.getDevice(DEVICE_ID1)).andReturn(device1).anyTimes(); replay(deviceService); expect(mepService.getMep(MDNAME1, MANAME1, MEPID1)).andReturn(mep1).anyTimes(); replay(mepServ...
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createNetwork(InputStream input) throws IOException { log.trace(String.format(MESSAGE, "CREATE")); String inputStr = IOUtils.toString(input, REST_UTF8); if (!haService.isActive() ...
@Test public void testCreateNetworkWithDuplicatedId() { mockOpenstackNetworkAdminService.createNetwork(anyObject()); expectLastCall().andThrow(new IllegalArgumentException()); replay(mockOpenstackNetworkAdminService); expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes...
public MyNewIssuesNotification newMyNewIssuesNotification(Map<String, UserDto> assigneesByUuid) { verifyAssigneesByUuid(assigneesByUuid); return new MyNewIssuesNotification(new DetailsSupplierImpl(assigneesByUuid)); }
@Test public void newMyNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_fails_with_NPE_if_ruleKey_is_null() { MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(()...
public Set<String> heartbeatTopics() throws InterruptedException { return listTopics().stream() .filter(this::isHeartbeatTopic) .collect(Collectors.toSet()); }
@Test public void heartbeatTopicsTest() throws InterruptedException { MirrorClient client = new FakeMirrorClient(Arrays.asList("topic1", "topic2", "heartbeats", "source1.heartbeats", "source2.source1.heartbeats", "source3.heartbeats")); Set<String> heartbeatTopics = client.heartbeatTopic...
public void start() { heartbeatExecutor.scheduleAtFixedRate( new Runnable() { @Override public void run() { // Because consul check set pass triggers consul // server write operation,frequently heart beat will impact consul // performance,so heart beat takes long cycle and switcher che...
@Test public void testStart() throws InterruptedException { heartbeatManager.start(); Map<String, Long> mockServices = new HashMap<String, Long>(); int serviceNum = 5; for (int i = 0; i < serviceNum; i++) { String serviceid = "service" + i; mockServices.put(s...
public static InMemorySorter create(Options options) { return new InMemorySorter(options); }
@Test public void testManySorters() throws Exception { SorterTestUtils.testRandom( () -> InMemorySorter.create(new InMemorySorter.Options()), 1000000, 10); }
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(containerService.isContainer(file)) { return PathAttributes.EMPTY; } return th...
@Test public void testFindFile() throws Exception { final Path container = new SpectraDirectoryFeature(session, new SpectraWriteFeature(session)).mkdir( new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus()); ...
@Override public Collection<Integer> getOutboundPorts(EndpointQualifier endpointQualifier) { final AdvancedNetworkConfig advancedNetworkConfig = node.getConfig().getAdvancedNetworkConfig(); if (advancedNetworkConfig.isEnabled()) { EndpointConfig endpointConfig = advancedNetworkConfig.get...
@Test public void testGetOutboundPorts_acceptsSpaceAsASeparator() { networkConfig.addOutboundPortDefinition("29000 29001"); Collection<Integer> outboundPorts = serverContext.getOutboundPorts(MEMBER); assertThat(outboundPorts).hasSize(2); assertThat(outboundPorts).containsExactlyInAn...
@Override public String getSQLListOfSchemas( DatabaseMeta databaseMeta ) { String databaseName = getDatabaseName(); if ( databaseMeta != null ) { databaseName = databaseMeta.environmentSubstitute( databaseName ); } return "SELECT SCHEMA_NAME AS \"name\" FROM " + databaseName + ".INFORMATION_SCHE...
@Test public void testGetSQLListOfSchemasWithoutParameter() { SnowflakeHVDatabaseMeta snowflakeHVDatabaseMeta = spy( new SnowflakeHVDatabaseMeta() ); snowflakeHVDatabaseMeta.getSQLListOfSchemas(); verify( snowflakeHVDatabaseMeta ).getSQLListOfSchemas( null ); }
public String format(DataTable table) { StringBuilder result = new StringBuilder(); formatTo(table, result); return result.toString(); }
@Test void should_print() { DataTable table = tableOf("hello"); assertEquals("| hello |\n", formatter.format(table)); }
@Override public boolean shouldHandle(Request request) { // we don't check the method here because we want to return 405 if it is anything but POST return MUX_URI_PATH.equals(request.getURI().getPath()); }
@Test(dataProvider = "multiplexerConfigurations") public void testIsMultiplexedRequest(MultiplexerRunMode multiplexerRunMode) throws Exception { MultiplexedRequestHandlerImpl multiplexer = createMultiplexer(null, multiplexerRunMode); RestRequest request = fakeMuxRestRequest(); assertTrue(multiplexer.sho...
public void setStayDuration(double stayDuration) { this.stayDuration = stayDuration; }
@Test public void setStayDuration() { SAExposureConfig saExposureConfig = new SAExposureConfig(1,1,true); saExposureConfig.setStayDuration(2); assertEquals(2, saExposureConfig.getStayDuration(), 0.2); }
public IndicesStatsResponse indicesStats(String... indices) { return execute(() -> { Request request = new Request("GET", "/" + (indices.length > 0 ? (String.join(",", indices) + "/") : "") + "_stats"); request.addParameter("level", "shards"); Response response = restHighLevelClient.getLowLevelCli...
@Test public void should_rethrow_ex_on_indices_stat_fail() throws Exception { when(restClient.performRequest(argThat(new RawRequestMatcher( "GET", "/_stats")))) .thenThrow(IOException.class); assertThatThrownBy(() -> underTest.indicesStats()) .isInstanceOf(ElasticsearchException.class...
@Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof ChangesOnMyIssuesNotification)) { return null; } ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif; if (notification.getChange() instanceof AnalysisChange) { ...
@Test public void formats_returns_html_message_for_multiple_issues_of_same_rule_on_same_project_on_master_when_analysis_change() { Project project = newProject("1"); String ruleName = randomAlphabetic(8); String host = randomAlphabetic(15); Rule rule = newRule(ruleName, randomRuleTypeHotspotExcluded()...
@Override public boolean login() throws LoginException { Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("User name"); callbacks[1] = new PasswordCallback("Password", false); try { handler.handle(callbacks); } catch (IOException | Unsuppo...
@Test public void testLogin() throws LoginException { LoginContext context = new LoginContext("LDAPLogin", new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.lengt...
public String removeComments( String script ) { if ( script == null ) { return null; } StringBuilder result = new StringBuilder(); MODE mode = MODE.SQL; char currentStringChar = 0; for ( int i = 0; i < script.length(); i++ ) { char ch = script.charAt( i ); char nextCh = i <...
@Test public void testRemoveComments() { assertEquals( null, sqlScriptParser.removeComments( null ) ); assertEquals( "", sqlScriptParser.removeComments( "" ) ); assertEquals( "SELECT col1 FROM test", sqlScriptParser.removeComments( "SELECT col1 FROM test" ) ); assertEquals( "SELECT col1 FROM test ", s...
String zone(String podName) { String nodeUrlString = String.format("%s/api/v1/nodes/%s", kubernetesMaster, nodeName(podName)); return extractZone(callGet(nodeUrlString)); }
@Test public void zoneFailureDomain() throws JsonProcessingException { // given String podName = "pod-name"; stub(String.format("/api/v1/namespaces/%s/pods/%s", NAMESPACE, podName), pod("hazelcast-0", NAMESPACE, "node-name")); //language=JSON String nodeResponse = """ ...
@Override public InputStream getTaskStateFile(String state, String name) throws IOException { return getTaskStateFile(state, name, false, true); }
@Test void shouldGetTaskStateFileFromTriggerContext() throws IOException { // Given StorageInterface storageInterface = Mockito.mock(StorageInterface.class); InputStream is = new ByteArrayInputStream(new byte[0]); Mockito.when(storageInterface.get(any(), eq(URI.create("/namespace/sta...
public static void removeDupes( final List<CharSequence> suggestions, List<CharSequence> stringsPool) { if (suggestions.size() < 2) return; int i = 1; // Don't cache suggestions.size(), since we may be removing items while (i < suggestions.size()) { final CharSequence cur = suggestions.get(i...
@Test public void testRemoveDupesOnlyDupes() throws Exception { ArrayList<CharSequence> list = new ArrayList<>(Arrays.<CharSequence>asList("typed", "typed", "typed", "typed", "typed")); IMEUtil.removeDupes(list, mStringPool); Assert.assertEquals(1, list.size()); Assert.assertEquals("typed", li...
public ColumnConstraints getConstraints() { return constraints; }
@Test public void shouldReturnEmptyConstraints() { // Given: final TableElement valueElement = new TableElement(NAME, new Type(SqlTypes.STRING)); // Then: assertThat(valueElement.getConstraints(), is(NO_COLUMN_CONSTRAINTS)); }
@Override @Deprecated public <VR> KStream<K, VR> transformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, ? extends VR> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransformerSup...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullValueTransformerSupplierOnTransformValuesWithNamedAndStores() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.transformValues( (org.apache.kafk...
public boolean isSameShardingCondition() { Collection<String> hintStrategyTables = findHintStrategyTables(sqlStatementContext); return 1 == hintStrategyTables.size() || subqueryContainsShardingCondition && 1 == conditions.size(); }
@Test void assertIsSameShardingConditionFalse() { ShardingConditions shardingConditions = createMultipleShardingConditions(); assertFalse(shardingConditions.isSameShardingCondition()); }
public long lastAppliedOffset() { return metrics.lastAppliedOffset(); }
@Test public void testCreateAndClose() throws Exception { MockFaultHandler faultHandler = new MockFaultHandler("testCreateAndClose"); try (MetadataLoader loader = new MetadataLoader.Builder(). setFaultHandler(faultHandler). setHighWaterMarkAccessor(OptionalLong::empty...
@JsonProperty public URI getUri() { return uri; }
@Test public void testQueryDividedIntoSplitsShouldHaveCorrectSpacingBetweenTimes() { Instant now = LocalDateTime.of(2019, 10, 2, 7, 26, 56, 0).toInstant(UTC); PrometheusConnectorConfig config = getCommonConfig(prometheusHttpServer.resolve("/prometheus-data/prometheus-metrics.json")); Pro...
public FEELFnResult<BigDecimal> invoke(@ParameterName("string") String string) { if ( string == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null")); } else { return FEELFnResult.ofResult(NumberEvalHelper.getBigDecimalOrNull...
@Test void invokeNull() { FunctionTestUtil.assertResultError(stringLengthFunction.invoke(null), InvalidParametersEvent.class); }
public Set<DatabaseTableName> getCachedTableNames() { // use partition cache to get all cached table names because partition cache is more accurate, // table cache will be cached when user use `use catalog.db` command. return partitionCache.asMap().keySet().stream().map(hivePartitionName -> ...
@Test public void testGetCachedName() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); HiveCacheUpdateProcessor processor = new HiveCacheUpdateProcessor( "hive_catalog...
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowMaterializedViewPattern() throws AnalysisException, DdlException { ctx.setCurrentUserIdentity(UserIdentity.ROOT); ctx.setCurrentRoleIds(Sets.newHashSet(PrivilegeBuiltinConstants.ROOT_ROLE_ID)); ShowMaterializedViewsStmt stmt = new ShowMaterializedViewsStmt("testDb"...
public Category name(String name) { this.name = name; return this; }
@Test public void nameTest() { // TODO: test name }
public int capacity() { return capacity; }
@Test void shouldCalculateCapacityForBuffer() { assertThat(broadcastReceiver.capacity(), is(CAPACITY)); }
public static Catalog loadIcebergCatalog(SparkSession spark, String catalogName) { CatalogPlugin catalogPlugin = spark.sessionState().catalogManager().catalog(catalogName); Preconditions.checkArgument( catalogPlugin instanceof HasIcebergCatalog, String.format( "Cannot load Iceberg ca...
@Test public void testLoadIcebergCatalog() throws Exception { spark.conf().set("spark.sql.catalog.test_cat", SparkCatalog.class.getName()); spark.conf().set("spark.sql.catalog.test_cat.type", "hive"); Catalog catalog = Spark3Util.loadIcebergCatalog(spark, "test_cat"); Assert.assertTrue( "Shoul...
@Override public int compare(final List<String> o1, final List<String> o2) { if (o1.size() < o2.size()) { return -1; } else if (o1.size() > o2.size()) { return 1; } else { int index = 0; while (index < o1.size()) { String item1...
@Test void testListsWithSameElementsIgnoringCaseAreEqual() { assertEquals(0, toTest.compare(List.of("Mum"), List.of("mum"))); assertEquals(0, toTest.compare(List.of("mum", "Dad"), List.of("mum", "dad"))); }
@VisibleForTesting String importSingleAlbum(UUID jobId, TokensAndUrlAuthData authData, PhotoAlbum inputAlbum) throws IOException, InvalidTokenException, PermissionDeniedException, UploadErrorException { // Set up album GoogleAlbum googleAlbum = new GoogleAlbum(); googleAlbum.setTitle(GooglePhotosImp...
@Test public void importAlbum() throws Exception { // Set up String albumName = "Album Name"; String albumDescription = "Album description"; PhotoAlbum albumModel = new PhotoAlbum(OLD_ALBUM_ID, albumName, albumDescription); GoogleAlbum responseAlbum = new GoogleAlbum(); responseAlbum.setId(NE...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 7) { onInvalidDataReceived(device, data); return; } // First byte: flags int offset = 0; final int flags = data.getIntValue(Data.FORMAT_UINT8,...
@Test public void onBloodPressureMeasurementReceived_minimal() { final DataReceivedCallback callback = new BloodPressureMeasurementDataCallback() { @Override public void onBloodPressureMeasurementReceived(@NonNull final BluetoothDevice device, final float systolic, final float diastolic, final...
@GetMapping public DeferredResult<ResponseEntity<ApolloConfigNotification>> pollNotification( @RequestParam(value = "appId") String appId, @RequestParam(value = "cluster") String cluster, @RequestParam(value = "namespace", defaultValue = ConfigConsts.NAMESPACE_APPLICATION) String namespace, @R...
@Test public void testPollNotificationWithDefaultNamespaceAsFile() throws Exception { String namespace = String.format("%s.%s", defaultNamespace, "properties"); when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(defaultNamespace); String someWatchKey = "someKey"; String anotherWatchKey = "...
@SuppressWarnings("WeakerAccess") public Map<String, Object> getAdminConfigs(final String clientId) { final Map<String, Object> clientProvidedProps = getClientPropsWithPrefix(ADMIN_CLIENT_PREFIX, AdminClientConfig.configNames()); final Map<String, Object> props = new HashMap<>(); props.putA...
@Test public void shouldSupportNonPrefixedAdminConfigs() { props.put(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, 10); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> configs = streamsConfig.getAdminConfigs(clientId); assertEquals(10, confi...
@Override public boolean matches(Job localJob, Job storageProviderJob) { if (storageProviderJob.getVersion() == localJob.getVersion() + 1 && localJob.hasState(PROCESSING) && !storageProviderJob.hasState(PROCESSING)) { return jobSteward.getThreadProcessingJob(localJob) == null; ...
@Test void ifJobIsHavingConcurrentStateChangeAndStorageProviderJobIsAlsoProcessingItWillNotMatch() { final Job localJob = aJobInProgress().withVersion(2).build(); final Job storageProviderJob = aCopyOf(localJob).withVersion(3).build(); lenient().when(jobSteward.getThreadProcessingJob(localJ...
public CMap parsePredefined(String name) throws IOException { try (RandomAccessRead randomAccessRead = getExternalCMap(name)) { // deactivate strict mode strictMode = false; return parse(randomAccessRead); } }
@Test void testUniJIS_UCS2_H() throws IOException { CMap cMap = new CMapParser().parsePredefined("UniJIS-UCS2-H"); assertEquals(34, cMap.toCID(new byte[] { 0, 65 }), "UniJIS-UCS2-H CID 65 -> 34"); }
protected static boolean isDuplicate( List<? extends SharedObjectInterface> objects, SharedObjectInterface object ) { String newName = object.getName(); for ( SharedObjectInterface soi : objects ) { if ( soi.getName().equalsIgnoreCase( newName ) ) { return true; } } return false; }
@Test public void isDuplicate_DifferentCase() { assertTrue( isDuplicate( singletonList( mockObject( "qwerty" ) ), mockObject( "Qwerty" ) ) ); }
public static Map<String, String> getClientMd5Map(String configKeysString) { Map<String, String> md5Map = new HashMap<>(5); if (null == configKeysString || "".equals(configKeysString)) { return md5Map; } int start = 0; List<String> tmpList = new Arra...
@Test void testGetClientMd5MapForNewProtocol() { String configKeysString = "test0" + MD5Util.WORD_SEPARATOR_CHAR + "test1" + MD5Util.WORD_SEPARATOR_CHAR + "test2" + MD5Util.WORD_SEPARATOR_CHAR + "test3" + MD5Util.LINE_SEPARATOR_CHAR; Map<String, Strin...
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = trees.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = b; for (int i...
@Test public void testPuma8nhLS() { test(Loss.ls(), "puma8nh", Puma8NH.formula, Puma8NH.data, 3.2482); }
@Override public boolean isOperational() { if (nodeOperational) { return true; } boolean flag = false; try { flag = checkOperational(); } catch (InterruptedException e) { LOG.trace("Interrupted while checking ES node is operational", e); Thread.currentThread().interrupt();...
@Test public void isOperational_should_not_be_os_language_sensitive() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()) .thenThrow(new ElasticsearchException(new ExecutionException(new ConnectException("Connexion refusée")))); EsManagedProcess underTest ...
public static PTransformMatcher emptyFlatten() { return new PTransformMatcher() { @Override public boolean matches(AppliedPTransform<?, ?, ?> application) { return (application.getTransform() instanceof Flatten.PCollections) && application.getInputs().isEmpty(); } @Overr...
@Test public void emptyFlattenWithEmptyFlatten() { AppliedPTransform application = AppliedPTransform.of( "EmptyFlatten", Collections.emptyMap(), Collections.singletonMap( new TupleTag<Integer>(), PCollection.createPrimitiveOutputInternal(...
public static <T> String render(ClassPluginDocumentation<T> classPluginDocumentation) throws IOException { return render("task", JacksonMapper.toMap(classPluginDocumentation)); }
@SuppressWarnings("unchecked") @Test void state() throws IOException { PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader()); RegisteredPlugin scan = pluginScanner.scan(); Class<Set> set = scan.findClass(Set.class.getName()).orElseThrow(); ...
@Override public CharSequence toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder sb = new XmlStringBuilder(this, xmlEnvironment); return sb.attribute(ELEM_URI, uri) .optAttribute(ELEM_MEDIA_TYPE, mediaType) .optAttribute(ELEM_WIDTH, width) .optAtt...
@Test public void testMinimal() { ThumbnailElement minimal = new ThumbnailElement("cid:sha1+ffd7c8d28e9c5e82afea41f97108c6b4@bob.xmpp.org"); assertXmlSimilar("<thumbnail xmlns='urn:xmpp:thumbs:1'\n" + "uri='cid:sha1+ffd7c8d28e9c5e82afea41f97108c6b4@bob.xmpp.org'/>", ...
@Override public Path move(final Path source, final Path target, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { if(containerService.isContainer(source)) { if(new SimplePathPredicate(sourc...
@Test public void testMoveWithRenameDifferentDataRoomSameFilename() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room1 = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(P...
@Override public void createOrUpdate(final String path, final Object data) { zkClient.createOrUpdate(path, data, CreateMode.PERSISTENT); }
@Test public void testOnAppAuthChangedCreate() { AppAuthData appAuthData = AppAuthData.builder().appKey(MOCK_APP_KEY).appSecret(MOCK_APP_SECRET).build(); String appAuthPath = DefaultPathConstants.buildAppAuthPath(appAuthData.getAppKey()); zookeeperDataChangedListener.onAppAuthChanged(Immuta...
@Override public Range<T> span() { if (rangeBitSetMap.isEmpty()) { return null; } Entry<Long, BitSet> firstSet = rangeBitSetMap.firstEntry(); Entry<Long, BitSet> lastSet = rangeBitSetMap.lastEntry(); int first = firstSet.getValue().nextSetBit(0); int last ...
@Test public void testNPE() { OpenLongPairRangeSet<LongPair> set = new OpenLongPairRangeSet<>(consumer); assertNull(set.span()); }