focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Rule<ProjectNode> projectNodeRule() { return new PullUpExpressionInLambdaProjectNodeRule(); }
@Test public void testInvalidSwitchWhenExpression() { tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).projectNodeRule()) .setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true") .on(p -> { p.variable("...
public static void main(String[] args) { var king = new OrcKing(); king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
@Override public long getNextTimeOffset(int timesShown) { final Calendar calendar = mCalendarProvider.getInstance(); final int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); if (dayOfYear < mFirstNoticeStart) { // should start showing at May start return ONE_DAY * (mFirstNoticeStart - dayOfYe...
@Test public void testHappyPath() { Calendar instance = Calendar.getInstance(); PeriodsTimeProvider underTest = new PeriodsTimeProvider(() -> instance, 100, 115, 200, 230); instance.set(2020, Calendar.JANUARY, 1, 10, 10, 10); Assert.assertEquals(99 * ONE_DAY, underTest.getNextTimeOffset(0)); inst...
@Override public void setConf(Configuration conf) { super.setConf(conf); getRawMapping().setConf(conf); }
@Test public void testResolve() throws IOException { File mapFile = File.createTempFile(getClass().getSimpleName() + ".testResolve", ".txt"); Files.asCharSink(mapFile, StandardCharsets.UTF_8).write( hostName1 + " /rack1\n" + hostName2 + "\t/rack2\n"); mapFile.deleteOnExit(); TableMappi...
public String create(T entity) { ensureValidScope(entity); return insertedIdAsString(collection.insertOne(entity)); }
@Test void testInvalidScopeFails() { // Invalid scopes not registered with the EntityScopeService should not be allowed. final ScopedDTO invalidScoped = ScopedDTO.builder().name("test").scope("INVALID").build(); assertThatThrownBy(() -> scopedEntityMongoUtils.create(invalidScoped)) ...
public static String escapeIdentifier(String identifier) { return '`' + identifier.replace("`", "``") + '`'; }
@Test public void testEscapeIdentifierNoSpecialCharacters() { assertEquals("`asdasd asd ad`", SingleStoreUtil.escapeIdentifier("asdasd asd ad")); }
public static <T extends SearchablePlugin> List<T> search(Collection<T> searchablePlugins, String query) { return searchablePlugins.stream() .filter(plugin -> Text.matchesSearchTerms(SPLITTER.split(query.toLowerCase()), plugin.getKeywords())) .sorted(comparator(query)) .collect(Collectors.toList()); }
@Test public void searchOrdersPinnedItemsFirstIfThereAreNoExactMatches() { List<SearchablePlugin> results = PluginSearch.search(plugins.values(), "integrat"); assertThat(results, contains(plugins.get("Grand Exchange"), plugins.get("Discord"))); }
public static String createApiVersionUrl(String baseUrl, ExtensionJson json) { return createApiVersionUrl(baseUrl, json.namespace, json.name, json.targetPlatform, json.version); }
@Test public void testCreateApiVersionUrlNoTarget() throws Exception { var baseUrl = "http://localhost/"; assertThat(UrlUtil.createApiVersionUrl(baseUrl, "foo", "bar", null, "1.0.0")) .isEqualTo("http://localhost/api/foo/bar/1.0.0"); }
@ApiOperation(value = "Get Device Profile names (getDeviceProfileNames)", notes = "Returns a set of unique device profile names owned by the tenant." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value ...
@Test public void testGetDeviceProfileNames() throws Exception { var pageLink = new PageLink(Integer.MAX_VALUE); var deviceProfileInfos = doGetTypedWithPageLink("/api/deviceProfileInfos?", new TypeReference<PageData<DeviceProfileInfo>>() { }, pageLink); Assert...
public static List<Endpoint> listenerListToEndPoints( String input, Map<ListenerName, SecurityProtocol> nameToSecurityProto ) { return listenerListToEndPoints(input, n -> { SecurityProtocol result = nameToSecurityProto.get(n); if (result == null) { thr...
@Test public void testAnotherListenerListToEndPointsWithNonDefaultProtoMap() { Map<ListenerName, SecurityProtocol> map = new HashMap<>(); map.put(new ListenerName("CONTROLLER"), SecurityProtocol.PLAINTEXT); assertEquals(Arrays.asList( new Endpoint("CONTROLLER", SecurityProtocol.P...
public static int stringHash(Client client) { String s = buildUniqueString(client); if (s == null) { return 0; } return s.hashCode(); }
@Test void testRevision0() { assertEquals(-1713189600L, DistroUtils.stringHash(client0)); }
@Override public boolean acceptsURL(String url) throws SQLException { return DriverUri.acceptsURL(url); }
@Test public void testDriverInvalidUri() throws Exception { // Invalid prefix for (String invalidPrefixUri : Arrays.asList( "flink://localhost:8888/catalog_name/database_name?sessionId=123&key1=val1&key2=val2", "jdbc::flink://localhost:...
public static int checkLessThan(int n, int expected, String name) { if (n >= expected) { throw new IllegalArgumentException(name + ": " + n + " (expected: < " + expected + ')'); } return n; }
@Test(expected = IllegalArgumentException.class) public void checkLessThanMustFailIfArgumentIsGreaterThanExpected() { RangeUtil.checkLessThan(1, 0, "var"); }
public static Date string2Date(String date) { if (date == null) { return null; } int year = Integer.parseInt(date.substring(0, 2)); int month = Integer.parseInt(date.substring(2, 4)); int day = Integer.parseInt(date.substring(4, 6)); int hour = Integer.parseI...
@Test public void string2Date() { Date date = SmppUtils.string2Date("-300101010000004+"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); assertEquals(5, calendar.get(Calendar.YEAR)); assertEquals(11, calendar.get(Calendar.MONTH)); assertEquals(10...
@VisibleForTesting static boolean isCompressed(String contentEncoding) { return contentEncoding.contains(HttpHeaderValues.GZIP.toString()) || contentEncoding.contains(HttpHeaderValues.DEFLATE.toString()) || contentEncoding.contains(HttpHeaderValues.BR.toString()) ...
@Test void detectsBR() { assertTrue(HttpUtils.isCompressed("br")); }
@SuppressWarnings("rawtypes") public Result waitUntilDone(Config config) { return finishOrTimeout( config, new Supplier[] {() -> false}, () -> jobIsDone(config.project(), config.region(), config.jobId())); }
@Test public void testWaitUntilDoneTimeout() throws IOException { when(client.getJobStatus(any(), any(), any())).thenReturn(JobState.RUNNING); Result result = new PipelineOperator(client).waitUntilDone(DEFAULT_CONFIG); assertThat(result).isEqualTo(Result.TIMEOUT); }
static boolean shouldUpdate(AmazonInfo newInfo, AmazonInfo oldInfo) { if (newInfo.getMetadata().isEmpty()) { logger.warn("Newly resolved AmazonInfo is empty, skipping an update cycle"); } else if (!newInfo.equals(oldInfo)) { if (isBlank(newInfo.get(AmazonInfo.MetaDataKey.instance...
@Test public void testAmazonInfoNoUpdateIfEqual() { AmazonInfo oldInfo = (AmazonInfo) instanceInfo.getDataCenterInfo(); AmazonInfo newInfo = copyAmazonInfo(instanceInfo); assertThat(RefreshableAmazonInfoProvider.shouldUpdate(newInfo, oldInfo), is(false)); }
@Override public RuntimeException handleFault(String failureMessage, Throwable cause) { if (cause == null) { log.error("Encountered {} fault: {}", type, failureMessage); } else { log.error("Encountered {} fault: {}", type, failureMessage, cause); } try { ...
@Test public void testHandleExceptionInAction() { LoggingFaultHandler handler = new LoggingFaultHandler("test", () -> { throw new RuntimeException("action failed"); }); handler.handleFault("uh oh"); // should not throw handler.handleFault("uh oh", new RuntimeException("yi...
@Override public CreateTopicsResult createTopics(final Collection<NewTopic> newTopics, final CreateTopicsOptions options) { final Map<String, KafkaFutureImpl<TopicMetadataAndConfig>> topicFutures = new HashMap<>(newTopics.size()); final CreatableTopicCollec...
@Test public void testTimeoutWithoutMetadata() throws Exception { try (final AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(Time.SYSTEM, mockBootstrapCluster(), newStrMap(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, "10"))) { env.kafkaClient().setNodeApiVersions(NodeApiV...
public static Double interpolateCourse(Double c1, Double c2, double fraction) { if (c1 == null || c2 == null) { return null; } checkArgument(VALID_COURSE_RANGE.contains(c1), "The 1st course: " + c1 + " is not in range"); checkArgument(VALID_COURSE_RANGE.contains(c2), "The 2...
@Test public void testInterpolateCourse_bug() { //A bug was found when interpolating between a Point with course 178 and a Point with 181 double TOL = 0.001; assertEquals( 178.0, interpolateCourse(178.0, 181.0, 0.0), TOL ); assertEquals( ...
public Map<String, String> confirm(RdaConfirmRequest params) { AppSession appSession = appSessionService.getSession(params.getAppSessionId()); AppAuthenticator appAuthenticator = appAuthenticatorService.findByUserAppId(appSession.getUserAppId()); if(!checkSecret(params, appSession) || !checkAcc...
@Test void checkSecretError(){ rdaConfirmRequest.setSecret("secret2"); when(appSessionService.getSession(any())).thenReturn(appSession); when(appAuthenticatorService.findByUserAppId(any())).thenReturn(appAuthenticator); Map<String, String> result = rdaService.confirm(rdaConfirmRequ...
@POST @ApiOperation("Create a new view") @AuditEvent(type = ViewsAuditEventTypes.VIEW_CREATE) public ViewDTO create(@ApiParam @Valid @NotNull(message = "View is mandatory") ViewDTO dto, @Context UserContext userContext, @Context SearchUser searchUser) thro...
@Test public void throwsExceptionWhenCreatingSearchWithFilterThatUserIsNotAllowedToSee() { final ViewsResource viewsResource = createViewsResource( mock(ViewService.class), mock(StartPageService.class), mock(RecentActivityService.class), mock(C...
public void start() { // Start the thread that creates connections asynchronously this.creator.start(); // Schedule a task to remove stale connection pools and sockets long recycleTimeMs = Math.min( poolCleanupPeriodMs, connectionCleanupPeriodMs); LOG.info("Cleaning every {} seconds", ...
@Test public void testConnectionCreatorWithException() throws Exception { // Create a bad connection pool pointing to unresolvable namenode address. ConnectionPool badPool = new ConnectionPool( conf, UNRESOLVED_TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, ClientProtocol.class, null); Blocking...
public static <InputT> UsingBuilder<InputT> of(PCollection<InputT> input) { return new UsingBuilder<>(DEFAULT_NAME, input); }
@Test public void testBuild_ImplicitName() { final PCollection<String> dataset = TestUtils.createMockDataset(TypeDescriptors.strings()); final Split.Output<String> split = Split.of(dataset).using((UnaryPredicate<String>) what -> true).output(); final Filter positive = (Filter) TestUtils.getProduc...
@Override public Sensor addRateTotalSensor(final String scopeName, final String entityName, final String operationName, final Sensor.RecordingLevel recordingLevel, fina...
@Test public void shouldAddRateTotalSensor() { final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, CLIENT_ID, VERSION, time); shouldAddCustomSensor( streamsMetrics.addRateTotalSensor(SCOPE_NAME, ENTITY_NAME, OPERATION_NAME, RecordingLevel.DEBUG), streams...
@Override public InMemoryReaderIterator iterator() throws IOException { return new InMemoryReaderIterator(); }
@Test public void testProgressReporting() throws Exception { List<Integer> elements = Arrays.asList(33, 44, 55, 66, 77, 88); // Should initially read elements at indices: 44@1, 55@2, 66@3, 77@4 Coder<Integer> coder = BigEndianIntegerCoder.of(); InMemoryReader<Integer> inMemoryReader = new InM...
@Override public Mono<AccessToken> requestToken(AuthorizationCodeTokenRequest request) { return Mono .justOrEmpty(request.code()) .map(this::getRedisKey) .flatMap(redis.opsForValue()::get) .switchIfEmpty(Mono.error(() -> new OAuth2Exception(Er...
@Test public void testRequestToken() { StaticApplicationContext context = new StaticApplicationContext(); context.refresh(); context.start(); DefaultAuthorizationCodeGranter codeGranter = new DefaultAuthorizationCodeGranter( new RedisAccessTokenManager(RedisHelper.f...
public String toEncodedString() { StringBuilder sb = new StringBuilder(); try { for (Map.Entry<String, String> entry : entries()) { sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")); if (!Strings.isNullOrEmpty(entry.getValue())) { sb.ap...
@Test void testToEncodedString() { HttpQueryParams qp = new HttpQueryParams(); qp.add("k'1", "v1&"); assertEquals("k%271=v1%26", qp.toEncodedString()); qp = new HttpQueryParams(); qp.add("k+", "\n"); assertEquals("k%2B=%0A", qp.toEncodedString()); }
public void download(String pluginKey, Version version) { Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(true); if (updateCenter.isPresent()) { List<Release> installablePlugins = updateCenter.get().findInstallablePlugins(pluginKey, version); checkRequest(!installable...
@Test public void fail_if_no_compatible_plugin_found() { assertThatThrownBy(() -> pluginDownloader.download("foo", create("1.0"))) .isInstanceOf(BadRequestException.class); }
public boolean lockRecordRecentlyCreated(String lockName) { return lockRecords.contains(lockName); }
@Test void shouldNotLie() { assertThat(lockRecordRegistry.lockRecordRecentlyCreated(NAME)).isFalse(); }
public ReferenceBuilder<T> interfaceClass(Class<?> interfaceClass) { this.interfaceClass = interfaceClass; return getThis(); }
@Test void interfaceClass() { ReferenceBuilder builder = new ReferenceBuilder(); builder.interfaceClass(DemoService.class); Assertions.assertEquals(DemoService.class, builder.build().getInterfaceClass()); }
public TTextFileDesc toThrift() { TTextFileDesc desc = new TTextFileDesc(); if (fieldDelim != null) { desc.setField_delim(fieldDelim); } if (lineDelim != null) { desc.setLine_delim(lineDelim); } if (collectionDelim != null) { desc.setCo...
@Test public void testToThrift() { TextFileFormatDesc desc = new TextFileFormatDesc(null, null, null, null); TTextFileDesc tTextFileDesc = desc.toThrift(); Assert.assertFalse(tTextFileDesc.isSetField_delim()); Assert.assertFalse(tTextFileDesc.isSetLine_delim()); Assert.assert...
@Override public boolean alterOffsets(Map<String, String> connectorConfig, Map<Map<String, ?>, Map<String, ?>> offsets) { AbstractConfig config = new AbstractConfig(CONFIG_DEF, connectorConfig); String filename = config.getString(FILE_CONFIG); if (filename == null || filename.isEmpty()) { ...
@Test public void testAlterOffsetsStdin() { sourceProperties.remove(FileStreamSourceConnector.FILE_CONFIG); Map<Map<String, ?>, Map<String, ?>> offsets = Collections.singletonMap( Collections.singletonMap(FILENAME_FIELD, FILENAME), Collections.singletonMap(POSITION_FI...
public int computeThreshold(StreamConfig streamConfig, CommittingSegmentDescriptor committingSegmentDescriptor, @Nullable SegmentZKMetadata committingSegmentZKMetadata, String newSegmentName) { long desiredSegmentSizeBytes = streamConfig.getFlushThresholdSegmentSizeBytes(); if (desiredSegmentSizeBytes <= ...
@Test public void testApplyMultiplierToTotalDocsWhenTimeThresholdNotReached() { long currentTime = 1640216032391L; Clock clock = Clock.fixed(java.time.Instant.ofEpochMilli(currentTime), ZoneId.of("UTC")); SegmentFlushThresholdComputer computer = new SegmentFlushThresholdComputer(clock); StreamConfig...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); for (final GarbageCollectorMXBean gc : garbageCollectors) { final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); gauges.put(name(name, "count"), (Gauge<Lon...
@Test public void hasAGaugeForGcCounts() { final Gauge<Long> gauge = (Gauge<Long>) metrics.getMetrics().get("PS-OldGen.count"); assertThat(gauge.getValue()) .isEqualTo(1L); }
@SuppressWarnings("unchecked") public static <T> boolean containsAll(T[] array, T... values) { for (T value : values) { if (false == contains(array, value)) { return false; } } return true; }
@Test public void containsAllTest() { Integer[] a = {1, 2, 3, 4, 3, 6}; boolean contains = ArrayUtil.containsAll(a, 4, 2, 6); assertTrue(contains); contains = ArrayUtil.containsAll(a, 1, 2, 3, 5); assertFalse(contains); }
public ContainerLaunchContext completeContainerLaunch() throws IOException { String cmdStr = ServiceUtils.join(commands, " ", false); log.debug("Completed setting up container command {}", cmdStr); containerLaunchContext.setCommands(commands); //env variables if (log.isDebugEnabled()) { ...
@Test public void testDockerContainerMounts() throws IOException { launcher.yarnDockerMode = true; launcher.envVars.put(AbstractLauncher.ENV_DOCKER_CONTAINER_MOUNTS, "s1:t1:ro"); launcher.mountPaths.put("s2", "t2"); launcher.completeContainerLaunch(); String dockerContainerMounts = launche...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } if(containerService.isContainer(file)) { final PathAttributes attributes = new PathAttributes(); ...
@Test public void testRedirectWithNoLocationHeader() throws Exception { final Path container = new Path("profiles.cyberduck.io", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path test = new Path(container, "S3 (HTTP).cyberduckprofile", EnumSet.of(Path.Type.file)); final S3Attrib...
@Override public Mono<Void> backup(Backup backup) { return Mono.usingWhen( createTempDir("halo-full-backup-", scheduler), tempDir -> backupExtensions(tempDir) .then(Mono.defer(() -> backupWorkDir(tempDir))) .then(Mono.defer(() -> packageBackup(tempDir,...
@Test void backupTest() throws IOException { Files.writeString(tempDir.resolve("fake-file"), "halo", StandardOpenOption.CREATE_NEW); var extensionStores = List.of( createExtensionStore("fake-extension-store", "fake-data") ); when(repository.findAll()).thenReturn(Flux.from...
@Override public ObjectNode encode(Instruction instruction, CodecContext context) { checkNotNull(instruction, "Instruction cannot be null"); return new EncodeInstructionCodecHelper(instruction, context).encode(); }
@Test public void modOduSignalIdInstructionTest() { OduSignalId oduSignalId = OduSignalId.oduSignalId(1, 8, new byte[] {8, 0, 0, 0, 0, 0, 0, 0, 0, 0}); L1ModificationInstruction.ModOduSignalIdInstruction instruction = (L1ModificationInstruction.ModOduSignalIdInstruction) ...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldNotCastDecimalTooBig() { // When: final Exception e = assertThrows( ArithmeticException.class, () -> cast(new BigDecimal(10), 2, 1) ); // Then: assertThat(e.getMessage(), containsString("Numeric field overflow")); }
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image) throws IOException { return createFromImage(document, image, 0.75f); }
@Test void testCreateFromImageUSHORT_555_RGB() throws IOException { PDDocument document = new PDDocument(); BufferedImage image = ImageIO.read(JPEGFactoryTest.class.getResourceAsStream("jpeg.jpg")); // create an USHORT_555_RGB image int width = image.getWidth(); int heig...
@Override public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) { super.removeListener(listener); return this; }
@Test public void shouldNotDoAnythingOnRemove() { Channel channel = Mockito.mock(Channel.class); CompleteChannelFuture future = new CompleteChannelFutureImpl(channel); ChannelFutureListener l = Mockito.mock(ChannelFutureListener.class); future.removeListener(l); Mockito.verif...
public static Date getCurrentDate() { return new Date(); }
@Test public void testGetCurrentDate() { Date currentDate = DateUtil.getCurrentDate(); Assertions.assertNotNull(currentDate); }
@Override public AdjacencyMatrix setWeight(int source, int target, double weight) { graph[source][target] = weight; if (!digraph) { graph[target][source] = weight; } return this; }
@Test public void testSetWeight() { System.out.println("setWeight"); g4.setWeight(1, 4, 5.7); assertEquals(5.7, g4.getWeight(1, 4), 1E-10); assertEquals(1.0, g4.getWeight(4, 1), 1E-10); g8.setWeight(1, 4, 5.7); assertEquals(5.7, g8.getWeight(1, 4), 1E-10); as...
public static String getTypeName(final int type) { switch (type) { case START_EVENT_V3: return "Start_v3"; case STOP_EVENT: return "Stop"; case QUERY_EVENT: return "Query"; case ROTATE_EVENT: return "...
@Test public void getTypeNameInputPositiveOutputNotNull21() { // Arrange final int type = 33; // Act final String actual = LogEvent.getTypeName(type); // Assert result Assert.assertEquals("Gtid", actual); }
public Class<T> getConfigurationClass() { return Generics.getTypeParameter(getClass(), Configuration.class); }
@Test void canDetermineConfiguration() throws Exception { assertThat(new PoserApplication().getConfigurationClass()) .isSameAs(FakeConfiguration.class); }
@Override public void checkBeforeUpdate(final AlterReadwriteSplittingRuleStatement sqlStatement) { ReadwriteSplittingRuleStatementChecker.checkAlteration(database, sqlStatement.getRules(), rule.getConfiguration()); }
@Test void assertCheckSQLStatementWithoutToBeAlteredLoadBalancers() { when(database.getRuleMetaData().findRules(any())).thenReturn(Collections.emptyList()); executor.setDatabase(database); ReadwriteSplittingRule rule = mock(ReadwriteSplittingRule.class); when(rule.getConfiguration())...
@Override public void decorateRouteContext(final RouteContext routeContext, final QueryContext queryContext, final ShardingSphereDatabase database, final BroadcastRule broadcastRule, final ConfigurationProperties props, final ConnectionContext connectionContext) { SQLSta...
@Test void assertDecorateBroadcastRouteContextWithSingleDataSource() { BroadcastRuleConfiguration currentConfig = mock(BroadcastRuleConfiguration.class); when(currentConfig.getTables()).thenReturn(Collections.singleton("t_order")); BroadcastRule broadcastRule = new BroadcastRule(currentConfi...
private void unregister(ConnectPoint connectPoint, HandlerRegistration registration) { synchronized (packetHandlers) { packetHandlers.remove(connectPoint, registration); if (packetHandlers.isEmpty()) { cancelPackets(); } } }
@Test public void testUnregister() { // Register a handler and verify the registration is there neighbourManager.registerNeighbourHandler(CP1, HANDLER, APP_ID); assertTrue(verifyRegistration(CP1, HANDLER, APP_ID)); // Unregister the handler but supply a different connect point ...
protected boolean isBoolean(String field, FieldPresence presence) { return isBoolean(object, field, presence); }
@Test public void isBoolean() { assertTrue("is not proper boolean", cfg.isBoolean(BOOLEAN, MANDATORY)); assertTrue("did not detect missing field", expectInvalidField(() -> cfg.isBoolean("none", MANDATORY))); assertTrue("is not proper boolean", cfg.isBoolean("none", OPTIONAL))...
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test public void testMergeAclEntriesUnchanged() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, USER, "bruce", ALL)) .add(aclEntry(ACCESS, GROUP, READ_EXECUTE)) .add(aclEntry(ACCESS, GROUP, "sale...
public ElasticAgentInformationDTO getElasticAgentInformationDTO(ElasticAgentInformation elasticAgentInformation) { return elasticAgentInformationConverterV5.toDTO(elasticAgentInformation); }
@Test public void shouldGetRequestBodyForMigrateCall_withOldConfig() throws CryptoException { ConfigurationProperty property1 = new ConfigurationProperty(new ConfigurationKey("key"), new ConfigurationValue("value")); ConfigurationProperty property2 = new ConfigurationProperty(new ConfigurationKey("k...
@Override public CompletableFuture<JobID> submitJob(@Nonnull JobGraph jobGraph) { CompletableFuture<java.nio.file.Path> jobGraphFileFuture = CompletableFuture.supplyAsync( () -> { try { final java.nio.file.Pa...
@Test void testJobSubmissionFailureCauseForwardedToClient() throws Exception { try (final TestRestServerEndpoint restServerEndpoint = createRestServerEndpoint(new SubmissionFailingHandler())) { try (RestClusterClient<?> restClusterClient = createRestClusterCli...
public DdlCommandResult execute( final String sql, final DdlCommand ddlCommand, final boolean withQuery, final Set<SourceName> withQuerySources ) { return execute(sql, ddlCommand, withQuery, withQuerySources, false); }
@Test public void shouldDropMissingType() { // Given: metaStore.deleteType("type"); // When: final DdlCommandResult result = cmdExec.execute(SQL_TEXT, dropType, false, NO_QUERY_SOURCES); // Then: assertThat("Expected successful execution", result.isSuccess()); assertThat(result.getMessag...
public static Map<String, Class<?>> compile(Map<String, String> classNameSourceMap, ClassLoader classLoader) { return compile(classNameSourceMap, classLoader, null); }
@Test public void compileAndLoadClass() throws Exception { Map<String, String> source = singletonMap("org.kie.memorycompiler.ExampleClass", EXAMPLE_CLASS); Map<String, Class<?>> compiled = KieMemoryCompiler.compile(source, this.getClass().getClassLoader()); Class<?> exampleClazz = compiled....
Record convert(Object data) { return convert(data, null); }
@Test public void testMissingColumnDetectionMapNested() { Table table = mock(Table.class); when(table.schema()).thenReturn(ID_SCHEMA); RecordConverter converter = new RecordConverter(table, config); Map<String, Object> nestedData = createNestedMapData(); SchemaUpdate.Consumer consumer = new Schem...
public boolean accepts( String fileName ) { if ( fileName == null || fileName.indexOf( '.' ) == -1 ) { return false; } String extension = fileName.substring( fileName.lastIndexOf( '.' ) + 1 ); return extension.equals( "ktr" ); }
@Test public void testAccepts() throws Exception { assertFalse( transFileListener.accepts( null ) ); assertFalse( transFileListener.accepts( "NoDot" ) ); assertTrue( transFileListener.accepts( "Trans.ktr" ) ); assertTrue( transFileListener.accepts( ".ktr" ) ); }
public NumericIndicator down() { return down; }
@Test public void testCreation() { final AroonFacade facade = new AroonFacade(data, 5); assertEquals(data, facade.down().getBarSeries()); }
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) { // Set of Visited Schemas IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>(); // Stack that contains the Schemas to process and afterVisitNonTerminal // functions. // Deque<Either<Schema, Supplier<SchemaVi...
@Test public void testVisit3() { String s3 = "{\"type\": \"record\", \"name\": \"ss1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}" + "]}"; Assert.assertEquals("ss1.", Schemas.visit(new Schema.Parser().parse(s3), new TestVisitor())); }
@Override public void process() { JMeterContext context = getThreadContext(); Sampler sam = context.getCurrentSampler(); SampleResult res = context.getPreviousResult(); HTTPSamplerBase sampler; HTTPSampleResult result; if (!(sam instanceof HTTPSamplerBase) || !(res in...
@Test public void testSimpleParse4() throws Exception { HTTPSamplerBase config = makeUrlConfig("/subdir/index\\..*"); HTTPSamplerBase context = makeContext("http://www.apache.org/subdir/previous.html"); String responseText = "<html><head><title>Test page</title></head><body>" ...
static String trimFieldsAndRemoveEmptyFields(String str) { char[] chars = str.toCharArray(); char[] res = new char[chars.length]; /* * set when reading the first non trimmable char after a separator char (or the beginning of the string) * unset when reading a separator */ boolean inField ...
@Test @UseDataProvider("emptyAndtrimmable") public void trimFieldsAndRemoveEmptyFields_ignores_empty_fields_and_trims_fields(String empty, String trimmable) { String expected = trimmable.trim(); assertThat(empty.trim()).isEmpty(); assertThat(trimFieldsAndRemoveEmptyFields(trimmable)).isEqualTo(expected...
@Override public List<ProviderGroup> subscribe(ConsumerConfig config) { String directUrl = config.getDirectUrl(); if (StringUtils.isNotBlank(directUrl)) { List<ConsumerConfig> listeners = notifyListeners.get(directUrl); if (listeners == null) { notifyListeners...
@Test public void testSubscribe() { ConsumerConfig<Object> consumerConfig = new ConsumerConfig<>(); String directUrl = "bolt://alipay.com"; consumerConfig.setDirectUrl(directUrl); List<ProviderGroup> providerGroups = domainRegistry.subscribe(consumerConfig); assertTrue(domain...
boolean hasFile(String fileReference) { return hasFile(new FileReference(fileReference)); }
@Test public void requireThatExistingFileIsFound() throws IOException { String dir = "123"; writeFile(dir); assertTrue(fileServer.hasFile(dir)); }
@Override public Processor<K, Change<V>, KO, SubscriptionWrapper<K>> get() { return new UnbindChangeProcessor(); }
@Test public void leftJoinShouldPropagateDeletionOfAPrimaryKeyThatHadNullFK() { final MockInternalNewProcessorContext<String, SubscriptionWrapper<String>> context = new MockInternalNewProcessorContext<>(); leftJoinProcessor.init(context); context.setRecordMetadata("topic", 0, 0); le...
@Override public void consume(Update update) { super.consume(update); }
@Test void sendsLocalityViolation() { Update update = mockFullUpdate(bot, USER, "/group"); bot.consume(update); verify(silent, times(1)).send(format("Sorry, %s-only feature.", "group"), USER.getId()); }
public void updateBatchSize(int size) { batchSizesUpdater.accept(size); }
@Test public void testUpdateBatchSize() { MetricsRegistry registry = new MetricsRegistry(); try (FakeMetadataLoaderMetrics fakeMetrics = new FakeMetadataLoaderMetrics(registry)) { fakeMetrics.metrics.updateBatchSize(50); assertEquals(50, fakeMetrics.batchSize.get()); ...
public static void delete(final File file, final boolean ignoreFailures) { if (file.exists()) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files)...
@Test void deleteIgnoreFailuresShouldThrowExceptionIfDeleteOfAFileFails() { final File file = mock(File.class); when(file.exists()).thenReturn(true); when(file.delete()).thenReturn(false); assertThrows(NullPointerException.class, () -> IoUtil.delete(file, false)); }
public static int bytesToShortLE(byte[] bytes, int off) { return (bytes[off + 1] << 8) + (bytes[off] & 255); }
@Test public void testBytesToShortLE() { assertEquals(-12345, ByteUtils.bytesToShortLE(SHORT_12345_LE, 0)); }
@Override public int getOriginalPort() { try { return getOriginalPort(getContext(), getHeaders(), getPort()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
@Test void getOriginalPort_EmptyXFFPort() throws URISyntaxException { Headers headers = new Headers(); headers.add(HttpHeaderNames.X_FORWARDED_PORT, ""); // Default to using server port assertEquals(9999, HttpRequestMessageImpl.getOriginalPort(new SessionContext(), headers, 9999)); ...
public static String resolveIpAddress(String hostname) throws UnknownHostException { Preconditions.checkNotNull(hostname, "hostname"); Preconditions.checkArgument(!hostname.isEmpty(), "Cannot resolve IP address for empty hostname"); return InetAddress.getByName(hostname).getHostAddress(); }
@Test public void resolveIpAddress() throws UnknownHostException { assertEquals(NetworkAddressUtils.resolveIpAddress("localhost"), "127.0.0.1"); assertEquals(NetworkAddressUtils.resolveIpAddress("127.0.0.1"), "127.0.0.1"); }
public ChannelFuture close() { return close(ctx().newPromise()); }
@Test @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS) public void writingAfterClosedChannelDoesNotNPE() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(2); Channel serverChannel = null; Channel clientChannel = null; final CountDownLatch latch = new...
@NonNull @VisibleForTesting static String[] getPermissionsStrings(int requestCode) { switch (requestCode) { case CONTACTS_PERMISSION_REQUEST_CODE -> { return new String[] {Manifest.permission.READ_CONTACTS}; } case NOTIFICATION_PERMISSION_REQUEST_CODE -> { if (Build.VERSION.SDK_I...
@Test public void testGetPermissionsStringsContacts() { Assert.assertArrayEquals( new String[] {Manifest.permission.READ_CONTACTS}, PermissionRequestHelper.getPermissionsStrings( PermissionRequestHelper.CONTACTS_PERMISSION_REQUEST_CODE)); }
public static String getSystemProperty(String key) { try { return System.getProperty(key); } catch (Throwable t) { return null; } }
@Test public void testGetSystemProperty() { Assert.assertNull(EagleEyeCoreUtils.getSystemProperty(null)); Assert.assertNull(EagleEyeCoreUtils.getSystemProperty("foo")); }
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void kTableNonMaterializedMapValuesShouldPreserveTopologyStructure() { final StreamsBuilder builder = new StreamsBuilder(); final KTable<Object, Object> table = builder.table("input-topic"); table.mapValues((readOnlyKey, value) -> null); final TopologyDescription describ...
@SuppressWarnings("WeakerAccess") public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) { final Map<String, Object> consumerProps = getCommonConsumerConfigs(); // Get main consumer override configs final Map<String, Object> mainC...
@Test public void shouldBeSupportNonPrefixedConsumerConfigs() { props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(ConsumerConfig.METRICS_NUM_SAMPLES_CONFIG, 1); final StreamsConfig streamsConfig = new StreamsConfig(props); final Map<String, Object> consumerCon...
@Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Version", getVersion()); setAttribute(protobuf...
@Test public void toProtobuf_whenExternalUserAuthentication_shouldWriteIt() { when(commonSystemInformation.getExternalUserAuthentication()).thenReturn("LDAP"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External User Authentication", "LDAP"); }
public static <T extends PipelineOptions> T as(Class<T> klass) { return new Builder().as(klass); }
@Test public void testMultipleMissingGettersThrows() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage( "missing property methods on [org.apache.beam.sdk.options." + "PipelineOptionsFactoryTest$MissingMultipleGetters]"); expectedException.expec...
@Override public void afterMethod(final TargetAdviceObject target, final TargetAdviceMethod method, final Object[] args, final Object result, final String pluginType) { MetricsCollectorRegistry.<CounterMetricsCollector>get(config, pluginType).inc(); }
@Test void assertCountExecuteErrors() { TargetAdviceObjectFixture targetObject = new TargetAdviceObjectFixture(); new ExecuteErrorsCountAdvice().afterMethod(targetObject, mock(TargetAdviceMethod.class), new Object[]{}, null, "FIXTURE"); assertThat(MetricsCollectorRegistry.get(config, "FIXTUR...
@Override public boolean registerThreadPoolPluginSupport(@NonNull ThreadPoolPluginSupport support) { if (!managedThreadPoolPluginSupports.containsKey(support.getThreadPoolId())) { enableThreadPoolPluginRegistrars.values().forEach(registrar -> registrar.doRegister(support)); enableThr...
@Test public void testRegisterThreadPoolPluginSupport() { GlobalThreadPoolPluginManager manager = new DefaultGlobalThreadPoolPluginManager(); Assert.assertTrue(manager.enableThreadPoolPlugin(new TestPlugin("1"))); TestSupport support = new TestSupport("1"); Assert.assertTrue(manager...
public void shutdown(long awaitTerminateMillis) { this.scheduledExecutorService.shutdown(); ThreadUtils.shutdownGracefully(this.consumeExecutor, awaitTerminateMillis, TimeUnit.MILLISECONDS); }
@Test public void testShutdown() throws IllegalAccessException { popService.shutdown(3000L); Field scheduledExecutorServiceField = FieldUtils.getDeclaredField(popService.getClass(), "scheduledExecutorService", true); Field consumeExecutorField = FieldUtils.getDeclaredField(popService.getClas...
@Override public Collection<GroupDto> getGroups() { return emptySet(); }
@Test public void getGroups() { assertThat(githubWebhookUserSession.getGroups()).isEmpty(); }
@Override public QualityGate findEffectiveQualityGate(Project project) { return findQualityGate(project).orElseGet(this::findDefaultQualityGate); }
@Test public void findQualityGate_by_project_found() { QualityGateDto qualityGateDto = new QualityGateDto(); qualityGateDto.setUuid(QUALITY_GATE_DTO.getUuid()); qualityGateDto.setName(QUALITY_GATE_DTO.getName()); when(qualityGateDao.selectByProjectUuid(any(), any())).thenReturn(qualityGateDto); w...
@Override public void process() { JMeterContext context = getThreadContext(); Sampler sam = context.getCurrentSampler(); SampleResult res = context.getPreviousResult(); HTTPSamplerBase sampler; HTTPSampleResult result; if (!(sam instanceof HTTPSamplerBase) || !(res in...
@Test public void testSimpleParse5() throws Exception { HTTPSamplerBase config = makeUrlConfig("/subdir/index\\.h.*"); HTTPSamplerBase context = makeContext("http://www.apache.org/subdir/one/previous.html"); String responseText = "<html><head><title>Test page</title></head><body>" ...
@Override public Object toKsqlRow(final Schema connectSchema, final Object connectData) { if (connectData == null) { return null; } return toKsqlValue(schema, connectSchema, connectData, ""); }
@Test public void shouldTranslateMissingStructFieldToNull() { // Given: final Schema structSchema = SchemaBuilder .struct() .field("INT", SchemaBuilder.OPTIONAL_INT32_SCHEMA) .optional() .build(); final Schema rowSchema = SchemaBuilder .struct() .field("STR...
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) { if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) { throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'."); } return loadManagerWrapper.get();...
@Test(timeOut = 30 * 1000) public void testRoleChange() throws Exception { makePrimaryAsLeader(); var leader = primaryLoadManager; var follower = secondaryLoadManager; BrokerLoadData brokerLoadExpected = new BrokerLoadData(); SystemResourceUsage usage = new SystemResourceUs...
@Override public JType apply(String nodeName, JsonNode node, JsonNode parent, JClassContainer jClassContainer, Schema schema) { String propertyTypeName = getTypeName(node); JType type; if (propertyTypeName.equals("object") || node.has("properties") && node.path("properties").size() > 0) { type =...
@Test public void applyGeneratesBigDecimal() { JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName()); ObjectNode objectNode = new ObjectMapper().createObjectNode(); objectNode.put("type", "number"); when(config.isUseBigDecimals()).thenReturn(true); ...
public static UriTemplate create(String template, Charset charset) { return new UriTemplate(template, true, charset); }
@Test void encodeLiterals() { String template = "https://www.example.com/A Team"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expandedTemplate = uriTemplate.expand(Collections.emptyMap()); assertThat(expandedTemplate).isEqualToIgnoringCase("https://www.example.com/A%20Te...
public static KTableHolder<GenericKey> build( final KGroupedTableHolder groupedTable, final TableAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedTable, aggregate, buildContext, ...
@Test public void shouldBuildAggregatorParamsCorrectlyForAggregate() { // When: aggregate.build(planBuilder, planInfo); // Then: verify(aggregateParamsFactory).createUndoable( INPUT_SCHEMA, NON_AGG_COLUMNS, functionRegistry, FUNCTIONS, KsqlConfig.empty() );...
@Override public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException { if(file.isRoot()) { return true; } try { final Path found = this.search(file, listener); return found != null; } catch(Notfound...
@Test public void testFindPlaceholder() throws Exception { assertTrue(new DefaultFindFeature(new NullSession(new Host(new TestProtocol())) { @Override public AttributedList<Path> list(final Path file, final ListProgressListener listener) { return new AttributedList<>(...
public static void main(String[] args) { // Loading the Logback configuration loadLoggerConfiguration(); // Getting the bar series BarSeries series = CsvTradesLoader.loadBitstampSeries(); // Building the trading strategy Strategy strategy = CCICorrectionStrategy.buildSt...
@Test public void test() { StrategyExecutionLogging.main(null); }
protected static int getMaxRowSize( List<List<?>> results ) { return results.stream().mapToInt( List::size ).max().getAsInt(); }
@Test public void testFastJsonReaderGetMaxRowSize() throws KettleException { List<List<Integer>> mainList = new ArrayList<>(); List<Integer> l1 = new ArrayList<>(); List<Integer> l2 = new ArrayList<>(); List<Integer> l3 = new ArrayList<>(); l1.add( 1 ); l2.add( 1 ); l2.add( 2 ); l3.add...
public String getSubscriptionsForChannel(String subscribeChannel) { return filterService.getFiltersForChannel(subscribeChannel).stream() .map(PrioritizedFilter::toString) .collect(Collectors.joining(",\n", "[", "]")); }
@Test void testGetSubscriptionsForChannel() { String channel = "test"; service.getSubscriptionsForChannel(channel); Mockito.verify(filterService, Mockito.times(1)).getFiltersForChannel(channel); }
public static void destroyAllShellProcesses() { synchronized (CHILD_SHELLS) { for (Shell shell : CHILD_SHELLS.keySet()) { if (shell.getProcess() != null) { shell.getProcess().destroy(); } } CHILD_SHELLS.clear(); } }
@Test(timeout=120000) public void testDestroyAllShellProcesses() throws Throwable { Assume.assumeFalse(WINDOWS); StringBuilder sleepCommand = new StringBuilder(); sleepCommand.append("sleep 200"); String[] shellCmd = {"bash", "-c", sleepCommand.toString()}; final ShellCommandExecutor shexc1 = new ...
public static void setSyncInterval(JobConf job, int syncIntervalInBytes) { job.setInt(SYNC_INTERVAL_KEY, syncIntervalInBytes); }
@Test void setSyncInterval() { JobConf jobConf = new JobConf(); int newSyncInterval = 100000; AvroOutputFormat.setSyncInterval(jobConf, newSyncInterval); assertEquals(newSyncInterval, jobConf.getInt(AvroOutputFormat.SYNC_INTERVAL_KEY, -1)); }
public static Http2MultiplexCodecBuilder forServer(ChannelHandler childHandler) { return new Http2MultiplexCodecBuilder(true, childHandler); }
@Test public void testUnsharableHandler() { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() throws Throwable { Http2MultiplexCodecBuilder.forServer(new UnsharableChannelHandler()); } }); }
@ConstantFunction(name = "subtract", argTypes = {SMALLINT, SMALLINT}, returnType = SMALLINT, isMonotonic = true) public static ConstantOperator subtractSmallInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createSmallInt((short) Math.subtractExact(first.getSmallint(), second.ge...
@Test public void subtractSmallInt() { assertEquals(0, ScalarOperatorFunctions.subtractSmallInt(O_SI_10, O_SI_10).getSmallint()); }
@Override public void accept(Props props) { File homeDir = props.nonNullValueAsFile(PATH_HOME.getKey()); Provider provider = resolveProviderAndEnforceNonnullJdbcUrl(props); String driverPath = driverPath(homeDir, provider); props.set(JDBC_DRIVER_PATH.getKey(), driverPath); }
@Test public void checkAndComplete_sets_driver_path_for_mssql() throws Exception { File driverFile = new File(homeDir, "lib/jdbc/mssql/sqljdbc4.jar"); FileUtils.touch(driverFile); Props props = newProps(JDBC_URL.getKey(), "jdbc:sqlserver://localhost/sonar;SelectMethod=Cursor"); underTest.accept(props...
@Override public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) { if (null == yamlConfig) { return null; } if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) { return new TableDataConsistencyCheckResult(TableDa...
@Test void assertSwapToObjectWithNullYamlTableDataConsistencyCheckResult() { assertNull(yamlTableDataConsistencyCheckResultSwapper.swapToObject((YamlTableDataConsistencyCheckResult) null)); }
@Override public String getTaskType() { return "null"; }
@Test public void shouldKnowItsType() { assertThat(new NullTask().getTaskType(), is("null")); }