focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) { if (xmppServer.isLocal(user)) { try { getUser(user.getNode()); return true; } catch (final UserNotFoundException e) { return false; ...
@Test public void isRegisteredUserTrueWillReturnFalseNoAnswer() { final boolean result = userManager.isRegisteredUser(new JID(USER_ID, REMOTE_XMPP_DOMAIN, null), true); assertThat(result, is(false)); verify(iqRouter).route(any()); }
@Override public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException { authorizationService.validate(); }
@Test(expected = LoginCanceledException.class) public void testConnectMissingKey() throws Exception { session.close(); session.getHost().getCredentials().setOauth(OAuthTokens.EMPTY); session.login(new DisabledLoginCallback() { @Override public Credentials prompt(final...
public void generate() throws IOException { packageNameByTypes.clear(); generatePackageInfo(); generateTypeStubs(); generateMessageHeaderStub(); for (final List<Token> tokens : ir.messages()) { final Token msgToken = tokens.get(0); final List<...
@Test void shouldGeneratePutCharSequence() throws Exception { final UnsafeBuffer buffer = new UnsafeBuffer(new byte[4096]); generator().generate(); final Object encoder = wrap(buffer, compileCarEncoder().getConstructor().newInstance()); final Object decoder = getCarDecoder(buffe...
List<DataflowPackage> stageClasspathElements( Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) { return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions); }
@Test public void testPackageUploadWithExplicitPackageName() throws Exception { Pipe pipe = Pipe.open(); File tmpFile = makeFileWithContents("file.txt", "This is a test!"); final String overriddenName = "alias.txt"; when(mockGcsUtil.getObjects(anyListOf(GcsPath.class))) .thenReturn( ...
static Range consolidateRanges(List<RangeNode> ranges) { boolean consistent = true; Range result = new RangeImpl(); for (RangeNode r : ranges) { Comparable lowValue = null; if (r.getStart() instanceof NumberNode startNode) { lowValue = startNode.getValue()...
@Test void consolidateRangesInvalidRepeatedUB() { Range lowRange = new RangeImpl(Range.RangeBoundary.CLOSED, null, 50, Range.RangeBoundary.CLOSED); Range highRange = new RangeImpl(Range.RangeBoundary.CLOSED, null, 100, Range.RangeBoundary.CLOSED); List<RangeNode> ranges = getRangeNodes(lowRa...
public static <K, V> Write<K, V> write() { return new AutoValue_CdapIO_Write.Builder<K, V>().build(); }
@Test public void testWriteObjectCreationFailsIfPluginConfigIsNull() { assertThrows( IllegalArgumentException.class, () -> CdapIO.<String, String>write().withPluginConfig(null)); }
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testDbGetHex() throws Exception { web3j.dbGetHex("testDB", "myKey").send(); verifyResult( "{\"jsonrpc\":\"2.0\",\"method\":\"db_getHex\"," + "\"params\":[\"testDB\",\"myKey\"],\"id\":1}"); }
public void deserialize() throws KettleException { String xml = rep.getStepAttributeString( idStep, REPO_TAG ); requireNonNull( MetaXmlSerializer.deserialize( xml ) ) .to( stepMetaInterface ); }
@Test public void testDeserialize() throws KettleException { StepMetaPropsTest.FooMeta blankMeta = new StepMetaPropsTest.FooMeta(); String serialized = serialize( from( stepMeta ) ); doReturn( serialized ).when( repo ).getStepAttributeString( stepId, "step-xml" ); RepoSerializer .builder() ...
@Override public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return join(otherStream, toValueJoinerWithKey(joiner), w...
@Test public void shouldNotAllowNullValueJoinerOnTableJoinWithJoiner() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join(testTable, (ValueJoiner<? super String, ? super String, ?>) null, Joined.as("name"))); assertThat(ex...
@Override protected File getFile(HandlerRequest<EmptyRequestBody> handlerRequest) { if (logDir == null) { return null; } // wrapping around another File instantiation is a simple way to remove any path information // - we're // solely interested in the filename ...
@Test void testGetJobManagerCustomLogsExistingButForbiddenFile() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("../%s", FORBIDDEN_FILENAME))); assertThat(actualFile).isNotNull().doesNotExist(); }
public static void main(String[] args) throws IOException, ClassNotFoundException { // Write V1 var fishV1 = new RainbowFish("Zed", 10, 11, 12); LOGGER.info("fishV1 name={} age={} length={} weight={}", fishV1.getName(), fishV1.getAge(), fishV1.getLengthMeters(), fishV1.getWeightTons()); RainbowF...
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public Long clusterCountKeysInSlot(int slot) { RedisClusterNode node = clusterGetNodeForSlot(slot); MasterSlaveEntry entry = executorService.getConnectionManager().getEntry(new InetSocketAddress(node.getHost(), node.getPort())); RFuture<Long> f = executorService.readAsync(entry, St...
@Test public void testClusterCountKeysInSlot() { Long t = connection.clusterCountKeysInSlot(1); assertThat(t).isZero(); }
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time zon...
@Test public void shouldThrowIfInvalidTimeZone() { // When: final KsqlException e = assertThrows( KsqlFunctionException.class, () -> udf.timestampToString(1638360611123L, "yyyy-MM-dd HH:mm:ss.SSS", "PST") ); // Then: assertThat(e.getMessage(), containsString("Unknown time-...
public boolean readData() throws KettleException { // Clear the information // clear(); File file = new File( getKettleLocalRepositoriesFile() ); if ( !file.exists() || !file.isFile() ) { if ( log.isDetailed() ) { log.logDetailed( BaseMessages.getString( PKG, "RepositoryMeta.Log.NoRep...
@Test public void testReadData() throws Exception { LogChannel log = mock( LogChannel.class ); doReturn( getClass().getResource( "repositories.xml" ).getPath() ).when( repoMeta ).getKettleUserRepositoriesFile(); doReturn( log ).when( repoMeta ).newLogChannel(); repoMeta.readData(); String reposi...
@Nonnull public static List<IndexIterationPointer> normalizePointers(@Nonnull List<IndexIterationPointer> result, boolean descending) { if (result.size() <= 1) { // single pointer, nothing to do return result; } // without the same ordering of pointers order of resul...
@Test void normalizePointersMerge() { assertThat(normalizePointers(arrayListOf( pointer(singleton(5)), pointer(singleton(5))), false)) .as("Should merge overlapping ranges") .containsExactly(pointer(singleton(5))); assertThat(normalizePointers(arrayLi...
@Override public Enumerable<Object> execute(final ShardingSphereTable table, final ScanExecutorContext scanContext) { String databaseName = executorContext.getDatabaseName(); String schemaName = executorContext.getSchemaName(); DatabaseType databaseType = optimizerContext.getParserContext(da...
@Test void assertExecuteWithStatistics() { OptimizerContext optimizerContext = mock(OptimizerContext.class, RETURNS_DEEP_STUBS); when(optimizerContext.getParserContext(any()).getDatabaseType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "PostgreSQL")); SQLFederationExecutorCont...
public static double of(int[] truth, int[] prediction) { if (truth.length != prediction.length) { throw new IllegalArgumentException(String.format("The vector sizes don't match: %d != %d.", truth.length, prediction.length)); } ConfusionMatrix confusion = ConfusionMatrix.of(truth, pr...
@Test public void test() { System.out.println("MCC"); int[] truth = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
@Override public boolean isWarProject() { String packaging = project.getPackaging(); return "war".equals(packaging) || "gwt-app".equals(packaging); }
@Test public void testIsWarProject_gwtAppPackagingIsWar() { when(mockMavenProject.getPackaging()).thenReturn("gwt-app"); assertThat(mavenProjectProperties.isWarProject()).isTrue(); }
public void addComponentEnvVariables(Map<String, String> env, Properties properties, boolean custom) { Set<String> toRemove = new HashSet<>(); env.forEach((k, v) -> { if (custom) { toRemove.add(k); String ck = "camel.component." + k.substring(16).toLowerCase(L...
@Test public void testAddComponentEnvVariables() { Map<String, String> env = MainHelper.filterEnvVariables(new String[] { "CAMEL_COMPONENT_" }); env.put("CAMEL_COMPONENT_AWS2_S3_ACCESS_KEY", "mysecretkey"); Properties prop = new OrderedProperties(); helper.addComponentEnvVariables(en...
public static String escape(String string) { return EscapeUtil.escapeHtml4(string); }
@Test public void escapeTest(){ final String a = "<>"; final String escape = XmlUtil.escape(a); Console.log(escape); }
@Override public int size() { return 0; }
@Test public void testForEachObject() { Set<Integer> results = new HashSet<>(); es.forEach((Consumer<? super Integer>) results::add); assertEquals(0, results.size()); }
@Operation(summary = "queryUnauthorizedProject", description = "QUERY_UNAUTHORIZED_PROJECT_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", schema = @Schema(implementation = int.class, example = "100", required = true)) }) @GetMapping(value = "/unauth-project") @Res...
@Test public void testQueryUnauthorizedProject() { Result result = new Result(); putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryUnauthorizedProject(user, 2)).thenReturn(result); ProjectListResponse response = projectV2Controller.queryUnauthorizedProject(user, 2); ...
static ArgumentParser argParser() { ArgumentParser parser = ArgumentParsers .newArgumentParser("producer-performance") .defaultHelp(true) .description("This tool is used to verify the producer performance. To enable transactions, " + "you c...
@Test public void testUnexpectedArg() { String[] args = new String[] { "--test", "test", "--topic", "Hello-Kafka", "--num-records", "5", "--throughput", "100", "--record-size", "100", "--producer-props", "bootstrap.servers=localhos...
@Override public long get() { return complete(asyncCounter.get()); }
@Test(expected = StorageException.Interrupted.class) public void testInterrupted() { AtomicCounterWithErrors atomicCounter = new AtomicCounterWithErrors(); atomicCounter.setErrorState(TestingCompletableFutures.ErrorState.INTERRUPTED_EXCEPTION); DefaultAtomicCounter counter = new DefaultAtomi...
public CacheStats plus(CacheStats other) { return CacheStats.of( saturatedAdd(hitCount, other.hitCount), saturatedAdd(missCount, other.missCount), saturatedAdd(loadSuccessCount, other.loadSuccessCount), saturatedAdd(loadFailureCount, other.loadFailureCount), saturatedAdd(tota...
@Test public void plus() { var one = CacheStats.of(11, 13, 15, 13, 11, 9, 18); var two = CacheStats.of(53, 47, 41, 39, 37, 35, 70); var sum = two.plus(one); checkStats(sum, 124, 64, 64.0 / 124, 60, 60.0 / 124, 56, 52, 52.0 / 108, 56 + 52, 48, 48.0 / (56 + 52), 44, 88); assertThat(sum).is...
public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception { HeaderMap headers = exchange.getRequestHeaders(); String[] origins = headers.get(Headers.ORIGIN).toArray(); if(logger.isTraceEnabled()) logger.trace("origins from the request heade...
@Test public void testMatchOrigin() throws Exception { HeaderMap headerMap = new HeaderMap(); headerMap.add(HOST, "localhost:80"); headerMap.add(ORIGIN, "http://localhost"); HttpServerExchange exchange = new HttpServerExchange(null, headerMap, new HeaderMap(), 10); exchange.s...
@Override public DirectoryTimestamp getDirectoryTimestamp() { return DirectoryTimestamp.implicit; }
@Test public void testFeatures() { assertEquals(Protocol.Case.sensitive, new SFTPProtocol().getCaseSensitivity()); assertEquals(Protocol.DirectoryTimestamp.implicit, new SFTPProtocol().getDirectoryTimestamp()); }
public final void parseVersion(String version) { versionParts = new ArrayList<>(); if (version != null) { final Pattern rx = Pattern .compile("(\\d+[a-z]{1,3}$|[a-z]{1,3}[_-]?\\d+|\\d+|(rc|release|snapshot|beta|alpha)$)", Pattern.CASE_INSENSITI...
@Test public void testParseVersion() { String version = "1.2r1"; DependencyVersion instance = new DependencyVersion(); instance.parseVersion(version); List<String> parts = instance.getVersionParts(); assertEquals(3, parts.size()); assertEquals("1", parts.get(0)); ...
private CompletableFuture<Boolean> verifyTxnOwnership(TxnID txnID) { assert ctx.executor().inEventLoop(); return service.pulsar().getTransactionMetadataStoreService() .verifyTxnOwnership(txnID, getPrincipal()) .thenComposeAsync(isOwner -> { if (isOwner...
@Test(timeOut = 30000) public void sendEndTxnOnSubscription() throws Exception { final TransactionMetadataStoreService txnStore = mock(TransactionMetadataStoreService.class); when(txnStore.getTxnMeta(any())).thenReturn(CompletableFuture.completedFuture(mock(TxnMeta.class))); when(txnStore.ve...
@Override public TypeSerializerSchemaCompatibility<T> resolveSchemaCompatibility( TypeSerializerSnapshot<T> oldSerializerSnapshot) { if (!(oldSerializerSnapshot instanceof AvroSerializerSnapshot)) { return TypeSerializerSchemaCompatibility.incompatible(); } AvroSerial...
@Test void anAvroSpecificRecordIsCompatibleAfterARoundTrip() throws IOException { // user is an avro generated test object. AvroSerializer<User> serializer = new AvroSerializer<>(User.class); AvroSerializerSnapshot<User> restored = roundTrip(serializer.snapshotConfiguration()); ass...
@Subscribe public void onChatMessage(ChatMessage chatMessage) { if (chatMessage.getType() != ChatMessageType.TRADE && chatMessage.getType() != ChatMessageType.GAMEMESSAGE && chatMessage.getType() != ChatMessageType.SPAM && chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION) { return; }...
@Test public void testHsFloorNoPb() { ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Floor 1 time: <col=ff0000>1:19</col>. Personal best: 0:28", null, 0); chatCommandsPlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration("personalbest", "hallowed sepulchre floor ...
public static int indexOf(ByteBuf needle, ByteBuf haystack) { if (haystack == null || needle == null) { return -1; } if (needle.readableBytes() > haystack.readableBytes()) { return -1; } int n = haystack.readableBytes(); int m = needle.readableBy...
@Test public void testIndexOf() { ByteBuf haystack = Unpooled.copiedBuffer("abc123", CharsetUtil.UTF_8); assertEquals(0, ByteBufUtil.indexOf(Unpooled.copiedBuffer("a", CharsetUtil.UTF_8), haystack)); assertEquals(1, ByteBufUtil.indexOf(Unpooled.copiedBuffer("bc".getBytes(CharsetUtil.UTF_8)),...
public LatLong avgLatLong() { return LatLong.quickAvgLatLong(point1.latLong(), point2.latLong()); }
@Test public void testAvgLatLong() { Point p1 = Point.builder().latLong(33.63143, -84.33913).time(EPOCH).build(); Point p2 = Point.builder().latLong(33.64143, -84.43913).time(EPOCH).build(); PointPair pair = PointPair.of(p1, p2); LatLong actual = pair.avgLatLong(); LatLong...
public static URL parseURL(String address, Map<String, String> defaults) { if (StringUtils.isEmpty(address)) { throw new IllegalArgumentException("Address is not allowed to be empty, please re-enter."); } String url; if (address.contains("://") || address.contains(URL_PARAM_S...
@Test void testParseUrl2() { String address = "192.168.0.1"; String backupAddress1 = "192.168.0.2"; String backupAddress2 = "192.168.0.3"; Map<String, String> parameters = new HashMap<String, String>(); parameters.put("username", "root"); parameters.put("password", "...
@Override public Set<Link> getIngressLinks(ConnectPoint dst) { return filter(links.values(), link -> dst.equals(link.dst())); }
@Test public final void testGetIngressLinks() { final ConnectPoint d1P1 = new ConnectPoint(DID1, P1); final ConnectPoint d2P2 = new ConnectPoint(DID2, P2); LinkKey linkId1 = LinkKey.linkKey(d1P1, d2P2); LinkKey linkId2 = LinkKey.linkKey(d2P2, d1P1); LinkKey linkId3 = LinkKey....
@SuppressWarnings("unchecked") public <V> V run(String callableName, RetryOperation<V> operation) { int attempt = 1; while (true) { try { return operation.run(); } catch (Exception e) { if (attempt >= maxAttempts || !retryPredic...
@Test public void testSuccess() { assertEquals( retryDriver.run("test", new MockOperation(5, RETRYABLE_EXCEPTION)), Integer.valueOf(5)); }
public static Range<Comparable<?>> safeIntersection(final Range<Comparable<?>> range, final Range<Comparable<?>> connectedRange) { try { return range.intersection(connectedRange); } catch (final ClassCastException ex) { Class<?> clazz = getRangeTargetNumericType(range, connectedR...
@Test void assertSafeIntersectionForDouble() { Range<Comparable<?>> range = Range.closed(1242.114, 31474836.12); Range<Comparable<?>> connectedRange = Range.downTo(567.34F, BoundType.OPEN); Range<Comparable<?>> newRange = SafeNumberOperationUtils.safeIntersection(range, connectedRange); ...
public static void loadPropertiesFile(final String filenameOrUrl) { loadPropertiesFile(PropertyAction.REPLACE, filenameOrUrl); }
@Test void shouldDoNothingToSystemPropsWhenLoadingFileWhichDoesNotExist() { final int originalSystemPropSize = System.getProperties().size(); loadPropertiesFile("$unknown-file$"); assertEquals(originalSystemPropSize, System.getProperties().size()); }
public static <K, C, V, T> V computeIfAbsent(Map<K, V> target, K key, BiFunction<C, T, V> mappingFunction, C param1, T param2) { Objects.requireNonNull(target, "target"); Objects.requireNonNull(key, "key"); Objects.requireNonNull(mappingFunction, ...
@Test public void computeIfAbsentNotExistTargetTest() { BiFunction<String, String, String> mappingFunction = (a, b) -> a + b; try { MapUtil.computeIfAbsent(null, "key", mappingFunction, "param1", "param2"); } catch (Exception e) { if (e instanceof NullPointerException...
@Override public boolean isReturnEntityRequested() { String returnEntityValue = getParameter(RestConstants.RETURN_ENTITY_PARAM); if (returnEntityValue == null) { // Default to true for backward compatibility so that existing clients can receive entity without using parameter return true; ...
@Test(dataProvider = "returnEntityParameterData") public void testReturnEntityParameter(String uri, boolean expectReturnEntity, boolean expectException) throws RestLiSyntaxException { final ResourceContextImpl context = new ResourceContextImpl(new PathKeysImpl(), new RestRequestBuilder(URI.create(uri)) ...
public static String encodeUrlWithoutPadding(byte[] bytes) { return getInstance().internalEncodeUrlWithoutPadding(bytes); }
@Test public void testEncodeUrlWithoutPadding() { final String helloWorldEncoded = "SGVsbG8gV29ybGQ"; final String helloWorldTwoLinesEncoded = "SGVsbG8gV29ybGQNCk5ldyBMaW5lMg"; final String helloWorldTwoLinesAndNewLineEncoded = "SGVsbG8gV29ybGQNClNlY29uZCBMaW5lDQo"; final String hell...
public static boolean electionWasClean(int newLeader, int[] isr) { return newLeader == NO_LEADER || Replicas.contains(isr, newLeader); }
@Test public void testElectionWasClean() { assertTrue(PartitionRegistration.electionWasClean(1, new int[]{1, 2})); assertFalse(PartitionRegistration.electionWasClean(1, new int[]{0, 2})); assertFalse(PartitionRegistration.electionWasClean(1, new int[]{})); assertTrue(PartitionRegistr...
public X509Certificate sign(PrivateKey caPrivateKey, X509Certificate caCertificate, PKCS10CertificationRequest csr, RenewalPolicy renewalPolicy) throws Exception { Instant validFrom = Instant.now(clock); var validUntil = validFrom.plus(renewalPolicy.parsedCertificateLifetime()); return sign(caP...
@Test void testSigningCertWithTwoHoursLifetime() throws Exception { var result = sign("PT2H"); assertThat(result).isNotNull(); assertThat(result.getNotAfter()).isEqualTo(fixedInstant.plus(2, ChronoUnit.HOURS)); }
public static String getBoxedClassName(ParameterField parameterField) { return parameterField.getDataType() == null ? Object.class.getName() : getBoxedClassName(parameterField.getDataType()); }
@Test void getBoxedClassNameByDataTypes() { List<DataType> dataTypes = getDataTypes(); dataTypes.forEach(dataType -> { String retrieved = org.kie.pmml.compiler.api.utils.ModelUtils.getBoxedClassName(dataType); commonVerifyEventuallyBoxedClassName(retrieved, dataType); ...
public static String toJson(UpdateRequirement updateRequirement) { return toJson(updateRequirement, false); }
@Test public void testAssertViewUUIDToJson() { String uuid = "2cc52516-5e73-41f2-b139-545d41a4e151"; String expected = String.format("{\"type\":\"assert-view-uuid\",\"uuid\":\"%s\"}", uuid); UpdateRequirement actual = new UpdateRequirement.AssertViewUUID(uuid); assertThat(UpdateRequirementParser.toJso...
public void assignStates() { checkStateMappingCompleteness(allowNonRestoredState, operatorStates, tasks); Map<OperatorID, OperatorState> localOperators = new HashMap<>(operatorStates); // find the states of all operators belonging to this task and compute additional // information in f...
@Test void testChannelStateAssignmentDownscaling() throws JobException, JobExecutionException { List<OperatorID> operatorIds = buildOperatorIds(2); Map<OperatorID, OperatorState> states = buildOperatorStates(operatorIds, 3); Map<OperatorID, ExecutionJobVertex> vertices = bui...
Double calculateMedian(List<Double> durationEntries) { if (durationEntries.isEmpty()) { return 0.0; } Collections.sort(durationEntries); int middle = durationEntries.size() / 2; if (durationEntries.size() % 2 == 1) { return durationEntries.get(middle); ...
@Test void calculateMedianOf() { OutputStream out = new ByteArrayOutputStream(); UsageFormatter usageFormatter = new UsageFormatter(out); Double result = usageFormatter.calculateMedian(asList(2.0, 9.0)); assertThat(result, is(closeTo(5.5, EPSILON))); }
@Override public void close() { close(Duration.ofMillis(Long.MAX_VALUE)); }
@Test public void testInterceptorConstructClose() { try { Properties props = new Properties(); // test with client ID assigned by KafkaProducer props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999"); props.setProperty(ProducerConfig.INTER...
@Override public Addresses loadAddresses(ClientConnectionProcessListenerRegistry listenerRunner) { List<String> configuredAddresses = networkConfig.getAddresses(); if (configuredAddresses.isEmpty()) { configuredAddresses.add("127.0.0.1"); } Addresses addresses = new Add...
@Test public void whenMix() throws UnknownHostException { ClientNetworkConfig config = new ClientNetworkConfig(); config.addAddress("10.0.0.1:5701"); config.addAddress("10.0.0.1:5702"); config.addAddress("10.0.0.2"); DefaultAddressProvider provider = new DefaultAddressProvide...
@Override public String getName() { return getLogger().getName(); }
@Test public void getName() throws Exception { Logger loggerFromClass = new MiddlewareLoggerImpl(MiddlewareLoggerImplTest.class); Logger logger = new MiddlewareLoggerImpl(MiddlewareLoggerImplTest.class.getCanonicalName()); Assert.assertEquals(loggerFromClass.getName(), logger.getName()); ...
public static List<Transformation<?>> optimize(List<Transformation<?>> transformations) { final Map<Transformation<?>, Set<Transformation<?>>> outputMap = buildOutputMap(transformations); final LinkedHashSet<Transformation<?>> chainedTransformations = new LinkedHashSet<>(); fina...
@Test void testTransformationWithMultipleOutputs() { ExternalPythonProcessOperator<?, ?> processOperator1 = createProcessOperator("f1", Types.STRING(), Types.LONG()); ExternalPythonProcessOperator<?, ?> processOperator2 = createProcessOperator("f2", Types.STRING(), Ty...
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(command, delay, unit); }
@Test public void schedule() { underTest.schedule(runnable, delay, SECONDS); verify(executorService).schedule(runnable, delay, SECONDS); }
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) { return containsAtLeastEntriesIn(accumulateMap("containsAtLeast", k0, v0, rest)); }
@Test public void containsAtLeastWrongValue_sameToStringForValues() { expectFailureWhenTestingThat(ImmutableMap.of("jan", 1L, "feb", 2L, "mar", 3L)) .containsAtLeast("jan", 1, "feb", 2); assertFailureKeys( "keys with wrong values", "for key", "expected value", "but got ...
@Override public LoggingConfiguration getConfiguration(final Path file) throws BackgroundException { final Path bucket = containerService.getContainer(file); if(bucket.isRoot()) { return LoggingConfiguration.empty(); } try { final Storage.Buckets.Get request =...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { new GoogleStorageLoggingFeature(session).getConfiguration( new Path(new AsciiRandomStringService().random().toLowerCase(Locale.ROOT), EnumSet.of(Path.Type.directory)) ); }
static int determineOperatorReservoirSize(int operatorParallelism, int numPartitions) { int coordinatorReservoirSize = determineCoordinatorReservoirSize(numPartitions); int totalOperatorSamples = coordinatorReservoirSize * OPERATOR_OVER_SAMPLE_RATIO; return (int) Math.ceil((double) totalOperatorSamples / op...
@Test public void testOperatorReservoirSize() { assertThat(SketchUtil.determineOperatorReservoirSize(5, 3)) .isEqualTo((10_002 * SketchUtil.OPERATOR_OVER_SAMPLE_RATIO) / 5); assertThat(SketchUtil.determineOperatorReservoirSize(123, 123)) .isEqualTo((123_00 * SketchUtil.OPERATOR_OVER_SAMPLE_RAT...
public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions, Timer timer) { return beginningOrEndOffset(partitions, ListOffsetsRequest.LATEST_TIMESTAMP, timer); }
@Test public void testEndOffsets() { buildFetcher(); assignFromUser(singleton(tp0)); client.prepareResponse(listOffsetResponse(tp0, Errors.NONE, ListOffsetsRequest.LATEST_TIMESTAMP, 5L)); assertEquals(singletonMap(tp0, 5L), offsetFetcher.endOffsets(singleton(tp0), time.timer(5000L)))...
public static String collectPath(String... pathParts) { final StringBuilder sb = new StringBuilder(); for (String item : pathParts) { if (StringUtils.isBlank(item)) { continue; } final String path = trimPath(item); if (StringUtils.isNotBlan...
@Test(description = "not fail when passed path is empty") public void testEmptyCollectedPath() { final String path = PathUtils.collectPath(""); assertEquals(path, "/"); }
public String getReference(Reference reference) { StringWriter writer = new StringWriter(); try { getWriter(writer).writeReference(reference); } catch (IOException e) { throw new AssertionError("Unexpected IOException"); } return writer.toString(); }
@Test public void testReference() throws IOException { TestDexFormatter formatter = new TestDexFormatter(); Assert.assertEquals( "reference", formatter.getReference(mock(Reference.class))); }
public static void logSQL(final QueryContext queryContext, final boolean showSimple, final ExecutionContext executionContext) { log("Logic SQL: {}", queryContext.getSql()); if (showSimple) { logSimpleMode(executionContext.getExecutionUnits()); } else { logNormalMode(execu...
@Test void assertLogNormalSQLWithoutParameter() { SQLLogger.logSQL(queryContext, false, new ExecutionContext(queryContext, executionUnits, mock(RouteContext.class))); assertThat(appenderList.size(), is(4)); assertTrue(appenderList.stream().allMatch(loggingEvent -> Level.INFO == loggingEvent....
public static boolean canLoad(String filePath) { if (filePath == null) { return false; } try (DataInputStream dis = new DataInputStream(Files.newInputStream(Paths.get(filePath)))) { int magic = dis.readInt(); return magic == CLASS_MAGIC || magic == BTraceProbePersisted.MAGIC; } catch (...
@Test void canLoadNonExistingFile() { assertFalse(BTraceProbeFactory.canLoad("!invalid path")); }
public synchronized void setLevel(Level newLevel) { if (level == newLevel) { // nothing to do; return; } if (newLevel == null && isRootLogger()) { throw new IllegalArgumentException("The level of the root logger cannot be set to null"); } leve...
@Test public void testEnabledX_Off() throws Exception { root.setLevel(Level.OFF); checkLevelThreshold(loggerTest, Level.OFF); }
public PullRequestFilesProducer(GitHubEndpoint endpoint) throws Exception { super(endpoint); Registry registry = endpoint.getCamelContext().getRegistry(); Object service = registry.lookupByName(GitHubConstants.GITHUB_PULL_REQUEST_SERVICE); if (service != null) { LOG.debug("U...
@Test public void testPullRequestFilesProducer() { PullRequest pullRequest = pullRequestService.addPullRequest("testPullRequestFilesProducer"); latestPullRequestNumber = pullRequest.getNumber(); CommitFile file = new CommitFile(); file.setFilename("testfile"); List<CommitFi...
public Release findLatestActiveRelease(Namespace namespace) { return findLatestActiveRelease(namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName()); }
@Test public void testFindRelease() throws Exception { String someAppId = "1"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; long someReleaseId = 1; String someReleaseKey = "someKey"; String someValidConfiguration = "{\"apollo.bar\": \"foo\"}"; ...
@Override public ConnectResponse<ConnectorInfo> create( final String connector, final Map<String, String> config ) { try { final Map<String, String> maskedConfig = QueryMask.getMaskedConnectConfig(config); LOG.debug("Issuing create request to Kafka Connect at URI {} with name {} and conf...
@Test public void testCreateWithError() throws JsonProcessingException { // Given: WireMock.stubFor( WireMock.post(WireMock.urlEqualTo(pathPrefix + "/connectors")) .withHeader(AUTHORIZATION.toString(), new EqualToPattern(AUTH_HEADER)) .withHeader(CUSTOM_HEADER_NAME, new EqualTo...
public static Index withRelations(String name) { return new Index(name, true); }
@Test public void withRelations_index_name_can_not_contain_underscore_except__all_keyword() { // doesn't fail Index.withRelations("_all"); assertThatThrownBy(() -> Index.withRelations("_")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Index name must be lower-case letters or '_a...
@Override public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) { ExampleTableHandle exampleTableHandle = (ExampleTableHandle) tableHandle; checkArgument(exampleTableHandle.getConnectorId().equals(connectorId), "tableHandle is not for this ...
@Test public void testGetColumnHandles() { // known table assertEquals(metadata.getColumnHandles(SESSION, NUMBERS_TABLE_HANDLE), ImmutableMap.of( "text", new ExampleColumnHandle(CONNECTOR_ID, "text", createUnboundedVarcharType(), 0), "value", new ExampleColumnHand...
@Override public void delete(PageId pageId) throws IOException, PageNotFoundException { Callable<Void> callable = () -> { mPageStore.delete(pageId); return null; }; try { mTimeLimter.callWithTimeout(callable, mTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { ...
@Test public void delete() throws Exception { mPageStore.put(PAGE_ID, PAGE); mTimeBoundPageStore.delete(PAGE_ID); assertThrows(PageNotFoundException.class, () -> mPageStore.get(PAGE_ID, 0, PAGE.length, new ByteArrayTargetBuffer(mBuf, 0))); }
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { if(directory.isRoot()) { final AttributedList<Path> list = new AttributedList<>(); for(RootFolder root : session.roots()) { switch(root.g...
@Test public void testListRoot() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path directory = new Path("/", EnumSet.of(AbstractPath.Type.directory, Path.Type.volume)); final AttributedList<Path> list = new StoregateListService(session, nodeid...
public String toString() { return getFilePaths() == null || getFilePaths().length == 0 ? "File Input (unknown file)" : "File Input (" + Arrays.toString(this.getFilePaths()) + ')'; }
@Test void testToStringWithoutPathSet() { final DummyFileInputFormat format = new DummyFileInputFormat(); assertThat(format.toString()) .as("The toString() should be correct.") .isEqualTo("File Input (unknown file)"); }
@Override public String telnet(Channel channel, String message) { if (StringUtils.isEmpty(message)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(mess...
@Test void testChangePath() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "demo"); assertEquals("Used the demo as default.\r\nYou...
@Override public void execute(Context context) { editionProvider.get().ifPresent(edition -> { if (!edition.equals(EditionProvider.Edition.COMMUNITY)) { return; } Map<String, Integer> filesPerLanguage = reportReader.readMetadata().getNotAnalyzedFilesByLanguageMap() .entrySet() ...
@Test public void do_nothing_SQ_community_edition_if_cpp_files_in_report_is_zero() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.Analy...
@Override public Collection<String> split(String in) { String text = in.replaceAll("\\r?\\n", " "); return Arrays.asList(StringUtils.split(text)); }
@Test public void testSplit() { Collection<String> split = wordSplitStrategy.split("Hello World\n Foo Bar"); assertEquals(4, split.size()); assertEquals("Bar", new ArrayList<>(split).get(3)); }
@Override public <UK, UV> MapState<UK, UV> getMapState(MapStateDescriptor<UK, UV> stateProperties) { KeyedStateStore keyedStateStore = checkPreconditionsAndGetKeyedStateStore(stateProperties); stateProperties.initializeSerializerUnlessSet(this::createSerializer); return keyedStateStore.getMa...
@Test void testMapStateReturnsEmptyMapByDefault() throws Exception { StreamingRuntimeContext context = createMapOperatorRuntimeContext(); MapStateDescriptor<Integer, String> descr = new MapStateDescriptor<>("name", Integer.class, String.class); MapState<Integer, String> sta...
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void definedAsEmpty() throws ScanException { propertyContainer0.putProperty("empty", ""); String input = "a=${empty}"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); Assertions...
@Override public DynamicMessage parse(final InputStream inputStream) { try { return DynamicMessage.newBuilder(messageDescriptor) .mergeFrom(inputStream, ExtensionRegistryLite.getEmptyRegistry()) .build(); } catch (IOException e) { throw...
@Test public void testParseThrowException() { InputStream inputStream = new ByteArrayInputStream("test".getBytes()); assertThrows(RuntimeException.class, () -> dynamicMessageMarshaller.parse(inputStream)); }
@Override public ConnectResponse<ConnectorStateInfo> status(final String connector) { try { LOG.debug("Issuing status request to Kafka Connect at URI {} with name {}", connectUri, connector); final ConnectResponse<ConnectorStateInfo> connectResponse = withRetries(() -> Request ...
@Test public void testStatus() throws JsonProcessingException { // Given: WireMock.stubFor( WireMock.get(WireMock.urlEqualTo(pathPrefix + "/connectors/foo/status")) .withHeader(AUTHORIZATION.toString(), new EqualToPattern(AUTH_HEADER)) .withHeader(CUSTOM_HEADER_NAME, new EqualT...
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { //set OfficeParserConfig if the user hasn't specified one configure(context); // Have the OOXML file processed OO...
@Test public void testEmbeddedPDF() throws Exception { Metadata metadata = new Metadata(); StringWriter sw = new StringWriter(); SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); ...
public static String u8(long v) { char[] result = new char[16]; for (int i = 0; i < 16; i++) { result[15 - i] = Character.forDigit((int) v & 0x0f, 16); v >>= 4; } return new String(result); }
@Test public void testU8() { Assert.assertEquals("0000000000000000", Hex.u8(0L)); Assert.assertEquals("0000016b5086c128", Hex.u8(1560424137000L)); Assert.assertEquals("000462d53c8abac0", Hex.u8(1234567890123456L)); }
@Override public boolean delete() throws FileSystemException { return requireResolvedFileObject().delete(); }
@Test public void testDelegatesDelete() throws FileSystemException { fileObject.delete(); verify( resolvedFileObject, times( 1 ) ).delete(); }
public void addAll(PartitionIdSet other) { bitSet.or(other.bitSet); resetSize(); }
@Test public void test_addAll_fromPartitionIdSet() { partitionIdSet.addAll(listOf(0, 1, 2, 3, 4)); PartitionIdSet other = new PartitionIdSet(271); other.addAll(partitionIdSet); assertContents(other); }
@Override public Serde<GenericKey> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> schemaRegistryClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, f...
@Test public void shouldWrapInLoggingSerdeWindowed() { // When: factory .create(format, TIMED_WND, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt, Optional.empty()); // Then: verify(innerFactory).wrapInLoggingSerde(any(), eq(LOGGER_PREFIX), eq(processingLogCxt), ...
@Override public Collection<ThreadPoolPlugin> getAllEnableThreadPoolPlugins() { return enableThreadPoolPlugins.values(); }
@Test public void testGetAllEnableThreadPoolPlugins() { GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager(); manager.enableThreadPoolPlugin(new TestPlugin("1")); manager.enableThreadPoolPlugin(new TestPlugin("2")); Assert.assertEquals(2, manager.getAllE...
public static UThrow create(UExpression expression) { return new AutoValue_UThrow(expression); }
@Test public void serialization() { SerializableTester.reserializeAndAssert( UThrow.create(UNewClass.create(UClassIdent.create("java.lang.IllegalArgumentException")))); }
public long getTimeout() { return timeout; }
@Test @DirtiesContext public void testCreateEndpointDefaultNoTimeout() throws Exception { ExecEndpoint e = createExecEndpoint("exec:test"); assertEquals(ExecEndpoint.NO_TIMEOUT, e.getTimeout()); }
@VisibleForTesting static OpenAPI createDocumentation( String title, DocumentingRestEndpoint restEndpoint, RestAPIVersion apiVersion) { final OpenAPI openApi = new OpenAPI(); // eagerly initialize some data-structures to simplify operations later on openApi.setPaths(new io.swagg...
@Test void testModelNameClashByTopLevelClassesDetected() { assertThatThrownBy( () -> OpenApiSpecGenerator.createDocumentation( "title", DocumentingRestEndpoint.forRestHandl...
private static LongStream range(long start, long end, long step) { return start > end ? LongStream.empty() : LongStream.iterate(start, n -> n + step).limit(1 + (end - start) / step); }
@Test public void when_receiveRandomTimestamps_then_emitAscending() { // Given final List<Long> timestampsToAdd = LongStream.range(0, 100).boxed().collect(toList()); shuffle(timestampsToAdd); ArrayList<Object> inbox = new ArrayList<>(); for (long ts : timestampsToAdd) { ...
public static byte[] decodeBase64(byte[] base64Data) { return new Base64().decode(base64Data); }
@Test void testDecodeNullOrEmpty() { byte[] b1 = Base64.decodeBase64(null); assertNull(b1); byte[] b2 = Base64.decodeBase64(new byte[] {}); assertEquals(0, b2.length); }
@Override public boolean isVisualizedAutoTrackEnabled() { return false; }
@Test public void isVisualizedAutoTrackEnabled() { Assert.assertFalse(mSensorsAPI.isVisualizedAutoTrackEnabled()); }
@Override protected void close() { // Turn off nacos heartbeat transmission ReflectUtils.invokeMethod(target, "shutdown", null, null); LOGGER.warning("Nacos heartbeat has been closed by user."); }
@Test public void close() throws NoSuchMethodException { final NacosRpcClientHealthInterceptor interceptor = new NacosRpcClientHealthInterceptor(); final RpcClient rpcClient = Mockito.mock(RpcClient.class); interceptor.doBefore(buildContext(rpcClient)); interceptor.close(); M...
@Override public void addChildren(Deque<Expression> expressions) { if (expression != null) { expression.addChildren(expressions); } }
@Test public void addChildren() { @SuppressWarnings("unchecked") Deque<Expression> expressions = mock(Deque.class); test.addChildren(expressions); verify(expr).addChildren(expressions); verifyNoMoreInteractions(expr); }
public static boolean equals(FlatRecordTraversalObjectNode left, FlatRecordTraversalObjectNode right) { if (left == null && right == null) { return true; } if (left == null || right == null) { return false; } if (!left.getSchema().getName().equals(right.ge...
@Test public void shouldUseExactFlagToConsiderExtraFieldsInEquality_usingReferences() { TypeState1 typeState1 = new TypeState1(); typeState1.longField = 1L; typeState1.stringField = "A"; typeState1.doubleField = 1.0; typeState1.basicIntField = 1; typeState1.basicIntFi...
@Override public AuthenticationResult authenticate(final ChannelHandlerContext context, final PacketPayload payload) { if (SSL_REQUEST_PAYLOAD_LENGTH == payload.getByteBuf().markReaderIndex().readInt() && SSL_REQUEST_CODE == payload.getByteBuf().readInt()) { if (ProxySSLContext.getInstance().isS...
@Test void assertSSLUnwilling() { ByteBuf byteBuf = createByteBuf(8, 8); byteBuf.writeInt(8); byteBuf.writeInt(80877103); PacketPayload payload = new PostgreSQLPacketPayload(byteBuf, StandardCharsets.UTF_8); ChannelHandlerContext context = mock(ChannelHandlerContext.class); ...
private void updateField( Object[] r ) throws Exception { // Loop through fields for ( int i = 0; i < data.getFieldnr(); i++ ) { // DO CONVERSION OF THE DEFAULT VALUE ... // Entered by user ValueMetaInterface targetValueMeta = data.getOutputRowMeta().getValueMeta( data.getFieldnrs()[i] ); ...
@Test public void testUpdateField() throws Exception { SetValueConstant step = new SetValueConstant( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ); ValueMetaInterface valueMeta = new ValueMetaString( "Field1" ); valueMeta.setStorageType( ValueMetaInterface.STORAGE_TYPE_BINARY_STRING ...
@Override public void trackInstallation(String eventName, JSONObject properties, boolean disableCallback) { }
@Test public void trackInstallation() { mSensorsAPI.setTrackEventCallBack(new SensorsDataTrackEventCallBack() { @Override public boolean onTrackEvent(String eventName, JSONObject eventProperties) { Assert.fail(); return false; } });...
@Override public EntitySuggestionResponse suggest(final String collection, final String valueColumn, final String query, final int page, fin...
@Test void checksPermissionsForEachDocumentWhenUserDoesNotHavePermissionForWholeCollection() { doReturn(false).when(entityPermissionsUtils).hasAllPermission(subject); doReturn(false).when(entityPermissionsUtils).hasReadPermissionForWholeCollection(subject, "dashboards"); final Collection<St...
@Override public void doRun() { if (isServerInPreflightMode.get()) { // we don't want to automatically trigger CSRs during preflight, don't run it if the preflight is still not finished or skipped LOG.debug("Datanode still in preflight mode, skipping cert renewal task"); ...
@Test void testExpiringSoon() throws Exception { final DatanodeKeystore datanodeKeystore = datanodeKeystore(Duration.ofMinutes(1)); final CsrRequester csrRequester = Mockito.mock(CsrRequester.class); final DataNodeCertRenewalPeriodical periodical = new DataNodeCertRenewalPeriodical(datanodeK...
public static <T extends Type> Type decodeIndexedValue( String rawInput, TypeReference<T> typeReference) { return decoder.decodeEventParameter(rawInput, typeReference); }
@Test public void testDecodeIndexedDynamicBytesValue() { DynamicBytes bytes = new DynamicBytes(new byte[] {1, 2, 3, 4, 5}); String encoded = TypeEncoder.encodeDynamicBytes(bytes); String hash = Hash.sha3(encoded); assertEquals( FunctionReturnDecoder.decodeIndexedValu...
public static int decodeInt(InputStream stream) throws IOException { long r = decodeLong(stream); if (r < 0 || r >= 1L << 32) { throw new IOException("varint overflow " + r); } return (int) r; }
@Test public void endOfFileThrowsException() throws Exception { ByteArrayInputStream inStream = new ByteArrayInputStream(new byte[0]); thrown.expect(EOFException.class); VarInt.decodeInt(inStream); }
public static ListenableFuture<EntityFieldsData> findAsync(TbContext ctx, EntityId originatorId) { switch (originatorId.getEntityType()) { // TODO: use EntityServiceRegistry case TENANT: return toEntityFieldsDataAsync(ctx.getTenantService().findTenantByIdAsync(ctx.getTenantId(), (Te...
@Test public void givenUnsupportedEntityTypes_whenFindAsync_thenException() { for (var entityType : EntityType.values()) { if (!SUPPORTED_ENTITY_TYPES.contains(entityType)) { var entityId = EntityIdFactory.getByTypeAndUuid(entityType, RANDOM_UUID); var expectedEx...
@Override public DataSourceProvenance getProvenance() { return new DemoLabelDataSourceProvenance(this); }
@Test public void testInterlockingCrescents() { // Check zero samples throws assertThrows(PropertyException.class, () -> new InterlockingCrescentsDataSource(0)); // Check valid parameters work InterlockingCrescentsDataSource source = new InterlockingCrescentsDataSource(200); ...