focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static final StartTime absolute(Instant absoluteStart) { return new StartTime(StartTimeOption.ABSOLUTE, null, absoluteStart); }
@Test public void testStopAbsolute() { StopTime st = StopTime.absolute(OffsetDateTime .of(2017, 3, 20, 11, 43, 11, 0, ZoneOffset.ofHours(-7)) .toInstant()); assertEquals(StopTimeOption.ABSOLUTE, st.option()); assertNull(st.relativeTime()); assertEquals...
public static List<KiePMMLFieldOperatorValue> getXORConstraintEntryFromSimplePredicates(final List<Predicate> predicates, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) { return predicates.stream() .filter(predicate -> predicate instanceof SimplePredicate) .map...
@Test void getXORConstraintEntryFromSimplePredicates() { List<Predicate> predicates = new ArrayList<>(simplePredicates); List<KiePMMLFieldOperatorValue> retrieved = KiePMMLASTFactoryUtils .getXORConstraintEntryFromSimplePredicates(predicates, fieldTypeMap); assertThat(retriev...
public CompatibilityInfoMap checkRestSpecVsSnapshot(String prevRestSpecPath, String currSnapshotPath, CompatibilityLevel compatLevel) { return checkCompatibility(prevRestSpecPath, currSnapshotPath, compatLevel, true); }
@Test public void testCompatibleRestSpecVsSnapshot() { final RestLiSnapshotCompatibilityChecker checker = new RestLiSnapshotCompatibilityChecker(); final CompatibilityInfoMap infoMap = checker.checkRestSpecVsSnapshot(RESOURCES_DIR + FS + "idls" + FS + "twitter-statuses.restspec.json", ...
@Override public final String toString() { return ", " + columnName + " = " + getRightValue(); }
@Test void assertParameterMarkerGeneratedKeyAssignmentTokenToString() { generatedKeyAssignmentToken = new ParameterMarkerGeneratedKeyAssignmentToken(0, "id"); String resultParameterMarkerGeneratedKeyAssignmentTokenToString = generatedKeyAssignmentToken.toString(); assertThat(resultParameterM...
@Override public boolean accept(Object object) { return factToCheck.stream() .allMatch(factCheckerHandle -> factCheckerHandle.getClazz().isAssignableFrom(object.getClass()) && factCheckerHandle.getCheckFuction().appl...
@Test public void acceptWithFailure() { ConditionFilter conditionFilterFail = createConditionFilter(object -> ValueWrapper.errorWithValidValue(null, null)); assertThat(conditionFilterFail.accept("String")).isFalse(); }
public static boolean isMatch(String str, String exp) { int strIndex = 0; int expIndex = 0; int starIndex = -1; //记录上一个 '*' 的位置 while (strIndex < str.length()) { final char pkgChar = str.charAt(strIndex); final char expChar = expIndex < exp.length() ? exp.charAt(e...
@Test public void testIsMatch() { Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "cn.myperf4j*abc")); Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "*.myperf4j*abc")); Assert.assertTrue(isMatch("cn.myperf4j.config.abc", "*.myperf4j*a*c")); Assert.assertFalse(isMatch("cn.m...
@VisibleForTesting static List<Tuple2<ConfigGroup, String>> generateTablesForClass( Class<?> optionsClass, Collection<OptionWithMetaInfo> optionWithMetaInfos) { ConfigGroups configGroups = optionsClass.getAnnotation(ConfigGroups.class); List<OptionWithMetaInfo> allOptions = selectOptions...
@Test void testOverrideDefault() { final String expectedTable = "<table class=\"configuration table table-bordered\">\n" + " <thead>\n" + " <tr>\n" + " <th class=\"text-left\" style=\"width: 20%\">Ke...
protected void checkRunningTxnExceedLimit(TransactionState.LoadJobSourceType sourceType) throws RunningTxnExceedException { switch (sourceType) { case ROUTINE_LOAD_TASK: // no need to check limit for routine load task: // 1. the number of running routine load tasks is...
@Test public void testCheckRunningTxnExceedLimit() { int maxRunningTxnNumPerDb = Config.max_running_txn_num_per_db; DatabaseTransactionMgr mgr = new DatabaseTransactionMgr(0, masterGlobalStateMgr); Deencapsulation.setField(mgr, "runningTxnNums", maxRunningTxnNumPerDb); ExceptionCheck...
public int validate( final ServiceContext serviceContext, final List<ParsedStatement> statements, final SessionProperties sessionProperties, final String sql ) { requireSandbox(serviceContext); final KsqlExecutionContext ctx = requireSandbox(snapshotSupplier.apply(serviceContext)); ...
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") @Test public void shouldCallPrepareStatementWithEmptySessionVariablesIfSubstitutionDisabled() { // Given givenRequestValidator(ImmutableMap.of(CreateStream.class, statementValidator)); when(ksqlConfig.getBoolean(KsqlConfig.KSQL_VARIABLE_SUBST...
public static boolean parse(final String str, ResTable_config out) { return parse(str, out, true); }
@Test public void parse_density_ldpi() { ResTable_config config = new ResTable_config(); ConfigDescription.parse("ldpi", config); assertThat(config.density).isEqualTo(DENSITY_LOW); }
@Override public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) { return getDescriptionInHtml(rule) .map(this::generateSections) .orElse(emptySet()); }
@Test public void parse_to_risk_description_fields_when_desc_contains_no_section() { String descriptionWithoutTitles = "description without titles"; when(rule.htmlDescription()).thenReturn(descriptionWithoutTitles); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<Strin...
@Override public SlotAssignmentResult ensure(long key1, long key2) { assert key1 != unassignedSentinel : "ensure() called with key1 == nullKey1 (" + unassignedSentinel + ')'; return super.ensure0(key1, key2); }
@Test public void testPut() { final long key1 = randomKey(); final long key2 = randomKey(); SlotAssignmentResult slot = hsa.ensure(key1, key2); assertTrue(slot.isNew()); final long valueAddress = slot.address(); assertNotEquals(NULL_ADDRESS, valueAddress); sl...
@Override public NacosUser authenticate(String username, String rawPassword) throws AccessException { if (StringUtils.isBlank(username) || StringUtils.isBlank(rawPassword)) { throw new AccessException("user not found!"); } NacosUserDetails nacosUserDetails = (NacosUserDetails) us...
@Test void testAuthenticate6() throws AccessException { NacosUser nacosUser = new NacosUser(); when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser); NacosUser authenticate = abstractAuthenticationManager.authenticate("token"); assertEquals(nacosUser, ...
public static void copyStream(InputStream input, Writer output) throws IOException { try (InputStreamReader inputStreamReader = new InputStreamReader(input)) { char[] buffer = new char[1024]; // Adjust if you want int bytesRead; while ((bytesRead = inputStreamReader.read(buff...
@Test void testCopyStreamOutputStream() throws IOException { InputStream inputStream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copyStream(inputStream, outputStream); assertThat(outpu...
@Override public void exists(final String path, final boolean watch, final AsyncCallback.StatCallback cb, final Object ctx) { if (!SymlinkUtil.containsSymlink(path)) { _zk.exists(path, watch, cb, ctx); } else { SymlinkStatCallback compositeCallback = new SymlinkStatCallback(path, _de...
@Test public void testSymlinkWithExistWatch3() throws InterruptedException, ExecutionException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.StatCallback existCallback = new AsyncCallback.StatCallback() { @Overrid...
public PutMessageResult putMessageReturnResult(MessageExtBrokerInner messageInner) { LOGGER.debug("[BUG-TO-FIX] Thread:{} msgID:{}", Thread.currentThread().getName(), messageInner.getMsgId()); PutMessageResult result = store.putMessage(messageInner); if (result != null && result.getPutMessageSta...
@Test public void testPutMessageReturnResult() { when(messageStore.putMessage(any(MessageExtBrokerInner.class))) .thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK))); PutMessageResult result = transactionBridge.putMessageRetu...
public void push(int id, float value) { checkIdInRange(id); if (size == max) throw new IllegalStateException("Cannot push anymore, the heap is already full. size: " + size); if (contains(id)) throw new IllegalStateException("Element with id: " + id + " was pushed already,...
@Test public void outOfRange() { assertThrows(IllegalArgumentException.class, () -> new MinHeapWithUpdate(4).push(4, 1.2f)); assertThrows(IllegalArgumentException.class, () -> new MinHeapWithUpdate(4).push(-1, 1.2f)); }
@Override public Thread newThread(Runnable target) { return delegate.newThread(target); }
@Test void requireThatThreadsCreatedAreJDiscContainerThreads() { assertEquals(ContainerThread.class, new ContainerThreadFactory(Mockito.mock(MetricConsumerProvider.class)) .newThread(Mockito.mock(Runnable.class)) .getClass()); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthSendRawTransaction() throws Exception { web3j.ethSendRawTransaction( "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f" + "072445675058bb8eb970870f072445675") .send(); verifyResult( "...
@Override public Optional<IndexSetConfig> get(String id) { return get(new ObjectId(id)); }
@Test @MongoDBFixtures("MongoIndexSetServiceTest.json") public void getWithStringId() throws Exception { final Optional<IndexSetConfig> indexSetConfig = indexSetService.get("57f3d721a43c2d59cb750001"); assertThat(indexSetConfig) .isPresent() .contains( ...
@Override public String getCommandWithArguments() { List<String> argList = new ArrayList<>(); argList.add(super.getCommandWithArguments()); argList.add(containerName); return StringUtils.join(argList, " "); }
@Test public void getCommandWithArguments() { dockerInspectCommand.withGettingContainerStatus(); assertEquals("inspect --format='{{.State.Status}}' container_name", dockerInspectCommand.getCommandWithArguments()); }
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test(description = "it should clone everything from JSON without models") public void cloneWithoutModels() throws IOException { final String json = ResourceUtils.loadClassResource(getClass(), RESOURCE_PATH_WITHOUT_MODELS); final OpenAPI openAPI = Json.mapper().readValue(json, OpenAPI.class); ...
public static Sensor enforcedProcessingSensor(final String threadId, final String taskId, final StreamsMetricsImpl streamsMetrics, final Sensor... parentSensors) { ...
@Test public void shouldGetEnforcedProcessingSensor() { final String operation = "enforced-processing"; final String totalDescription = "The total number of occurrences of enforced-processing operations"; final String rateDescription = "The average number of occurrences of enforced-processin...
public static ModelType of(String name, String version) { validate(name, version); return Builder.create().name(name).version(version).build(); }
@Test public void deserialize() { final ModelType modelType = ModelType.of("foobar", "1"); final JsonNode jsonNode = objectMapper.convertValue(modelType, JsonNode.class); assertThat(jsonNode.isObject()).isTrue(); assertThat(jsonNode.path("name").asText()).isEqualTo("foobar"); ...
public void close() { synchronized (LOCK) { for (KafkaMbean mbean : this.mbeans.values()) unregister(mbean); } }
@Test public void testDeprecatedJmxPrefixWithDefaultMetrics() throws Exception { @SuppressWarnings("deprecation") JmxReporter reporter = new JmxReporter("my-prefix"); // for backwards compatibility, ensure prefix does not get overridden by the default empty namespace in metricscontext ...
public abstract int getLocalPort();
@Test public void test_getLocalPort_whenNotYetBound() { Reactor reactor = newReactor(); try (AsyncServerSocket socket = newAsyncServerSocket(reactor)) { int localPort = socket.getLocalPort(); assertEquals(-1, localPort); } }
@Override public boolean containsInt(K name, int value) { return false; }
@Test public void testContainsInt() { assertFalse(HEADERS.containsInt("name1", 1)); }
public static String toStepName(ExecutableStage executableStage) { /* * Look for the first/input ParDo/DoFn in this executable stage by * matching ParDo/DoFn's input PCollection with executable stage's * input PCollection */ Set<PipelineNode.PTransformNode> inputs = executableStage.g...
@Test public void testExecutableStageWithPDone() { pipeline .apply("MyCreateOf", Create.of("1")) .apply( "PDoneTransform", new PTransform<PCollection<String>, PDone>() { @Override public PDone expand(PCollection<String> input) { r...
public boolean isIncompatibleWith(short version) { return min() > version || max() < version; }
@Test public void testIsIncompatibleWith() { assertFalse(new SupportedVersionRange((short) 1, (short) 1).isIncompatibleWith((short) 1)); assertFalse(new SupportedVersionRange((short) 1, (short) 4).isIncompatibleWith((short) 2)); assertFalse(new SupportedVersionRange((short) 1, (short) 4).isI...
public static <T> T populate(final Properties properties, final Class<T> clazz) { T obj = null; try { obj = clazz.getDeclaredConstructor().newInstance(); return populate(properties, obj); } catch (Throwable e) { log.warn("Error occurs !", e); } ...
@Test public void testPopulate_ExistObj() { CustomizedConfig config = new CustomizedConfig(); config.setConsumerId("NewConsumerId"); Assert.assertEquals(config.getConsumerId(), "NewConsumerId"); config = BeanUtils.populate(properties, config); //RemotingConfig config = Bea...
public static Predicate<TopicMessageDTO> celScriptFilter(String script) { CelValidationResult celValidationResult = CEL_COMPILER.compile(script); if (celValidationResult.hasError()) { throw new CelException(script, celValidationResult.getErrorString()); } try { CelAbstractSyntaxTree ast = c...
@Test void testBase64DecodingWorks() { var uuid = UUID.randomUUID().toString(); var msg = "test." + Base64.getEncoder().encodeToString(uuid.getBytes()); var f = celScriptFilter("string(base64.decode(record.value.split('.')[1])).contains('" + uuid + "')"); assertTrue(f.test(msg().content(msg))); }
public JobMetaDataParameterObject processJobMultipart(JobMultiPartParameterObject parameterObject) throws IOException, NoSuchAlgorithmException { // Change the timestamp in the beginning to avoid expiration changeLastUpdatedTime(); validateReceivedParameters(parameterObject); ...
@Test public void testInvalidOrder() { JobMultiPartParameterObject jobMultiPartParameterObject = new JobMultiPartParameterObject(); jobMultiPartParameterObject.setSessionId(null); jobMultiPartParameterObject.setCurrentPartNumber(2); jobMultiPartParameterObject.setTotalPartNumber(1); ...
private void validateContentLength(final int contentLength, final boolean multiRecipientMessage, final String userAgent) { final boolean oversize = contentLength > MAX_MESSAGE_SIZE; DistributionSummary.builder(CONTENT_SIZE_DISTRIBUTION_NAME) .tags(Tags.of(UserAgentTagUtil.getPlatformTag(userAgent), ...
@Test void testValidateContentLength() throws Exception { final int contentLength = Math.toIntExact(MessageController.MAX_MESSAGE_SIZE + 1); final byte[] contentBytes = new byte[contentLength]; Arrays.fill(contentBytes, (byte) 1); try (final Response response = resources.getJerseyTest() ...
@Override @Deprecated public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransf...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullValueTransformerWithKeySupplierOnFlatTransformValuesWithNamedAndStores() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatTransformValues( (...
public static NodeBadge number(int n) { // TODO: consider constraints, e.g. 1 <= n <= 999 return new NodeBadge(Status.INFO, false, Integer.toString(n), null); }
@Test public void numberOnly() { badge = NodeBadge.number(NUM); checkFields(badge, Status.INFO, false, NUM_STR, null); }
@Override public TopicAssignment place( PlacementSpec placement, ClusterDescriber cluster ) throws InvalidReplicationFactorException { RackList rackList = new RackList(random, cluster.usableBrokers()); throwInvalidReplicationFactorIfNonPositive(placement.numReplicas()); t...
@Test public void testPlacementOnFencedReplicaOnSingleRack() { MockRandom random = new MockRandom(); RackList rackList = new RackList(random, Arrays.asList( new UsableBroker(3, Optional.empty(), false), new UsableBroker(1, Optional.empty(), true), new UsableBroker...
public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException { if (pattern == null || host == null) { throw new IllegalArgumentException( "Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host); } pat...
@Test void testMatchIpRangeMatchWhenIpv6Exception() { IllegalArgumentException thrown = assertThrows( IllegalArgumentException.class, () -> NetUtils.matchIpRange("234e:0:4567::3d:*", "234e:0:4567::3d:ff", 90)); assertTrue(thrown.getMessage().contains("If you config ip...
@Override public Connection createConnection(String host, int port) throws IOException { try { Socket socket; SocketFactory socketFactory; socketFactory = config.isUsingSSL() && config.getHttpProxyHost() == null ? SSLSocketFactory ...
@Test @Disabled("Must be manually tested") public void createConnection() throws IOException { SmppConfiguration configuration = new SmppConfiguration(); SmppConnectionFactory factory = SmppConnectionFactory.getInstance(configuration); Connection connection = factory.createConnection("lo...
@Override public Map<K, V> getCachedMap() { return localCacheView.getCachedMap(); }
@Test public void testPutGetCache() { RLocalCachedMap<String, Integer> map = redisson.getLocalCachedMap(LocalCachedMapOptions.name("test")); Map<String, Integer> cache = map.getCachedMap(); map.put("12", 1); map.put("14", 2); map.put("15", 3); assertThat(cache).cont...
@Override public Path path() { return path(true); }
@Test void shouldReturnTheSameWorkingDirPath() { LocalWorkingDir workingDirectory = new LocalWorkingDir(Path.of("/tmp"), IdUtils.create()); assertThat(workingDirectory.path(), is(workingDirectory.path())); }
public Optional<String> getNameByActiveVersion(final String path) { Matcher matcher = activeVersionPathPattern.matcher(path); return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); }
@Test void assertGetNameByActiveVersionWhenNotFound() { Optional<String> actual = converter.getNameByActiveVersion("/invalid"); assertFalse(actual.isPresent()); }
public static CreateSourceAsProperties from(final Map<String, Literal> literals) { try { return new CreateSourceAsProperties(literals, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" ); throw new ...
@Test public void shouldFailIfInvalidConfig() { // When: final Exception e = assertThrows( KsqlException.class, () -> from( of("foo", new StringLiteral("bar")) ) ); // Then: assertThat(e.getMessage(), containsString("Invalid config variable(s) in the WITH claus...
@Override public boolean isCloseOnCircuitBreakerEnabled() { return clientConfig.getPropertyAsBoolean(CLOSE_ON_CIRCUIT_BREAKER, true); }
@Test void testIsCloseOnCircuitBreakerEnabled() { assertTrue(connectionPoolConfig.isCloseOnCircuitBreakerEnabled()); }
@Override public long usedHeapMemory() { return heap.usedMemory(); }
@Test void chunkMustDeallocateOrReuseWthBufferRelease() throws Exception { AdaptiveByteBufAllocator allocator = newAllocator(false); ByteBuf a = allocator.heapBuffer(8192); assertEquals(128 * 1024, allocator.usedHeapMemory()); ByteBuf b = allocator.heapBuffer(120 * 1024); ass...
public SnapshotDto setBuildString(@Nullable String buildString) { checkLength(MAX_BUILD_STRING_LENGTH, buildString, "buildString"); this.buildString = buildString; return this; }
@Test void hashcode_whenDifferentInstanceWithDifferentValues_shouldNotBeEqual() { SnapshotDto snapshotDto1 = create(); SnapshotDto snapshotDto2 = create().setBuildString("some-other-string"); assertThat(snapshotDto1).doesNotHaveSameHashCodeAs(snapshotDto2); }
@Override public FSINFO3Response fsinfo(XDR xdr, RpcInfo info) { return fsinfo(xdr, getSecurityHandler(info), info.remoteAddress()); }
@Test(timeout = 60000) public void testFsinfo() throws Exception { HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar"); long dirId = status.getFileId(); int namenodeId = Nfs3Utils.getNamenodeId(config); FileHandle handle = new FileHandle(dirId, namenodeId); XDR xdr_req = new XDR(); ...
@Deprecated public BigtableConfig withBigtableOptionsConfigurator( SerializableFunction<BigtableOptions.Builder, BigtableOptions.Builder> configurator) { checkArgument(configurator != null, "configurator can not be null"); return toBuilder().setBigtableOptionsConfigurator(configurator).build(); }
@Test public void testWithBigtableOptionsConfigurator() { assertEquals( CONFIGURATOR, config.withBigtableOptionsConfigurator(CONFIGURATOR).getBigtableOptionsConfigurator()); thrown.expect(IllegalArgumentException.class); config.withBigtableOptionsConfigurator(null); }
public static void stepExecuted(final Supplier<PMMLStep> stepSupplier, final PMMLRuntimeContext context) { if (!context.getEfestoListeners().isEmpty()) { final PMMLStep step = stepSupplier.get(); context.getEfestoListeners().forEach(listener -> listener.stepExecuted(step)); } ...
@Test void stepExecuted() { final Map<Integer, PMMLStep> listenerFeedback = new HashMap<>(); int size = 3; PMMLRuntimeContext pmmlContext = getPMMLContext(size, listenerFeedback); AtomicBoolean invoked = new AtomicBoolean(false); PMMLListenerUtils.stepExecuted(() -> new PMMLS...
@Override public void onEvent(Event event) { if (EnvUtil.getStandaloneMode()) { return; } if (event instanceof ClientEvent.ClientVerifyFailedEvent) { syncToVerifyFailedServer((ClientEvent.ClientVerifyFailedEvent) event); } else { syncToAllServer((C...
@Test void testOnClientChangedEventWithoutResponsible() { when(clientManager.isResponsibleClient(client)).thenReturn(false); distroClientDataProcessor.onEvent(new ClientEvent.ClientChangedEvent(client)); verify(distroProtocol, never()).syncToTarget(any(), any(), anyString(), anyLong()); ...
public static Permission getPermission(String name, String serviceName, String... actions) { PermissionFactory permissionFactory = PERMISSION_FACTORY_MAP.get(serviceName); if (permissionFactory == null) { throw new IllegalArgumentException("No permissions found for service: " + serviceName);...
@Test public void getPermission_DistributedExecutor() { Permission permission = ActionConstants.getPermission("foo", DistributedExecutorService.SERVICE_NAME); assertNotNull(permission); assertTrue(permission instanceof ExecutorServicePermission); }
public Collection<RepositoryTuple> swapToRepositoryTuples(final YamlRuleConfiguration yamlRuleConfig) { RepositoryTupleEntity tupleEntity = yamlRuleConfig.getClass().getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) { return Collections.emptyList(); } if (t...
@Test void assertSwapToRepositoryTuplesWithNodeYamlRuleConfiguration() { NodeYamlRuleConfiguration yamlRuleConfig = new NodeYamlRuleConfiguration(); yamlRuleConfig.setMapValue(Collections.singletonMap("k", new LeafYamlRuleConfiguration("v"))); yamlRuleConfig.setCollectionValue(Collections.si...
@Override public String getMetadata() { if (getEntityDescriptorElement() != null) { return Configuration.serializeSamlObject(getEntityDescriptorElement()).toString(); } throw new TechnicalException("Metadata cannot be retrieved because entity descriptor is null"); }
@Test public void resolveMetadataDocumentAsString() { metadataResolver.init(); var metadata = metadataResolver.getMetadata(); assertNotNull(metadata); }
@Override public void collectionItemAdded(final Host bookmark) { try { if(this.isLocked()) { log.debug("Skip indexing collection while loading"); } else { this.index(); } } finally { super.collectionI...
@Test public void testLoadAwaitFilesystemChange() throws Exception { final Local source = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); final CountDownLatch wait = new CountDownLatch(1); final BookmarkCollection collection = new BookmarkCollection(source) { ...
@Override public Collection<String> getDistributedTableNames() { return Collections.emptySet(); }
@Test void assertGetDistributedTableMapper() { assertThat(new LinkedList<>(ruleAttribute.getDistributedTableNames()), is(Collections.emptyList())); }
@Override public void updateRouter(Router osRouter) { checkNotNull(osRouter, ERR_NULL_ROUTER); checkArgument(!Strings.isNullOrEmpty(osRouter.getId()), ERR_NULL_ROUTER_ID); osRouterStore.updateRouter(osRouter); log.info(String.format(MSG_ROUTER, osRouter.getId(), MSG_UPDATED)); }
@Test(expected = NullPointerException.class) public void testUpdateRouterWithNull() { target.updateRouter(null); }
public static String getRelativeLinkTo(Item p) { Map<Object, String> ancestors = new HashMap<>(); View view = null; StaplerRequest request = Stapler.getCurrentRequest(); for (Ancestor a : request.getAncestors()) { ancestors.put(a.getObject(), a.getRelativePath()); ...
@Issue("JENKINS-17713") @Test public void getRelativeLinkTo_MavenModules() { StaplerRequest req = createMockRequest("/jenkins"); try ( MockedStatic<Stapler> mocked = mockStatic(Stapler.class); MockedStatic<Jenkins> mockedJenkins = mockStatic(Jenkins.class) ) {...
@VisibleForTesting static Path resolveEntropy(Path path, EntropyInjectingFileSystem efs, boolean injectEntropy) throws IOException { final String entropyInjectionKey = efs.getEntropyInjectionKey(); if (entropyInjectionKey == null) { return path; } else { ...
@Test void testFullUriNonMatching() throws Exception { EntropyInjectingFileSystem efs = new TestEntropyInjectingFs("_entropy_key_", "ignored"); Path path = new Path("s3://hugo@myawesomehost:55522/path/to/the/file"); assertThat(EntropyInjector.resolveEntropy(path, efs, true)).isEqualTo(path)...
@Deprecated public static String getJwt(JwtClaims claims) throws JoseException { String jwt; RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey( jwtConfig.getKey().getFilename(),jwtConfig.getKey().getPassword(), jwtConfig.getKey().getKeyName()); // A JWT is a JWS and/...
@Test public void longLivedTrainingJwt() throws Exception { JwtClaims claims = ClaimsUtil.getTestClaims("steve", "EMPLOYEE", "f7d42348-c647-4efb-a52d-4c5787421e72", Arrays.asList("training.accounts.read", "training.customers.read", "training.myaccounts.read", "training.transacts.read"), "user"); cla...
@Override public final int readInt() throws EOFException { final int i = readInt(pos); pos += INT_SIZE_IN_BYTES; return i; }
@Test public void testReadIntByteOrder() throws Exception { int readInt = in.readInt(LITTLE_ENDIAN); int theInt = Bits.readIntL(INIT_DATA, 0); assertEquals(theInt, readInt); }
public boolean isDryrun() { return dryrun; }
@Test public void testDryRunParamInRobotFrameworkCamelConfigurations() throws Exception { RobotFrameworkEndpoint robotFrameworkEndpoint = createEndpointWithOption(""); assertEquals(false, robotFrameworkEndpoint.getConfiguration().isDryrun()); robotFrameworkEndpoint = createEndpointWithOption...
public static URI parse(String featureIdentifier) { return parse(FeaturePath.parse(featureIdentifier)); }
@Test void reject_feature_with_lines() { Executable testMethod = () -> FeatureIdentifier.parse(URI.create("classpath:/path/to/file.feature:10:40")); IllegalArgumentException actualThrown = assertThrows(IllegalArgumentException.class, testMethod); assertThat("Unexpected exception message", ac...
public void eval(Object... args) throws HiveException { // When the parameter is (Integer, Array[Double]), Flink calls udf.eval(Integer, // Array[Double]), which is not a problem. // But when the parameter is a single array, Flink calls udf.eval(Array[Double]), // at this point java's v...
@Test public void testOverSumInt() throws Exception { Object[] constantArgs = new Object[] {null, 4}; DataType[] dataTypes = new DataType[] {DataTypes.INT(), DataTypes.INT()}; HiveGenericUDTF udf = init(TestOverSumIntUDTF.class, constantArgs, dataTypes); udf.eval(5, 4); a...
@Override public OpensearchDistribution get() { return distribution.get(); }
@Test void testDetection() { final OpensearchDistribution x64 = provider(tempDir, OpensearchArchitecture.x64).get(); Assertions.assertThat(x64.version()).isEqualTo("2.5.0"); Assertions.assertThat(x64.platform()).isEqualTo("linux"); Assertions.assertThat(x64.architecture()).isEqualTo(...
public MethodConfig setParameter(String key, String value) { if (parameters == null) { parameters = new ConcurrentHashMap<String, String>(); } parameters.put(key, value); return this; }
@Test public void setParameter() throws Exception { MethodConfig methodConfig = new MethodConfig(); Assert.assertNull(methodConfig.parameters); Assert.assertNull(methodConfig.getParameter("aa")); methodConfig.setName("echo"); methodConfig.setParameter("aa", "11"); Ass...
public void resetPositionsIfNeeded() { Map<TopicPartition, Long> offsetResetTimestamps = offsetFetcherUtils.getOffsetResetTimestamp(); if (offsetResetTimestamps.isEmpty()) return; resetPositionsAsync(offsetResetTimestamps); }
@Test public void testUpdateFetchPositionResetToEarliestOffset() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.requestOffsetReset(tp0, OffsetResetStrategy.EARLIEST); client.prepareResponse(listOffsetRequestMatcher(ListOffsetsRequest.EARLIEST_TIMESTAMP, ...
@SafeVarargs public static <S extends Comparable<S>> QueryLimit<S> getMinimum(QueryLimit<S> limit, QueryLimit<S>... limits) { Optional<QueryLimit<S>> queryLimit = Stream.concat( limits != null ? Arrays.stream(limits) : Stream.empty(), limit != null ? Stream.of(limit) : St...
@Test public void testGetMinimum() { QueryLimit<Duration> longLimit = createDurationLimit(new Duration(2, HOURS), SYSTEM); QueryLimit<Duration> shortLimit = createDurationLimit(new Duration(1, MINUTES), RESOURCE_GROUP); assertEquals(getMinimum(QUERY_LIMIT_DURATION, longLimit, shortLimit)...
@Override public RateLimiter rateLimiter(final String name) { return rateLimiter(name, getDefaultConfig()); }
@Test public void rateLimiterNewWithNullConfigSupplier() throws Exception { exception.expect(NullPointerException.class); exception.expectMessage("Supplier must not be null"); RateLimiterRegistry registry = new InMemoryRateLimiterRegistry(config); Supplier<RateLimiterConfig> rateLimi...
public static String getMimeType(String filePath) { if (StrUtil.isBlank(filePath)) { return null; } // 补充一些常用的mimeType if (StrUtil.endWithIgnoreCase(filePath, ".css")) { return "text/css"; } else if (StrUtil.endWithIgnoreCase(filePath, ".js")) { return "application/x-javascript"; } else if (StrUti...
@Test public void getMimeTypeTest() { String mimeType = FileUtil.getMimeType("test2Write.jpg"); assertEquals("image/jpeg", mimeType); mimeType = FileUtil.getMimeType("test2Write.html"); assertEquals("text/html", mimeType); mimeType = FileUtil.getMimeType("main.css"); assertEquals("text/css", mimeType); ...
public Optional<Result> execute( List<RowMetaAndData> rows ) throws KettleException { if ( rows.isEmpty() || stopped ) { return Optional.empty(); } Trans subtrans = this.createSubtrans(); running.add( subtrans ); parentTrans.addActiveSubTransformation( subTransName, subtrans ); // Pass p...
@Test public void blockAndUnblockTwice() throws KettleException, InterruptedException, ExecutionException, TimeoutException { final ExecutorService executorService = Executors.newFixedThreadPool( 1 ); TransMeta parentMeta = new TransMeta( this.getClass().getResource( "subtrans-executor-parent.ktr" ...
@Override public boolean recycle() { if (this.buffer != null) { if (this.buffer.capacity() > MAX_CAPACITY_TO_RECYCLE) { // If the size is too large, we should release it to avoid memory overhead this.buffer = null; } else { BufferUtils....
@Test public void testRecycle() { final ByteBufferCollector object = ByteBufferCollector.allocateByRecyclers(); object.recycle(); final ByteBufferCollector object2 = ByteBufferCollector.allocateByRecyclers(); Assert.assertSame(object, object2); object2.recycle(); }
protected abstract MemberData memberData(Subscription subscription);
@Test public void testMemberData() { List<String> topics = topics(topic); List<TopicPartition> ownedPartitions = partitions(tp(topic1, 0), tp(topic2, 1)); List<Subscription> subscriptions = new ArrayList<>(); // add subscription in all ConsumerProtocolSubscription versions su...
@Override public CustomResponse<Void> logout(TokenInvalidateRequest tokenInvalidateRequest) { return userServiceClient.logout(tokenInvalidateRequest); }
@Test void logout_ValidTokenInvalidateRequest_ReturnsCustomResponse() { // Given TokenInvalidateRequest tokenInvalidateRequest = TokenInvalidateRequest.builder() .accessToken("validAccessToken") .refreshToken("validRefreshToken") .build(); Cu...
@Override protected final CompletableFuture<MetricCollectionResponseBody> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { metricFetcher.update(); final MetricStore.ComponentMetricStore component...
@Test void testListMetrics() throws Exception { final CompletableFuture<MetricCollectionResponseBody> completableFuture = testMetricsHandler.handleRequest( HandlerRequest.create( EmptyRequestBody.getInstance(), ...
@Override public ByteBuf getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); return this; }
@Test public void getDirectByteBufferBoundaryCheck() { assertThrows(IndexOutOfBoundsException.class, new Executable() { @Override public void execute() { buffer.getBytes(-1, ByteBuffer.allocateDirect(0)); } }); }
@VisibleForTesting static Optional<String> checkSchemas( final LogicalSchema schema, final LogicalSchema other ) { final Optional<String> keyError = checkSchemas(schema.key(), other.key(), "key ") .map(msg -> "Key columns must be identical. " + msg); if (keyError.isPresent()) { ret...
@Test public void shouldEnforceNoReordering() { // Given: final LogicalSchema someSchema = LogicalSchema.builder() .keyColumn(ColumnName.of("k0"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("f0"), SqlTypes.BIGINT) .valueColumn(ColumnName.of("f1"), SqlTypes.STRING) .build(); ...
public static <T, PredicateT extends ProcessFunction<T, Boolean>> Filter<T> by( PredicateT predicate) { return new Filter<>(predicate); }
@Test @Category(NeedsRunner.class) public void testFilterByMethodReferenceWithLambda() { PCollection<Integer> output = p.apply(Create.of(1, 2, 3, 4, 5, 6, 7)).apply(Filter.by(new EvenFilter()::isEven)); PAssert.that(output).containsInAnyOrder(2, 4, 6); p.run(); }
public static ExecutionArrayList<Byte> hexToBytes(ExecutionContext ctx, String value) { String hex = prepareNumberString(value, true); if (hex == null) { throw new IllegalArgumentException("Hex string must be not empty!"); } int len = hex.length(); if (len % 2 > 0) { ...
@Test public void hexToBytes_Test() { String input = "0x01752B0367FA000500010488FFFFFFFFFFFFFFFF33"; byte[] expected = {1, 117, 43, 3, 103, -6, 0, 5, 0, 1, 4, -120, -1, -1, -1, -1, -1, -1, -1, -1, 51}; List<Byte> actual = TbUtils.hexToBytes(ctx, input); Assertions.assertEquals(toList...
@Override public boolean tryAcquireJobLock(Configuration conf) { Path path = new Path(locksDir, String.format(LOCKS_DIR_JOB_FILENAME, getJobJtIdentifier(conf))); return tryCreateFile(conf, path); }
@Test(expected = NullPointerException.class) public void testMissingJobId() { Configuration conf = new Configuration(); tested.tryAcquireJobLock(conf); }
public synchronized Topology addSource(final String name, final String... topics) { internalTopologyBuilder.addSource(null, name, null, null, null, topics); return this; }
@Test public void shouldNotAllowNullTopicsWhenAddingSourceWithPattern() { assertThrows(NullPointerException.class, () -> topology.addSource("source", (Pattern) null)); }
public static String findDatumOverlijden(List<Container> categorieList){ return findValue(categorieList, CATEGORIE_OVERLIJDEN, ELEMENT_DATUM_OVERLIJDEN); }
@Test public void testFindDatumOverlijden() { assertThat(CategorieUtil.findDatumOverlijden(createFullCategories()), is("datumoverlijden")); }
private StorageVolume getStorageVolumeOfDb(String svName) throws DdlException { StorageVolume sv = null; if (svName.equals(StorageVolumeMgr.DEFAULT)) { sv = getDefaultStorageVolume(); if (sv == null) { throw ErrorReportException.report(ErrorCode.ERR_NO_DEFAULT_STO...
@Test public void testGetStorageVolumeOfDb() throws DdlException, AlreadyExistsException { new Expectations() { { editLog.logSetDefaultStorageVolume((SetDefaultStorageVolumeLog) any); } }; SharedDataStorageVolumeMgr sdsvm = new SharedDataStorageVolume...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldDeserializeJsonObjectWithMissingFields() { // Given: final Map<String, Object> orderRow = new HashMap<>(AN_ORDER); orderRow.remove("ordertime"); final byte[] bytes = serializeJson(orderRow); // When: final Struct result = deserializer.deserialize(SOME_TOPIC, bytes); ...
public static DatabaseBackendHandler newInstance(final QueryContext queryContext, final ConnectionSession connectionSession, final boolean preferPreparedStatement) { SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); SQLStatement sqlStatement = sqlStatementContext.getSqlSta...
@Test void assertNewInstanceReturnedUnicastDatabaseBackendHandlerWithDAL() { String sql = "DESC tbl"; SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class); when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DALStatement.class)); DatabaseBackendHandler ac...
@Override public AccessKeyPair getAccessKey(URL url, Invocation invocation) { AccessKeyPair accessKeyPair = new AccessKeyPair(); String accessKeyId = url.getParameter(Constants.ACCESS_KEY_ID_KEY); String secretAccessKey = url.getParameter(Constants.SECRET_ACCESS_KEY_KEY); accessKeyPa...
@Test void testGetAccessKey() { URL url = URL.valueOf("dubbo://10.10.10.10:2181") .addParameter(Constants.ACCESS_KEY_ID_KEY, "ak") .addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk"); DefaultAccessKeyStorage defaultAccessKeyStorage = new DefaultAccessKeyStorage(); ...
@Override public boolean checkAndSetSupportPartitionInformation(Connection connection) { String catalogSchema = "information_schema"; String partitionInfoTable = "partitions"; // Different types of MySQL protocol databases have different case names for schema and table names, // whic...
@Test public void testCheckPartitionWithoutPartitionsTable() { try { JDBCSchemaResolver schemaResolver = new MysqlSchemaResolver(); Assert.assertFalse(schemaResolver.checkAndSetSupportPartitionInformation(connection)); } catch (Exception e) { System.out.println(e....
public static PipelineJob get(final String jobId) { return JOBS.get(jobId); }
@Test void assertGet() { assertThat(PipelineJobRegistry.get("foo_job"), is(job)); }
public byte[] toByteArray() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { write(stream); } catch (IOException e) { // Should not happen as ByteArrayOutputStream does not throw IOException on write throw new RuntimeException(e); } ...
@Test public void testToByteArray_lt_OP_PUSHDATA1() { // < OP_PUSHDATA1 for (byte len = 1; len < OP_PUSHDATA1; len++) { byte[] bytes = new byte[len]; RANDOM.nextBytes(bytes); byte[] expected = ByteUtils.concat(new byte[] { len }, bytes); byte[] actual ...
@Override public void start(EdgeExplorer explorer, int startNode) { SimpleIntDeque fifo = new SimpleIntDeque(); GHBitSet visited = createBitSet(); visited.add(startNode); fifo.push(startNode); int current; while (!fifo.isEmpty()) { current = fifo.pop(); ...
@Test public void testBFS2() { BreadthFirstSearch bfs = new BreadthFirstSearch() { @Override protected GHBitSet createBitSet() { return new GHTBitSet(); } @Override public boolean goFurther(int v) { counter++; ...
boolean hasCapacity() { if (aggBuilder.getRecordsCount() == 0) { return true; } int avgSize = (sizeBytes - BASE_OVERHEAD) / aggBuilder.getRecordsCount(); return sizeBytes + avgSize <= maxAggregatedBytes; }
@Test public void testHasCapacity() { aggregator = new RecordsAggregator(BASE_OVERHEAD + PARTITION_KEY_OVERHEAD + 100, new Instant()); assertThat(aggregator.addRecord(PARTITION_KEY, null, new byte[30])).isTrue(); assertThat(aggregator.hasCapacity()).isTrue(); // can fit next record of avg size assertT...
@Override public synchronized boolean registerAETitle(String aet) throws ConfigurationException { ensureConfigurationExists(); try { registerAET(aet); return true; } catch (AETitleAlreadyExistsException e) { return false; } }
@Test public void testRegisterAETitle() throws Exception { config.unregisterAETitle("TEST-AET1"); assertTrue(config.registerAETitle("TEST-AET1")); assertFalse(config.registerAETitle("TEST-AET1")); assertTrue( Arrays.asList(config.listRegisteredAETitles()) ...
public boolean denied(String name, MediaType mediaType) { String suffix = (name.contains(".") ? name.substring(name.lastIndexOf(".") + 1) : "").toLowerCase(Locale.ROOT); boolean defaultDeny = false; if (CollectionUtils.isNotEmpty(denyFiles)) { if (denyFiles.contains(suffix)) { ...
@Test public void testDenyWithAllow(){ FileUploadProperties uploadProperties=new FileUploadProperties(); uploadProperties.setAllowFiles(new HashSet<>(Arrays.asList("xls","json"))); assertFalse(uploadProperties.denied("test.xls", MediaType.ALL)); assertFalse(uploadProperties.denied("...
protected static String normalizePath( String path, String scheme ) { String normalizedPath = path; if ( path.startsWith( "\\\\" ) ) { File file = new File( path ); normalizedPath = file.toURI().toString(); } else if ( scheme == null ) { File file = new File( path ); normalizedPath ...
@Test public void testNormalizePathWithFile() { String vfsFilename = "\\\\tmp/acltest.txt"; String testNormalizePath = KettleVFS.normalizePath( vfsFilename, "someScheme" ); assertTrue( testNormalizePath.startsWith( "file:/" ) ); }
public static int fromLogical(Schema schema, java.util.Date value) { if (!(LOGICAL_NAME.equals(schema.name()))) throw new DataException("Requested conversion of Time object but the schema does not match."); Calendar calendar = Calendar.getInstance(UTC); calendar.setTime(value); ...
@Test public void testFromLogical() { assertEquals(0, Time.fromLogical(Time.SCHEMA, EPOCH.getTime())); assertEquals(10000, Time.fromLogical(Time.SCHEMA, EPOCH_PLUS_TEN_THOUSAND_MILLIS.getTime())); }
@Override public Iterator<E> iterator() { return new ElementIterator(); }
@Test public void testIteratorHasNextReturnsFalseIfIteratedOverAll() { final OAHashSet<Integer> set = new OAHashSet<>(8); populateSet(set, 1); final Iterator<Integer> iterator = set.iterator(); iterator.next(); assertFalse(iterator.hasNext()); }
@Override public Object toKsqlRow(final Schema connectSchema, final Object connectData) { if (connectData == null) { return null; } return toKsqlValue(schema, connectSchema, connectData, ""); }
@Test public void shouldTranslateStructFieldWithDifferentCase() { // Given: final Schema structSchema = SchemaBuilder .struct() .field("INT", SchemaBuilder.OPTIONAL_INT32_SCHEMA) .optional() .build(); final Schema rowSchema = SchemaBuilder .struct() .field(...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { attributes.find(file, listener); return true; } catch(NotfoundException e) { ...
@Test public void testFindFile() throws Exception { final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new GoogleStorageTou...
@Override public void close() throws IOException { if (null != closeableGroup) { closeableGroup.close(); } }
@Test public void testCloseBeforeInitializeDoesntThrow() throws IOException { catalog = new SnowflakeCatalog(); // Make sure no exception is thrown if we call close() before initialize(), in case callers // add a catalog to auto-close() helpers but end up never using/initializing a catalog. catalog.c...
@Override public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity) throws Exception { HttpRequestBase request = build(uri, httpMethod, requestHttpEntity, defaultConfig); CloseableHttpResponse response = client.execute(request); return new...
@Test void testExecuteForFormWithoutConfig() throws Exception { isForm = true; Header header = Header.newInstance().addParam(HttpHeaderConsts.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); Map<String, String> body = new HashMap<>(); body.put("test", "test"); RequestHtt...
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { long datetime = payload.readInt8(); return 0L == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDateTime(datetime); }
@Test void assertRead() { when(payload.readInt8()).thenReturn(99991231235959L); LocalDateTime expected = LocalDateTime.of(9999, 12, 31, 23, 59, 59); assertThat(new MySQLDatetimeBinlogProtocolValue().read(columnDef, payload), is(Timestamp.valueOf(expected))); }
@SuppressWarnings("unchecked") public static <S extends Stanza> S parseStanza(String stanza) throws XmlPullParserException, SmackParsingException, IOException { return (S) parseStanza(getParserFor(stanza), XmlEnvironment.EMPTY); }
@Test public void multipleMessageBodiesParsingTest() throws Exception { String control = XMLBuilder.create("message") .namespace(StreamOpen.CLIENT_NAMESPACE) .a("from", "romeo@montague.lit/orchard") .a("to", "juliet@capulet.lit/balcony") .a("id", "zid615d9") ...