focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void flushAllTracks() { parallelismDetector.run(() -> { ArrayList<String> allKnownKeys = newArrayList(tracksUnderConstruction.keySet()); closeAndPublish(allKnownKeys); }); }
@Test public void flushAllTracks() { String ONE = "[RH],STARS,D21_B,03/24/2018,14:42:00.130,N518SP,C172,,5256,032,110,186,042.92704,-083.70974,3472,5256,-14.5730,42.8527,1,Y,A,D21,,POL,ARB,1446,ARB,ACT,VFR,,01500,,,,,,S,1,,0,{RH}"; String TWO = "[RH],STARS,D21_B,03/24/2018,14:42:04.750,N518SP,C172,...
public static MetadataBlock newEos() { return new MetadataBlock(); }
@Test public void emptyDataBlockCorrectness() throws IOException { testSerdeCorrectness(MetadataBlock.newEos()); }
@ApiOperation(value = "Delete common relations (deleteCommonRelations)", notes = "Deletes all the relations ('from' and 'to' direction) for the specified entity and relation type group: 'COMMON'. " + SECURITY_CHECKS_ENTITY_DESCRIPTION) @PreAuthorize("hasAnyAuthority('SYS_ADMIN','TENA...
@Test public void testDeleteRelations() throws Exception { final int numOfDevices = 30; createDevicesByFrom(numOfDevices, BASE_DEVICE_NAME + " from"); createDevicesByTo(numOfDevices, BASE_DEVICE_NAME + " to"); String urlTo = String.format("/api/relations?toId=%s&toType=%s", ...
@Override public Map<String, Object> getAttributes(boolean addSecureFields) { Map<String, Object> materialMap = new HashMap<>(); materialMap.put("type", "package"); materialMap.put("plugin-id", getPluginId()); Map<String, String> repositoryConfigurationMap = packageDefinition.getRepo...
@Test void shouldGetAttributesWithSecureFields() { PackageMaterial material = createPackageMaterialWithSecureConfiguration(); Map<String, Object> attributes = material.getAttributes(true); assertThat(attributes.get("type")).isEqualTo("package"); assertThat(attributes.get("plugin-id"...
@Override public int totalSize() { return payload != null ? payload.length : 0; }
@Test public void totalSize_whenEmpty() { HeapData heapData = new HeapData(new byte[0]); assertEquals(0, heapData.totalSize()); }
@Override public void write(final MySQLPacketPayload payload, final Object value) { if (value instanceof byte[]) { payload.writeBytesLenenc((byte[]) value); } else { payload.writeStringLenenc(value.toString()); } }
@Test void assertWrite() { byte[] input = {0x0a, 0x33, 0x18, 0x01, 0x4a, 0x08, 0x0a, (byte) 0x9a, 0x01, 0x18, 0x01, 0x4a, 0x6f}; byte[] expected = {0x0d, 0x0a, 0x33, 0x18, 0x01, 0x4a, 0x08, 0x0a, (byte) 0x9a, 0x01, 0x18, 0x01, 0x4a, 0x6f}; ByteBuf actual = Unpooled.wrappedBuffer(new byte[exp...
public static Object get(Object object, int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } if (object instanceof Map) { Map map = (Map) object; Iterator iterator = map.entrySet().iterator(); r...
@Test void testGetArray4() { assertThrows(ArrayIndexOutOfBoundsException.class, () -> { CollectionUtils.get(new int[] {}, 0); }); }
public static HttpConfigResponse createFromConfig(ConfigResponse config) { return new HttpConfigResponse(config); }
@Test public void require_that_response_is_created_from_config() throws IOException { long generation = 1L; ConfigPayload payload = ConfigPayload.fromInstance(new SimpletypesConfig(new SimpletypesConfig.Builder())); ConfigResponse configResponse = SlimeConfigResponse.fromConfigPayload(payloa...
public String getTopicName(AsyncMockDefinition definition, EventMessage eventMessage) { logger.debugf("AsyncAPI Operation {%s}", definition.getOperation().getName()); // Produce service name part of topic name. String serviceName = definition.getOwnerService().getName().replace(" ", ""); servic...
@Test void testGetTopicName() { AmazonSNSProducerManager producerManager = new AmazonSNSProducerManager(); Service service = new Service(); service.setName("Streetlights API"); service.setVersion("0.1.0"); Operation operation = new Operation(); operation.setName("RECEIVE receive...
public List<String> split( String script ) { if ( script == null ) { return Collections.emptyList(); } List<String> result = new ArrayList<String>(); MODE mode = MODE.SQL; char currentStringChar = 0; int statementStart = 0; for ( int i = 0; i < script.length(); i++ ) { char ch...
@Test public void testSplit() { assertEquals( Arrays.asList( new String[0] ), sqlScriptParser.split( null ) ); assertEquals( Arrays.asList( new String[0] ), sqlScriptParser.split( "" ) ); assertEquals( Arrays.asList( new String[0] ), sqlScriptParser.split( " " ) ); assertEquals( Arrays.asList( "SELECT...
public EndpointResponse accessDeniedFromKafkaResponse(final Exception e) { return constructAccessDeniedFromKafkaResponse(errorMessages.kafkaAuthorizationErrorMessage(e)); }
@Test public void shouldReturnForbiddenKafkaResponse() { final EndpointResponse response = errorHandler.accessDeniedFromKafkaResponse(exception); assertThat(response.getStatus(), is(403)); assertThat(response.getEntity(), is(instanceOf(KsqlErrorMessage.class))); assertThat(((KsqlErrorMessage) response...
@Override public Long createDictType(DictTypeSaveReqVO createReqVO) { // 校验字典类型的名字的唯一性 validateDictTypeNameUnique(null, createReqVO.getName()); // 校验字典类型的类型的唯一性 validateDictTypeUnique(null, createReqVO.getType()); // 插入字典类型 DictTypeDO dictType = BeanUtils.toBean(crea...
@Test public void testCreateDictType_success() { // 准备参数 DictTypeSaveReqVO reqVO = randomPojo(DictTypeSaveReqVO.class, o -> o.setStatus(randomEle(CommonStatusEnum.values()).getStatus())) .setId(null); // 避免 id 被赋值 // 调用 Long dictTypeId = dictTypeServi...
static JarFileWithEntryClass findOnlyEntryClass(Iterable<File> jarFiles) throws IOException { List<JarFileWithEntryClass> jarsWithEntryClasses = new ArrayList<>(); for (File jarFile : jarFiles) { findEntryClass(jarFile) .ifPresent( entryClass -...
@Test void testFindOnlyEntryClassSingleJar() throws IOException { File jarFile = TestJob.getTestJobJar(); JarManifestParser.JarFileWithEntryClass jarFileWithEntryClass = JarManifestParser.findOnlyEntryClass(ImmutableList.of(jarFile)); assertThat(jarFileWithEntryClass.getEnt...
public ProtocolBuilder buffer(Integer buffer) { this.buffer = buffer; return getThis(); }
@Test void buffer() { ProtocolBuilder builder = new ProtocolBuilder(); builder.buffer(1024); Assertions.assertEquals(1024, builder.build().getBuffer()); }
@Override public SelLong assignOps(SelOp op, SelType rhs) { SelTypeUtil.checkTypeMatch(this.type(), rhs.type()); long another = ((SelLong) rhs).val; switch (op) { case ASSIGN: this.val = another; // direct assignment return this; case ADD_ASSIGN: this.val += another; ...
@Test public void testAssignOps() { SelType obj = SelLong.of(2); SelType res = orig.assignOps(SelOp.ASSIGN, obj); assertEquals("LONG: 2", res.type() + ": " + res); res = orig.assignOps(SelOp.ASSIGN, SelLong.of(3)); assertEquals("LONG: 2", obj.type() + ": " + obj); assertEquals("LONG: 3", res.t...
@Override public String toString() { return getClass().getSimpleName() + "[application=" + getApplication() + ", periodMillis=" + periodMillis + ", counters=" + getCounters() + ']'; }
@Test public void testToString() throws SchedulerException { final Collector collector = createCollectorWithOneCounter(); assertToStringNotEmpty("collector", collector); assertToStringNotEmpty("java", new JavaInformations(null, false)); assertToStringNotEmpty("thread", new ThreadInformations(Thread.current...
@Override @SuppressWarnings({"CastCanBeRemovedNarrowingVariableType", "unchecked"}) public E peek() { final E[] buffer = consumerBuffer; final long index = consumerIndex; final long mask = consumerMask; final long offset = modifiedCalcElementOffset(index, mask); Object e = lvElement(buffer, off...
@Test(dataProvider = "populated") public void peek_whenPopulated(MpscGrowableArrayQueue<Integer> queue) { assertThat(queue.peek()).isNotNull(); assertThat(queue).hasSize(POPULATED_SIZE); }
@Override public <PS extends Serializer<P>, P> KeyValueIterator<K, V> prefixScan(final P prefix, final PS prefixKeySerializer) { Objects.requireNonNull(prefix); Objects.requireNonNull(prefixKeySerializer); final NextIteratorFunction<K, V, ReadOnlyKeyValueStore<K, V>> nextIteratorFunction = n...
@Test public void shouldThrowNoSuchElementExceptionWhileNextForPrefixScan() { stubOneUnderlying.put("a", "1"); try (final KeyValueIterator<String, String> keyValueIterator = theStore.prefixScan("a", new StringSerializer())) { keyValueIterator.next(); assertThrows(NoSuchElemen...
public static IpAddress makeMaskPrefix(Version version, int prefixLength) { byte[] mask = makeMaskPrefixArray(version, prefixLength); return new IpAddress(version, mask); }
@Test(expected = IllegalArgumentException.class) public void testInvalidMakeTooLongMaskPrefixIPv4() { IpAddress ipAddress; ipAddress = IpAddress.makeMaskPrefix(IpAddress.Version.INET, 33); }
@Override public void setOriginalFile(Component file, OriginalFile originalFile) { storeOriginalFileInCache(originalFiles, file, originalFile); }
@Test public void setOriginalFile_throws_NPE_when_originalFile_is_null() { assertThatThrownBy(() -> underTest.setOriginalFile(SOME_FILE, null)) .isInstanceOf(NullPointerException.class) .hasMessage("originalFile can't be null"); }
public void addExtensionPoint( PluginInterface extensionPointPlugin ) { lock.writeLock().lock(); try { for ( String id : extensionPointPlugin.getIds() ) { extensionPointPluginMap.put( extensionPointPlugin.getName(), id, createLazyLoader( extensionPointPlugin ) ); } } finally { lock...
@Test public void addExtensionPointTest() throws KettlePluginException { ExtensionPointMap.getInstance().addExtensionPoint( pluginInterface ); assertEquals( ExtensionPointMap.getInstance().getTableValue( TEST_NAME, "testID" ), extensionPoint ); // Verify cached instance assertEquals( ExtensionPointMa...
public static USynchronized create(UExpression expression, UBlock block) { return new AutoValue_USynchronized(expression, block); }
@Test public void equality() { new EqualsTester() .addEqualityGroup(USynchronized.create(UFreeIdent.create("foo"), UBlock.create())) .addEqualityGroup(USynchronized.create(UFreeIdent.create("bar"), UBlock.create())) .testEquals(); }
@Override public int compareTo(final Version that) { String[] thisParts = version.split("\\."); String[] thatParts = that.version.split("\\."); int length = Math.max(thisParts.length, thatParts.length); for(int i = 0; i < length; i++) { int thisPart = i < thisParts.length...
@Test public void testCompare() { assertEquals(0, new Version("4").compareTo(new Version("4"))); assertEquals(0, new Version("4.1").compareTo(new Version("4.1"))); assertEquals(0, new Version("4.12").compareTo(new Version("4.12"))); assertEquals(-1, new Version("4.12").compareTo(new ...
public CompletableFuture<LookupTopicResult> getBroker(TopicName topicName) { long startTime = System.nanoTime(); final MutableObject<CompletableFuture> newFutureCreated = new MutableObject<>(); try { return lookupInProgress.computeIfAbsent(topicName, tpName -> { Compl...
@Test(invocationTimeOut = 3000) public void maxLookupRedirectsTest3() throws Exception { Field field = BinaryProtoLookupService.class.getDeclaredField("maxLookupRedirects"); field.setAccessible(true); field.set(lookup, 1); try { lookup.getBroker(topicName).get(); ...
public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrder() { return usingConfig(config.ignoringRepeatedFieldOrder()); }
@Test public void testCompareMultipleMessageTypes() { // Don't run this test twice. if (!testIsRunOnce()) { return; } expectThat( listOf( TestMessage2.newBuilder().addRString("foo").addRString("bar").build(), TestMessage3.newBuilder().addRString("baz"...
public InternalThreadLocal() { index = InternalThreadLocalMap.nextVariableIndex(); }
@Test void testInternalThreadLocal() { final AtomicInteger index = new AtomicInteger(0); final InternalThreadLocal<Integer> internalThreadLocal = new InternalThreadLocal<Integer>() { @Override protected Integer initialValue() { Integer v = index.getAndIncrem...
public int size() { return endpoints.size(); }
@Test void testSize() { Map<ListenerName, InetSocketAddress> endpointMap = Utils.mkMap( Utils.mkEntry(testListener, testSocketAddress)); assertEquals(1, Endpoints.fromInetSocketAddresses(endpointMap).size()); assertEquals(0, Endpoints.empty().size()); }
@Override public String getTableType() { return "kafka"; }
@Test public void testGetTableType() { assertEquals("kafka", provider.getTableType()); }
public static boolean isCompositeType(LogicalType logicalType) { if (logicalType instanceof DistinctType) { return isCompositeType(((DistinctType) logicalType).getSourceType()); } LogicalTypeRoot typeRoot = logicalType.getTypeRoot(); return typeRoot == STRUCTURED_TYPE || typ...
@Test void testIsCompositeTypeDistinctType() { DataType dataType = ROW(FIELD("f0", INT()), FIELD("f1", STRING())); DistinctType distinctType = DistinctType.newBuilder( ObjectIdentifier.of("catalog", "database", "type"), ...
public Map<String, String> asMap() { return pairs; }
@Test public void asMap() { OrderedProperties pairs = createTestKeyValues(); pairs.asMap().put("fifth", "5"); assertKeyOrder(pairs, "first", "second", "third", "FOURTH", "fifth"); }
public static Collection<String> getResourcesFromDirectory(File directory, Pattern pattern) { if (directory == null || directory.listFiles() == null) { return Collections.emptySet(); } return Arrays.stream(Objects.requireNonNull(directory.listFiles())) .flatMap(elem -...
@Test public void getResourcesFromDirectoryTest() { List<String> classPathElements = Arrays.asList(ResourceHelper.getClassPathElements()); Optional<String> testFolder = classPathElements.stream().filter(elem -> elem.contains("test-classes")).findFirst(); assertThat(testFolder...
public static <T> Deduplicate.Values<T> values() { return new Deduplicate.Values<>(DEFAULT_TIME_DOMAIN, DEFAULT_DURATION); }
@Test @Category({NeedsRunner.class, UsesTestStreamWithProcessingTime.class}) public void testProcessingTime() { Instant base = new Instant(0); TestStream<String> values = TestStream.create(StringUtf8Coder.of()) .advanceWatermarkTo(base) .addElements( Timestamp...
@Override public int leaveGroupEpoch() { return ShareGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH; }
@Test public void testLeaveGroupEpoch() { // Member should leave the group with epoch -1. ShareMembershipManager membershipManager = createMemberInStableState(); mockLeaveGroup(); membershipManager.leaveGroup(); assertEquals(MemberState.LEAVING, membershipManager.state()); ...
public void init(final InternalProcessorContext<KOut, VOut> context) { if (!closed) throw new IllegalStateException("The processor is not closed"); try { threadId = Thread.currentThread().getName(); internalProcessorContext = context; droppedRecordsSensor...
@Test public void shouldThrowStreamsExceptionIfExceptionCaughtDuringClose() { final ProcessorNode<Object, Object, Object, Object> node = new ProcessorNode<>(NAME, new ExceptionalProcessor(), Collections.emptySet()); assertThrows(StreamsException.class, () -> node.init(null)); }
public static String getGeneratedResourcesString(GeneratedResources generatedResources) throws JsonProcessingException { return objectMapper.writeValueAsString(generatedResources); }
@Test void getGeneratedResourcesString() throws JsonProcessingException { String fullClassName = "full.class.Name"; GeneratedResource generatedIntermediateResource = new GeneratedClassResource(fullClassName); String model = "foo"; LocalUri modelLocalUriId = new ReflectiveAppRoot(mode...
public List<Service> importServiceDefinition(String repositoryUrl, Secret repositorySecret, boolean disableSSLValidation, boolean mainArtifact) throws MockRepositoryImportException { log.info("Importing service definitions from {}", repositoryUrl); File localFile = null; Map<String, List<Stri...
@Test void testImportServiceDefinitionMainGrpcAndSecondaryPostman() { List<Service> services = null; try { File artifactFile = new File("target/test-classes/io/github/microcks/util/grpc/hello-v1.proto"); services = service.importServiceDefinition(artifactFile, null, new ArtifactInfo("he...
@Override public LinkEvent createOrUpdateLink(ProviderId providerId, LinkDescription linkDescription) { final DeviceId dstDeviceId = linkDescription.dst().deviceId(); final NodeId dstNodeId = mastershipService.getMasterFor(dstDeviceId); // Process lin...
@Test public final void testCreateOrUpdateLink() { ConnectPoint src = new ConnectPoint(DID1, P1); ConnectPoint dst = new ConnectPoint(DID2, P2); final DefaultLinkDescription linkDescription = new DefaultLinkDescription(src, dst, INDIRECT); LinkEvent event = linkStore.createOrUpdateL...
@SuppressWarnings("unchecked") public static <T> T invoke(Object obj, String methodName, Object... arguments) { try { Method method = ReflectUtil.getMethodByName(obj.getClass(), methodName); if (method == null) { throw new RuntimeException(methodName + "method not exi...
@Test public void invokeTest() { TestClass testClass = new TestClass(); Method method = ReflectUtil.getMethodByName(TestClass.class, "getPrivateField"); String invoke = ReflectUtil.invoke(testClass, method); Assert.assertEquals(invoke, "privateField"); }
@Override public boolean equals(@Nullable Object obj) { if (!(obj instanceof S3ResourceId)) { return false; } S3ResourceId o = (S3ResourceId) obj; return scheme.equals(o.scheme) && bucket.equals(o.bucket) && key.equals(o.key); }
@Test public void testEquals() { S3ResourceId a = S3ResourceId.fromComponents("s3", "bucket", "a/b/c"); S3ResourceId b = S3ResourceId.fromComponents("s3", "bucket", "a/b/c"); assertEquals(a, b); assertEquals(b, a); b = S3ResourceId.fromComponents("s3", a.getBucket(), "a/b/c/"); assertNotEqual...
public static String storeChangelogTopic(final String prefix, final String storeName, final String namedTopology) { if (namedTopology == null) { return prefix + "-" + storeName + STATE_CHANGELOG_TOPIC_SUFFIX; } else { return prefix + "-" + namedTopology + "-" + storeName + STATE_...
@Test public void shouldReturnDefaultChangelogTopicNameWithNamedTopology() { final String applicationId = "appId"; final String namedTopology = "namedTopology"; final String storeName = "store"; assertThat( ProcessorStateManager.storeChangelogTopic(applicationId, storeNa...
@Override protected String buildHandle(final List<URIRegisterDTO> uriList, final SelectorDO selectorDO) { List<TarsUpstream> addList = buildTarsUpstreamList(uriList); List<TarsUpstream> canAddList = new CopyOnWriteArrayList<>(); boolean isEventDeleted = uriList.size() == 1 && EventType.DELET...
@Test public void testBuildHandle() { shenyuClientRegisterTarsService = spy(shenyuClientRegisterTarsService); final String returnStr = "[{upstreamUrl:'localhost:8090',weight:1,warmup:10,status:true,timestamp:1637826588267}," + "{upstreamUrl:'localhost:8091',weight:2,warmup:10,st...
public static String addOrIncrementIndexInName(String name) { Matcher m = TRAILING_NUMBER_PATTERN.matcher(name); int index = 2; if (m.matches()) { try { int newIndex = Integer.parseInt(m.group(2)) + 1; if (newIndex > 2) { index = ne...
@Test public void test_addIndexToName() { assertEquals("a-2", addOrIncrementIndexInName("a")); assertEquals("a-3", addOrIncrementIndexInName("a-2")); assertEquals("a-26", addOrIncrementIndexInName("a-25")); assertEquals("a-25x-2", addOrIncrementIndexInName("a-25x")); assertEq...
public List<Service> importServiceDefinition(String repositoryUrl, Secret repositorySecret, boolean disableSSLValidation, boolean mainArtifact) throws MockRepositoryImportException { log.info("Importing service definitions from {}", repositoryUrl); File localFile = null; Map<String, List<Stri...
@Test void testImportServiceDefinitionMainGraphQLAndSecondaryPostman() { List<Service> services = null; try { File artifactFile = new File("target/test-classes/io/github/microcks/util/graphql/films.graphql"); services = service.importServiceDefinition(artifactFile, null, new ArtifactInf...
@Override public int getMaxIndexLength() { return 0; }
@Test void assertGetMaxIndexLength() { assertThat(metaData.getMaxIndexLength(), is(0)); }
private StringBuilder read(int n) throws IOException { // Input stream finished? boolean eof = false; // Read that many. final StringBuilder s = new StringBuilder(n); while (s.length() < n && !eof) { // Always get from the pushBack buffer. if (pushBack.len...
@Test public void testRead_0args() throws Exception { String data = ""; InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); XmlInputStream instance = new XmlInputStream(stream); int expResult = -1; int result = instance.read(); assert...
public XmlStreamInfo information() throws IOException { if (information.problem != null) { return information; } if (XMLStreamConstants.START_DOCUMENT != reader.getEventType()) { information.problem = new IllegalStateException("Expected START_DOCUMENT"); retu...
@Test public void nonExistingDocument() throws IOException { XmlStreamDetector detector = new XmlStreamDetector(getClass().getResourceAsStream("non-existing")); assertFalse(detector.information().isValid()); }
public static String toCommaDelimitedString(String one, String... others) { String another = arrayToDelimitedString(others, COMMA_SEPARATOR); return isEmpty(another) ? one : one + COMMA_SEPARATOR + another; }
@Test void testToCommaDelimitedString() { String value = toCommaDelimitedString(null); assertNull(value); value = toCommaDelimitedString(null, null); assertNull(value); value = toCommaDelimitedString(""); assertEquals("", value); value = toCommaDelimitedStr...
public static ParsedCommand parse( // CHECKSTYLE_RULES.ON: CyclomaticComplexity final String sql, final Map<String, String> variables) { validateSupportedStatementType(sql); final String substituted; try { substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),...
@Test public void shouldParseCreateStatement() { // When: List<CommandParser.ParsedCommand> commands = parse("CREATE STREAM FOO (A STRING) WITH (KAFKA_TOPIC='FOO', PARTITIONS=1, VALUE_FORMAT='DELIMITED');"); // Then: assertThat(commands.size(), is(1)); assertThat(commands.get(0).getStatement().is...
@Override public Object construct(String componentName) { ClusteringConfiguration clusteringConfiguration = configuration.clustering(); boolean shouldSegment = clusteringConfiguration.cacheMode().needsStateTransfer(); int level = configuration.locking().concurrencyLevel(); MemoryConfigurati...
@Test public void testEvictionRemoveNotSegmented() { dataContainerFactory.configuration = new ConfigurationBuilder().clustering() .memory().evictionStrategy(EvictionStrategy.REMOVE).size(1000).build(); assertEquals(DefaultDataContainer.class, this.dataContainerFactory.construct(COMPONENT_NAM...
public static HealthCheckRegistry getOrCreate(String name) { final HealthCheckRegistry existing = REGISTRIES.get(name); if (existing == null) { final HealthCheckRegistry created = new HealthCheckRegistry(); final HealthCheckRegistry raced = add(name, created); if (rac...
@Test public void savesCreatedRegistry() { final HealthCheckRegistry one = SharedHealthCheckRegistries.getOrCreate("db"); final HealthCheckRegistry two = SharedHealthCheckRegistries.getOrCreate("db"); assertThat(one).isSameAs(two); }
public PlainAccessResource buildPlainAccessResource(PlainAccessConfig plainAccessConfig) throws AclException { checkPlainAccessConfig(plainAccessConfig); return PlainAccessResource.build(plainAccessConfig, remoteAddressStrategyFactory. getRemoteAddressStrategy(plainAccessConfig.getWhiteRemot...
@Test public void buildPlainAccessResourceTest() { PlainAccessResource plainAccessResource = null; PlainAccessConfig plainAccess = new PlainAccessConfig(); plainAccess.setAccessKey("RocketMQ"); plainAccess.setSecretKey("12345678"); plainAccessResource = plainPermissionManage...
@Override public void close() { webSocketClient.close(); executor.shutdown(); }
@Test public void testCloseWebSocketOnClose() throws Exception { service.close(); verify(webSocketClient).close(); verify(executorService).shutdown(); }
@Override public TenantPackageDO getTenantPackage(Long id) { return tenantPackageMapper.selectById(id); }
@Test public void testGetTenantPackage() { // mock 数据 TenantPackageDO dbTenantPackage = randomPojo(TenantPackageDO.class); tenantPackageMapper.insert(dbTenantPackage);// @Sql: 先插入出一条存在的数据 // 调用 TenantPackageDO result = tenantPackageService.getTenantPackage(dbTenantPackage.ge...
void fetchPluginSettingsMetaData(GoPluginDescriptor pluginDescriptor) { String pluginId = pluginDescriptor.id(); List<ExtensionSettingsInfo> allMetadata = findSettingsAndViewOfAllExtensionsIn(pluginId); List<ExtensionSettingsInfo> validMetadata = allSettingsAndViewPairsWhichAreValid(allMetadata)...
@Test public void shouldNotFailWhenAPluginWithMultipleExtensionsHasMoreThanOneExtensionRespondingWithSettings_BUT_OneIsValidAndOtherThrowsException() { PluginSettingsConfiguration configuration = new PluginSettingsConfiguration(); configuration.add(new PluginSettingsProperty("k1").with(Property.REQU...
@Override public List<URI> services(String protocol, String serviceId, String tag) { if(StringUtils.isBlank(serviceId)) { logger.debug("The serviceId cannot be blank"); return new ArrayList<>(); } // transform to a list of URIs return discovery(protocol, serv...
@Test public void testServices() { List<URI> l = cluster.services("http", "com.networknt.apib-1.0.0", null); Assert.assertEquals(2, l.size()); }
@Override public AppResponse process(Flow flow, ActivateWithCodeRequest request) throws SharedServiceClientException { digidClient.remoteLog("1092", Map.of(lowerUnderscore(ACCOUNT_ID), appSession.getAccountId())); if (appAuthenticator.getCreatedAt().isBefore(ZonedDateTime.now().minusDays(Integer.p...
@Test void activationCodeExpiredResponse() throws SharedServiceClientException { //given mockedAppAuthenticator.setCreatedAt(ZonedDateTime.parse("2021-10-14T19:31:00.044077+01:00[Europe/Amsterdam]")); mockedAppAuthenticator.setGeldigheidstermijn("5"); //when AppResponse appRe...
public static void zipDirectory(File sourceDirectory, File zipFile) throws IOException { zipDirectory(sourceDirectory, zipFile, false); }
@Test public void testSubdirectoryWithContentsHasNoZipEntry() throws Exception { File zipDir = new File(tmpDir, "zip"); File subDirContent = new File(zipDir, "subdirContent"); assertTrue(subDirContent.mkdirs()); createFileWithContents(subDirContent, "myTextFile.txt", "Simple Text"); ZipFiles.zipD...
@Override public ReadwriteSplittingRule build(final ReadwriteSplittingRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType, final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceC...
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void assertBuild() { ReadwriteSplittingRuleConfiguration ruleConfig = new ReadwriteSplittingRuleConfiguration(Collections.singleton( new ReadwriteSplittingDataSourceGroupRuleConfiguration("name", "writeDataSourceName", Collections.single...
static int inferParallelism( ReadableConfig readableConfig, long limitCount, Supplier<Integer> splitCountProvider) { int parallelism = readableConfig.get(ExecutionConfigOptions.TABLE_EXEC_RESOURCE_DEFAULT_PARALLELISM); if (readableConfig.get(FlinkConfigOptions.TABLE_EXEC_ICEBERG_INFER_SOURCE_PARAL...
@Test public void testInferedParallelism() throws IOException { Configuration configuration = new Configuration(); // Empty table, infer parallelism should be at least 1 int parallelism = SourceUtil.inferParallelism(configuration, -1L, () -> 0); assertThat(parallelism).isEqualTo(1); // 2 splits (...
public void initialize(StorageProvider storageProvider, BackgroundJobServer backgroundJobServer) { storageProviderMetricsBinder = new StorageProviderMetricsBinder(storageProvider, meterRegistry); if (backgroundJobServer != null) { backgroundJobServerMetricsBinder = new BackgroundJobServerMet...
@Test void testWithStorageProviderOnly() { // GIVEN JobRunrMicroMeterIntegration jobRunrMicroMeterIntegration = new JobRunrMicroMeterIntegration(meterRegistry); when(storageProvider.getJobStats()).thenReturn(JobStats.empty()); // WHEN jobRunrMicroMeterIntegration.initialize(...
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void retryOnResultUsingMaybe() throws InterruptedException { RetryConfig config = RetryConfig.<String>custom() .retryOnResult("retry"::equals) .waitDuration(Duration.ofMillis(50)) .maxAttempts(3).build(); Retry retry = Retry.of("testName", config); ...
public static DataMap getAnnotationsMap(Annotation[] as) { return annotationsToData(as, true); }
@Test(description = "RestSpecAnnotation annotation with unsupported members with overrides") public void unsupportedScalarMembersWithOverriddenValues() { @UnsupportedScalarMembers( charMember = UnsupportedScalarMembers.DEFAULT_CHAR_MEMBER + 1, shortMember = UnsupportedScalarMembers.DEFAULT_SHORT...
@Override public final String path() { return delegate.getRequestURI(); }
@Test void path_getRequestURI() { when(request.getRequestURI()).thenReturn("/bar"); assertThat(wrapper.path()) .isEqualTo("/bar"); }
protected void addToRouteTotals(RouteStatistic routeStatistic) { routeTotalsStatistic.incrementTotalEips(routeStatistic.getTotalEips()); routeTotalsStatistic.incrementTotalEipsTested(routeStatistic.getTotalEipsTested()); routeTotalsStatistic.incrementTotalProcessingTime(routeStatistic.getTotalP...
@Test public void testAddToRouteTotals() { }
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) { List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext() ? createShardingConditionsWithInsertValues(sqlStatementContext, params) ...
@Test void assertCreateShardingConditionsInsertStatement() { when(insertStatementContext.getGeneratedKeyContext()).thenReturn(Optional.empty()); List<ShardingCondition> shardingConditions = shardingConditionEngine.createShardingConditions(insertStatementContext, Collections.emptyList()); ass...
public void receiveMessage(ProxyContext ctx, ReceiveMessageRequest request, StreamObserver<ReceiveMessageResponse> responseObserver) { ReceiveMessageResponseStreamWriter writer = createWriter(ctx, responseObserver); try { Settings settings = this.grpcClientSettingsManager.getClientS...
@Test public void testReceiveMessageIllegalInvisibleTimeTooSmall() { StreamObserver<ReceiveMessageResponse> receiveStreamObserver = mock(ServerCallStreamObserver.class); ArgumentCaptor<ReceiveMessageResponse> responseArgumentCaptor = ArgumentCaptor.forClass(ReceiveMessageResponse.class); doN...
public ConfigCheckResult checkConfig() { Optional<Long> appId = getAppId(); if (appId.isEmpty()) { return failedApplicationStatus(INVALID_APP_ID_STATUS); } GithubAppConfiguration githubAppConfiguration = new GithubAppConfiguration(appId.get(), gitHubSettings.privateKey(), gitHubSettings.apiURLOrDe...
@Test public void checkConfig_whenNoInstallationsAreReturned_shouldReturnFailedAppAutoProvisioningCheck() { mockGithubConfiguration(); ArgumentCaptor<GithubAppConfiguration> appConfigurationCaptor = ArgumentCaptor.forClass(GithubAppConfiguration.class); mockGithubAppWithValidConfig(appConfigurationCaptor)...
@Override public boolean requiresDestruction(Object bean) { return bean instanceof Startable; }
@Test public void startable_and_autoCloseable_should_require_destruction(){ assertThat(underTest.requiresDestruction(mock(Startable.class))).isTrue(); assertThat(underTest.requiresDestruction(mock(org.sonar.api.Startable.class))).isTrue(); assertThat(underTest.requiresDestruction(mock(Object.class))).isFa...
@Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(task); }
@Test public void submit_runnable_delegates_to_executorService() { underTest.submit(SOME_RUNNABLE); inOrder.verify(executorService).submit(SOME_RUNNABLE); inOrder.verifyNoMoreInteractions(); }
public TrackingResult track(Component component, Input<DefaultIssue> rawInput, @Nullable Input<DefaultIssue> targetInput) { if (analysisMetadataHolder.isPullRequest()) { return standardResult(pullRequestTracker.track(component, rawInput, targetInput)); } if (isFirstAnalysisSecondaryBranch()) { ...
@Test public void delegate_merge_tracker() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); when(branch.isMain()).thenReturn(false); when(analysisMetadataHolder.getBranch()).thenReturn(branch); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(tru...
@Override public Object getSmallintValue(final ResultSet resultSet, final int columnIndex) throws SQLException { return resultSet.getShort(columnIndex); }
@Test void assertGetSmallintValue() throws SQLException { when(resultSet.getShort(1)).thenReturn((short) 0); assertThat(dialectResultSetMapper.getSmallintValue(resultSet, 1), is((short) 0)); }
@Override public boolean getAutoCommit() { return false; }
@Test void assertGetAutoCommit() { assertFalse(connection.getAutoCommit()); }
@Override protected Mono<Boolean> doMatcher(final ServerWebExchange exchange, final WebFilterChain chain) { return Mono.just(paths.stream().anyMatch(path -> exchange.getRequest().getURI().getRawPath().startsWith(path))); }
@Test public void testDoMatcher() { Mono<Boolean> health = healthFilter.doMatcher(MockServerWebExchange .from(MockServerHttpRequest.post("http://localhost:8080/actuator/health")), webFilterChain); StepVerifier.create(health).expectNext(Boolean.TRUE).verifyComplete(); Mon...
public Materialization create( final StreamsMaterialization delegate, final MaterializationInfo info, final QueryId queryId, final QueryContext.Stacker contextStacker ) { final TransformVisitor transformVisitor = new TransformVisitor(queryId, contextStacker); final List<Transform> tran...
@Test public void shouldUseCorrectLoggerForPredicate() { // When: factory.create(materialization, info, queryId, new Stacker().push("filter")); // Then: verify(predicateInfo).getPredicate(loggerCaptor.capture()); assertThat( loggerCaptor.getValue().apply(new Stacker().getQueryContext()), ...
@VisibleForTesting static boolean isBrokenPipe(IOException original) { Throwable exception = original; while (exception != null) { String message = exception.getMessage(); if (message != null && message.toLowerCase(Locale.US).contains("broken pipe")) { return true; } exception...
@Test public void testIsBrokenPipe_notBrokenPipe() { Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new IOException())); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new SocketException())); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new SSLException("mock"))); }
public Optional<YamlRuleConfiguration> swapToYamlRuleConfiguration(final Collection<RepositoryTuple> repositoryTuples, final Class<? extends YamlRuleConfiguration> toBeSwappedType) { RepositoryTupleEntity tupleEntity = toBeSwappedType.getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) ...
@Test void assertSwapToYamlRuleConfigurationWithNodeYamlRuleConfiguration() { Optional<YamlRuleConfiguration> actual = new RepositoryTupleSwapperEngine().swapToYamlRuleConfiguration(Arrays.asList( new RepositoryTuple("/metadata/foo_db/rules/node/map_value/k/versions/0", "v"), ...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { String roadClassTag = readerWay.getTag("highway"); if (roadClassTag == null) return; RoadClass roadClass = RoadClass.find(roadClassTag); if (roadClas...
@Test public void testNoNPE() { ReaderWay readerWay = new ReaderWay(1); ArrayEdgeIntAccess intAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; parser.handleWayTags(edgeId, intAccess, readerWay, relFlags); assertEquals(RoadClass.OTHER, rcEnc.getEnum(false, edgeId, intAccess...
public static StringUtils.Pair parseVariableAndPath(String text) { Matcher matcher = VAR_AND_PATH_PATTERN.matcher(text); matcher.find(); String name = text.substring(0, matcher.end()); String path; if (matcher.end() == text.length()) { path = ""; } else { ...
@Test void testParsingVariableAndJsonPath() { assertEquals(StringUtils.pair("foo", "$"), ScenarioEngine.parseVariableAndPath("foo")); assertEquals(StringUtils.pair("foo", "$.bar"), ScenarioEngine.parseVariableAndPath("foo.bar")); assertEquals(StringUtils.pair("foo", "$['bar']"), ScenarioEngi...
@Override public long approximateNumEntries() { final List<ReadOnlyKeyValueStore<K, V>> stores = storeProvider.stores(storeName, storeType); long total = 0; for (final ReadOnlyKeyValueStore<K, V> store : stores) { total += store.approximateNumEntries(); if (total < 0)...
@Test public void shouldReturnLongMaxValueOnOverflow() { stubProviderTwo.addStore(storeName, new NoOpReadOnlyStore<Object, Object>() { @Override public long approximateNumEntries() { return Long.MAX_VALUE; } }); stubOneUnderlying.put("over...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final Map<Path, List<String>> containers = new HashMap<>(); for(Path file : files.keySet()) { if(containerService.isContainer(file)) { ...
@Test public void testDeleteMultiple() throws Exception { final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); for(Location.Name region : new SwiftLocationFeature(session).getLocations()) { container.attributes().setRegion(region.getIde...
public Node parse() throws ScanException { return E(); }
@Test public void testBasic() throws Exception { Parser<Object> p = new Parser<>("hello"); Node t = p.parse(); Assertions.assertEquals(Node.LITERAL, t.getType()); Assertions.assertEquals("hello", t.getValue()); }
public void setFatigue(Fatigue fatigue) { this.giant.setFatigue(fatigue); }
@Test void testSetFatigue() { final var model = mock(GiantModel.class); final var view = mock(GiantView.class); final var controller = new GiantController(model, view); verifyNoMoreInteractions(model, view); for (final var fatigue : Fatigue.values()) { controller.setFatigue(fatigue); ...
String getSubstitutionVariable(String key) { return substitutionVariables.get(key); }
@Test public void shouldNotBeVerboseByDefault() { assertThat(new LoggingConfiguration(null) .getSubstitutionVariable(LoggingConfiguration.PROPERTY_ROOT_LOGGER_LEVEL)).isEqualTo(LoggingConfiguration.LEVEL_ROOT_DEFAULT); }
@Override public void process() { try { if (containers.length > 1) { throw new RuntimeException("This processor can only handle single containers"); } ContainerUnloader container = containers[0]; // Get config Configuration config ...
@Test public void testMeta() { ImportContainerImpl importContainer = new ImportContainerImpl(); importContainer.setMetadata(MetadataDraft.builder().description("foo").title("bar").build()); Workspace workspace = new WorkspaceImpl(null, 1); DefaultProcessor defaultProcessor = new Def...
public void close() { close(Long.MAX_VALUE, false); }
@Test public void shouldThrowOnNegativeTimeoutForCloseWithCloseOptionLeaveGroupTrue() throws Exception { prepareStreams(); prepareStreamThread(streamThreadOne, 1); prepareStreamThread(streamThreadTwo, 2); prepareTerminableThread(streamThreadOne); final MockClientSupplier moc...
public static String parsePath(String uri, Map<String, String> patterns) { if (uri == null) { return null; } else if (StringUtils.isBlank(uri)) { return String.valueOf(SLASH); } CharacterIterator ci = new StringCharacterIterator(uri); StringBuilder pathBuf...
@Test(description = "parse regex with slash inside it from issue 1153") public void parseRegexWithSlashInside() { final Map<String, String> regexMap = new HashMap<String, String>(); final String path = PathUtils.parsePath("/{itemId: [0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]{2}/[0-9]{2}/[0-9]{2}/[0-9]{3}/[A-Z...
@Operation(summary = "queryAuthorizedNamespace", description = "QUERY_AUTHORIZED_NAMESPACE_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", schema = @Schema(implementation = int.class, example = "100")) }) @GetMapping(value = "/authed-namespace") @ResponseStatus(Htt...
@Test public void testQueryAuthorizedNamespace() throws Exception { MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userId", "1"); MvcResult mvcResult = mockMvc.perform(get("/k8s-namespace/authed-namespace") .header(SESSION_ID, sessionId...
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test(expected=AclException.class) public void testMergeAclEntriesDuplicateEntries() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, NONE)) .build(); ...
public static Map<String, String> mergeHeaders(Map<String, String> headers1, Map<String, String> headers2) { TreeMap<String, String> combinedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); if (headers2 != null) { combinedHeaders.putAll(headers2); } if (headers1 != null) { f...
@Test public void testMergeHeader() { Map<String, String> headers1 = new HashMap<>(); Map<String, String> headers2 = new HashMap<>(); headers1.put("X-header1", "header1Value"); headers1.put("X-commonheader", "commonHeader1Value"); headers2.put("X-header2", "header2Value"); headers2.put("X-Co...
@Override public String named() { return PluginEnum.RPC_PARAM_TRANSFORM.getName(); }
@Test public void testNamed() { String result = rpcParamTransformPlugin.named(); Assertions.assertEquals(PluginEnum.RPC_PARAM_TRANSFORM.getName(), result); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final MultivaluedMap<String, String> headers = requestContext.getHeaders(); final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY); if (authorization == null || authorization.isEmpty()...
@Test void testMissingPassword() throws IOException { final BasicAuthFilter filter = new BasicAuthFilter("admin", DigestUtils.sha256Hex("admin"), "junit-test"); final ContainerRequest request = mockRequest("admin", ""); filter.filter(request); final ArgumentCaptor<Response> captor = ...
@Override public final ChannelFuture close() { return close(newPromise()); }
@Test @Timeout(value = 2000, unit = TimeUnit.MILLISECONDS) public void testFireChannelInactiveAndUnregisteredOnClose() throws InterruptedException { testFireChannelInactiveAndUnregistered(new Action() { @Override public ChannelFuture doRun(Channel channel) { retur...
public static FhirIOPatientEverything getPatientEverything() { return new FhirIOPatientEverything(); }
@Test public void test_FhirIO_failedPatientEverything() { PatientEverythingParameter input = PatientEverythingParameter.builder().setResourceName("bad-resource-name").build(); FhirIOPatientEverything.Result everythingResult = pipeline.apply(Create.of(input)).apply(FhirIO.getPatientEverything()...
public static GeneratorResult run(String resolverPath, String defaultPackage, final boolean generateImported, final boolean generateDataTemplates, RestliVersion version, ...
@Test(dataProvider = "deprecatedByVersionDataProvider") public void testDeprecatedByVersion(String idlName, String buildersName, String substituteClassName) throws Exception { final String pegasusDir = moduleDir + FS + RESOURCES_DIR + FS + "pegasus"; final String outPath = outdir.getPath(); RestRequestB...
public void triggerPartitionReplicaSync(int partitionId, Collection<ServiceNamespace> namespaces, int replicaIndex) { assert replicaIndex >= 0 && replicaIndex < InternalPartition.MAX_REPLICA_COUNT : "Invalid replica index! partitionId=" + partitionId + ", replicaIndex=" + replicaIndex; ...
@Test(expected = AssertionError.class) public void testTriggerPartitionReplicaSync_whenReplicaIndexTooLarge_thenThrowException() { Set<ServiceNamespace> namespaces = Collections.singleton(INSTANCE); manager.triggerPartitionReplicaSync(PARTITION_ID, namespaces, InternalPartition.MAX_REPLICA_COUNT + 1...
public static Map<?, ?> convertToMap(Schema schema, Object value) { return convertToMapInternal(MAP_SELECTOR_SCHEMA, value); }
@Test public void shouldFailToParseStringOfMalformedMap() { assertThrows(DataException.class, () -> Values.convertToMap(Schema.STRING_SCHEMA, " { \"foo\" : 1234567890 , \"a\", \"bar\" : 0, \"baz\" : -987654321 } ")); }
public static Map<String, String> getTrimmedStringCollectionSplitByEquals( String str) { String[] trimmedList = getTrimmedStrings(str); Map<String, String> pairs = new HashMap<>(); for (String s : trimmedList) { if (s.isEmpty()) { continue; } String[] splitByKeyVal = getTrimm...
@Test public void testStringCollectionSplitByEqualsSuccess() { Map<String, String> splitMap = StringUtils.getTrimmedStringCollectionSplitByEquals(""); Assertions .assertThat(splitMap) .describedAs("Map of key value pairs split by equals(=) and comma(,)") .hasSize(0); split...
public void validateWriter(final Long memberId) { if (!this.writerId.equals(memberId)) { throw new WriterNotEqualsException(); } }
@Test void 작성자가_아니면_예외를_발생한다() { // given Board board = 게시글_생성_사진없음(); // when & then assertThatThrownBy(() -> board.validateWriter(board.getWriterId() + 1)) .isInstanceOf(WriterNotEqualsException.class); }
@Override public void setUpParameters(final List<Object> params) { AtomicInteger parametersOffset = new AtomicInteger(0); insertValueContexts = getInsertValueContexts(params, parametersOffset, valueExpressions); insertSelectContext = getInsertSelectContext(metaData, params, parametersOffset,...
@Test void assertInsertStatementContextWithoutColumnNames() { InsertStatement insertStatement = new MySQLInsertStatement(); insertStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("tbl")))); setUpInsertValues(insertStatement); InsertStatementCon...
public static void syncToFile(Collection<Member> members) { try { StringBuilder builder = new StringBuilder(); builder.append('#').append(LocalDateTime.now()).append(StringUtils.LF); for (String member : simpleMembers(members)) { builder.append(member).append(...
@Test void testSyncToFile() throws IOException { File file = new File(EnvUtil.getClusterConfFilePath()); file.getParentFile().mkdirs(); assertTrue(file.createNewFile()); MemberUtil.syncToFile(Collections.singleton(originalMember)); try (BufferedReader reader = new BufferedRea...