focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Object getCell(final int columnIndex) { Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.size() + 1); return data.get(columnIndex - 1); }
@Test void assertGetCellWithOutOfIndex() { assertThrows(IllegalArgumentException.class, () -> new LocalDataQueryResultRow().getCell(1)); }
@Override public void upload(UploadTask uploadTask) throws IOException { Throwable error = getErrorSafe(); if (error != null) { LOG.debug("don't persist {} changesets, already failed", uploadTask.changeSets.size()); uploadTask.fail(error); return; } ...
@Test void testSizeThreshold() throws Exception { int numChanges = 7; int changeSize = 11; int threshold = changeSize * numChanges; withStore( Integer.MAX_VALUE, threshold, MAX_BYTES_IN_FLIGHT, (store, probe) -> { ...
@Udf(description = "Returns a masked version of the input string. All characters of the input" + " will be replaced according to the default masking rules.") @SuppressWarnings("MethodMayBeStatic") // Invoked via reflection public String mask( @UdfParameter("input STRING to be masked") final String input...
@Test public void shouldReturnNullForNullInput() { final String result = udf.mask(null); assertThat(result, is(nullValue())); }
@Override public String toString() { return instance.toString(); }
@Test public void testToString() { MapWritable map = new MapWritable(); final IntWritable key = new IntWritable(5); final Text value = new Text("value"); map.put(key, value); assertEquals("{5=value}", map.toString()); }
@VisibleForTesting JarRunHandler getJarRunHandler() { return jarRunHandler; }
@Test void applicationsRunInSeparateThreads(@TempDir Path tempDir) throws Exception { final Path uploadDir = Files.createDirectories(tempDir.resolve("uploadDir")); // create a copy because the upload handler moves uploaded jars (because it assumes it to be // a temporary file) final ...
public static Sensor pollRatioSensor(final String threadId, final StreamsMetricsImpl streamsMetrics) { final Sensor sensor = streamsMetrics.threadLevelSensor(threadId, POLL + RATIO_SUFFIX, Sensor.RecordingLevel.INFO); final Map<String, String> tagMap ...
@Test public void shouldGetPollRatioSensor() { final String operation = "poll-ratio"; final String ratioDescription = "The fraction of time the thread spent on polling records from consumer"; when(streamsMetrics.threadLevelSensor(THREAD_ID, operation, RecordingLevel.INFO)).thenReturn(expecte...
@Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { matchedTokenList.add(tokenQueue.poll()); return true; }
@Test public void shouldMatch() { Token t1 = new Token("a", 1, 1); Token t2 = new Token("b", 2, 1); TokenQueue tokenQueue = spy(new TokenQueue(Arrays.asList(t1, t2))); List<Token> output = mock(List.class); AnyTokenMatcher matcher = new AnyTokenMatcher(); assertThat(matcher.matchToken(tokenQu...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { ShenyuContext shenyuContext = exchange.getAttribute(Constants.CONTEXT); assert shenyuContext != null; DivideRuleHandle ruleHandle = bu...
@Test public void doExecuteTest() { when(chain.execute(exchange)).thenReturn(Mono.empty()); Mono<Void> result = dividePlugin.doExecute(exchange, chain, selectorData, ruleData); StepVerifier.create(result).expectSubscription().verifyComplete(); DivideRuleHandle divideRuleHandle = Divi...
public static boolean isBlank(CharSequence str) { if ((str == null)) { return true; } int length = str.length(); if (length == 0) { return true; } for (int i = 0; i < length; i++) { char c = str.charAt(i); boolean charNotBla...
@Test public void isBlank() { String string = ""; Assert.assertTrue(StringUtil.isBlank(string)); }
@Override public boolean canManageResource(EfestoResource toProcess) { return toProcess instanceof EfestoFileResource && ((EfestoFileResource) toProcess).getModelType().equalsIgnoreCase(PMML_STRING); }
@Test void canManageResource() throws IOException { String fileName = "LinearRegressionSample.pmml"; File pmmlFile = getFileFromFileName(fileName).orElseThrow(() -> new RuntimeException("Failed to get pmmlFIle")); EfestoFileResource toProcess = new EfestoFileResource(pmmlFile); asser...
public static double getDoubleValue(ConstantOperator constantOperator) { OptionalDouble optionalDouble = doubleValueFromConstant(constantOperator); if (optionalDouble.isPresent()) { return optionalDouble.getAsDouble(); } else { return Double.NaN; } }
@Test public void getDoubleValue() { ConstantOperator constant0 = ConstantOperator.createTinyInt((byte) 1); ConstantOperator constant1 = ConstantOperator.createInt(1000); ConstantOperator constant2 = ConstantOperator.createSmallInt((short) 12); ConstantOperator constant3 = ConstantO...
public AmazonInfo build() { return new AmazonInfo(Name.Amazon.name(), metadata); }
@Test public void payloadWithOtherStuffBeforeAndAfterMetadata() throws IOException { String json = "{" + " \"@class\": \"com.netflix.appinfo.AmazonInfo\"," + " \"foo\": \"bar\"," + " \"metadata\": {" + " \"instance-id\": \"i-123...
public void parse(InputStream file) throws IOException, TikaException { UnsynchronizedByteArrayOutputStream xmpraw = UnsynchronizedByteArrayOutputStream.builder().get(); if (!scanner.parse(file, xmpraw)) { return; } XMPMetadata xmp = null; try (InputStream decoded = ...
@Test public void testParseJpeg() throws IOException, TikaException { Metadata metadata = new Metadata(); try (InputStream stream = getResourceAsStream("/test-documents/testJPEG_commented.jpg")) { // set some values before extraction to see that they are overridden metadata.s...
public static int toSeconds(TimeRange timeRange) { if (timeRange.getFrom() == null || timeRange.getTo() == null) { return 0; } try { return Seconds.secondsBetween(timeRange.getFrom(), timeRange.getTo()).getSeconds(); } catch (IllegalArgumentException e) { ...
@Test public void toSecondsReturnsCorrectNumberOfSeconds() throws Exception { DateTime from = DateTime.now(DateTimeZone.UTC); DateTime to = from.plusMinutes(5); assertThat(TimeRanges.toSeconds(AbsoluteRange.create(from, to))).isEqualTo(300); assertThat(TimeRanges.toSeconds(RelativeR...
@PostConstruct public void start() { List<SourceQuery> sourceQueries = sourceQuerySupplier.get(); log.info("Total Queries: %s", sourceQueries.size()); sourceQueries = applyOverrides(sourceQueries); sourceQueries = applyWhitelist(sourceQueries); sourceQueries = applyBlackl...
@Test public void testVerifierError() { VerificationManager manager = getVerificationManager(ImmutableList.of(SOURCE_QUERY), new MockPrestoAction(new RuntimeException()), VERIFIER_CONFIG); manager.start(); List<VerifierQueryEvent> events = eventClient.getEvents(); assertEquals(e...
@Override public PrimitiveIterator.OfInt iterator() { return new SingleIntIterator(); }
@Test public void testIterator() throws Exception { IntSet sis = new SingletonIntSet(3); PrimitiveIterator.OfInt iterator = sis.iterator(); assertEquals(3, iterator.nextInt()); assertFalse(iterator.hasNext()); }
@Override public int hashCode() { int result = 1; result = 31 * result + Objects.hashCode(username); result = 31 * result + Objects.hashCode(getPasswordValue()); result = 31 * result + Objects.hashCode(getSocketAddress().get()); result = 31 * result + Boolean.hashCode(getNonProxyHostsValue()); result = 31 ...
@Test void equalProxyProviders() { assertThat(createProxy(ADDRESS_1, PASSWORD_1)).isEqualTo(createProxy(ADDRESS_1, PASSWORD_1)); assertThat(createProxy(ADDRESS_1, PASSWORD_1).hashCode()).isEqualTo(createProxy(ADDRESS_1, PASSWORD_1).hashCode()); }
@Override public PluginDescriptor find(Path pluginPath) { Plugin plugin = yamlPluginFinder.find(pluginPath); return convert(plugin); }
@Test void find() throws JSONException { PluginDescriptor pluginDescriptor = yamlPluginDescriptorFinder.find(testFile.toPath()); String actual = JsonUtils.objectToJson(pluginDescriptor); JSONAssert.assertEquals(""" { "pluginId": "fake-plugin", ...
public static DateTime convertToDateTime(@Nonnull Object value) { if (value instanceof DateTime) { return (DateTime) value; } if (value instanceof Date) { return new DateTime(value, DateTimeZone.UTC); } else if (value instanceof ZonedDateTime) { final...
@Test @SuppressForbidden("Comparing twice with default timezone is okay in tests") void convertFromLocalDateTime() { final LocalDateTime input = LocalDateTime.of(2021, Month.AUGUST, 19, 12, 0); final DateTime output = DateTimeConverter.convertToDateTime(input); // both input and output...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testReadFieldsNestedPojo() { String[] readFields = {"pojo1.int2; string1; pojo1.string1"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, null, null, readFields, nestedPojoType, intType...
String addPath(String path) { // Make sure the paths always start and end with a slash. // This simplifies later comparison with the request path. if (!path.startsWith("/")) { path = "/" + path; } if (!path.endsWith("/")) { path = path + "/"; } ...
@Test public void test_addPath() { ResourceCacheControl resourceCacheControl = new ResourceCacheControl(); Assert.assertEquals("/a/b/", resourceCacheControl.addPath("a/b")); Assert.assertEquals("/a/b/", resourceCacheControl.addPath("/a/b")); Assert.assertEquals("/a/b/", resourceCach...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { String authorization = StringUtils.defaultString(exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION), exchange.getRequest().getURI(...
@Test public void testDoExecute() { ruleData.setHandle("{\"authorization\":\"test:test123\"}"); basicAuthPluginDataHandler.handlerRule(ruleData); when(this.chain.execute(any())).thenReturn(Mono.empty()); StepVerifier.create(basicAuthPlugin.doExecute(exchange, chain, selectorData, ru...
public OpenConfigConfigOfAssignmentHandler addAllocation(BigDecimal allocation) { modelObject.allocation(allocation); return this; }
@Test public void testAddAllocation() { // test Handler OpenConfigConfigOfAssignmentHandler config = new OpenConfigConfigOfAssignmentHandler(parent); // call addAllocation config.addAllocation(BigDecimal.valueOf(4)); // expected ModelObject DefaultConfig modelObject...
@Override public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) { if (scmExtension.canHandlePlugin(pluginDescriptor.id())) { scmMetadataStore.removeMetadata(pluginDescriptor.id()); } }
@Test public void shouldRemoveMetadataOnPluginUnLoadedCallback() throws Exception { SCMMetadataStore.getInstance().addMetadataFor(pluginDescriptor.id(), new SCMConfigurations(), createSCMView(null, null)); when(scmExtension.canHandlePlugin(pluginDescriptor.id())).thenReturn(true); metadataL...
public static CopyFilter getCopyFilter(Configuration conf) { String filtersClassName = conf .get(DistCpConstants.CONF_LABEL_FILTERS_CLASS); if (filtersClassName != null) { try { Class<? extends CopyFilter> filtersClass = conf .getClassByName(filtersClassName) ...
@Test public void testGetCopyFilterEmptyString() throws Exception { final String filterName = ""; Configuration configuration = new Configuration(false); configuration.set(DistCpConstants.CONF_LABEL_FILTERS_CLASS, filterName); intercept(RuntimeException.class, DistCpConstants.CLASS_INSTANTIATI...
public static void main(String[] args) { demonstrateTreasureChestIteratorForType(RING); demonstrateTreasureChestIteratorForType(POTION); demonstrateTreasureChestIteratorForType(WEAPON); demonstrateTreasureChestIteratorForType(ANY); demonstrateBstIterator(); }
@Test void shouldExecuteApplicationWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public static Object eval(String expression, Map<String, Object> context) { return eval(expression, context, ListUtil.empty()); }
@Test public void evalTest(){ final Dict dict = Dict.create() .set("a", 100.3) .set("b", 45) .set("c", -199.100); final Object eval = ExpressionUtil.eval("a-(b-c)", dict); assertEquals(-143.8, (double)eval, 0); }
@Override protected InputStream decorate(final InputStream in, final MessageDigest digest) throws IOException { if(null == digest) { log.warn("MD5 calculation disabled"); return super.decorate(in, null); } else { return new DigestInputStream(in, digest); ...
@Test public void testDecorate() throws Exception { final NullInputStream n = new NullInputStream(1L); assertSame(NullInputStream.class, new SwiftSmallObjectUploadFeature(session, new SwiftWriteFeature( session, new SwiftRegionService(session))).decorate(n, null).getClass()); }
public void removeMembership(String groupMembershipUuid) { try (DbSession dbSession = dbClient.openSession(false)) { UserGroupDto userGroupDto = findMembershipOrThrow(groupMembershipUuid, dbSession); removeMembership(userGroupDto.getGroupUuid(), userGroupDto.getUserUuid()); } }
@Test public void removeMemberByMembershipUuid_ifFound_shouldRemoveMemberFromGroup() { mockAdminInGroup(GROUP_A, USER_1); GroupDto groupDto = mockGroupDto(); UserDto userDto = mockUserDto(); UserGroupDto userGroupDto = new UserGroupDto().setUuid(UUID).setUserUuid(USER_1).setGroupUuid(GROUP_A); wh...
public void delete(DbSession dbSession, GroupDto group) { checkGroupIsNotDefault(dbSession, group); checkNotTryingToDeleteLastAdminGroup(dbSession, group); removeGroupPermissions(dbSession, group); removeGroupFromPermissionTemplates(dbSession, group); removeGroupMembers(dbSession, group); remov...
@Test public void delete_whenLastAdminGroup_throwAndDontDeleteGroup() { GroupDto groupDto = mockGroupDto(); when(dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS)) .thenReturn(Optional.of(new GroupDto().setUuid("another_group_uuid"))); // We must pass the default group check when(dbC...
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception { return newGetter(object, parent, modifier, field.getType(), field::get, (t, et) -> new FieldGetter(parent, field, modifier, t, et)); }
@Test public void newFieldGetter_whenExtractingFromNonEmpty_Collection_AndReducerSuffixInNotEmpty_thenInferTypeFromCollectionItem() throws Exception { OuterObject object = new OuterObject("name", new InnerObject("inner")); Getter getter = GetterFactory.newFieldGetter(object, null, inners...
public static Integer parsePort(Configuration flinkConfig, ConfigOption<String> port) { checkNotNull(flinkConfig.get(port), port.key() + " should not be null."); try { return Integer.parseInt(flinkConfig.get(port)); } catch (NumberFormatException ex) { throw new FlinkRun...
@Test void testParsePortNull() { final Configuration cfg = new Configuration(); ConfigOption<String> testingPort = ConfigOptions.key("test.port").stringType().noDefaultValue(); assertThatThrownBy( () -> KubernetesUtils.parsePort(cfg, testingPort), ...
@Override public Num calculate(BarSeries series, Position position) { if (position.isClosed()) { Num profit = excludeCosts ? position.getGrossProfit() : position.getProfit(); return profit.isPositive() ? profit : series.zero(); } return series.zero(); }
@Test public void calculateOnlyWithProfitPositions() { MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, series), Trade.sellAt(2, series), Trade.buyAt(3, series), Trade.sellAt(5, seri...
@Override public boolean isValid(final int timeout) throws SQLException { return databaseConnectionManager.isValid(timeout); }
@Test void assertIsInvalid() throws SQLException { try (ShardingSphereConnection connection = new ShardingSphereConnection(DefaultDatabase.LOGIC_NAME, mockContextManager())) { connection.getDatabaseConnectionManager().getConnections(DefaultDatabase.LOGIC_NAME, "ds", 0, 1, ConnectionMode.MEMORY_S...
@Override public String getString(String path) { return fileConfig.getString(path); }
@Test void getString() { SimpleFileConfig config = new SimpleFileConfig(); Assertions.assertEquals(File.pathSeparator, config.getString("path.separator")); config = new SimpleFileConfig(new File("file.conf"), ""); Assertions.assertEquals("default", config.getString("service....
@Udf(description = "Returns a new string encoded using the outputEncoding ") public String encode( @UdfParameter( description = "The source string. If null, then function returns null.") final String str, @UdfParameter( description = "The input encoding." + " If null, the...
@Test public void shouldEncodeHexToAscii() { assertThat(udf.encode("4578616d706C6521", "hex", "ascii"), is("Example!")); assertThat(udf.encode("506C616E74207472656573", "hex", "ascii"), is("Plant trees")); assertThat(udf.encode("31202b2031203d2031", "hex", "ascii"), is("1 + 1 = 1")); assertThat(udf.en...
@Override public int addListener(ObjectListener listener) { if (listener instanceof ScoredSortedSetAddListener) { return addListener("__keyevent@*:zadd", (ScoredSortedSetAddListener) listener, ScoredSortedSetAddListener::onAdd); } if (listener instanceof ScoredSortedSetRemoveList...
@Test public void testAddListener() { testWithParams(redisson -> { RScoredSortedSet<Integer> ss = redisson.getScoredSortedSet("test"); AtomicInteger latch = new AtomicInteger(); int id = ss.addListener(new ScoredSortedSetAddListener() { @Override ...
@Override public Collection<SQLToken> generateSQLTokens(final InsertStatementContext insertStatementContext) { Collection<SQLToken> result = new LinkedList<>(); EncryptTable encryptTable = encryptRule.getEncryptTable(insertStatementContext.getSqlStatement().getTable().getTableName().getIdentifier()....
@Test void assertGenerateSQLTokensExistColumns() { EncryptInsertDerivedColumnsTokenGenerator tokenGenerator = new EncryptInsertDerivedColumnsTokenGenerator(mockEncryptRule()); Collection<SQLToken> actual = tokenGenerator.generateSQLTokens(mockInsertStatementContext()); assertThat(actual.size...
public TenantCapacity getTenantCapacity(String tenant) { return tenantCapacityPersistService.getTenantCapacity(tenant); }
@Test void testGetTenantCapacity() { TenantCapacity tenantCapacity = new TenantCapacity(); tenantCapacity.setId(1L); tenantCapacity.setTenant("testTenant"); when(tenantCapacityPersistService.getTenantCapacity(eq("testTenant"))).thenReturn(tenantCapacity); TenantCapac...
@Override public Collection<JobManagerRunner> getJobManagerRunners() { return new ArrayList<>(this.jobManagerRunners.values()); }
@Test void testGetJobManagerRunners() { assertThat(testInstance.getJobManagerRunners()).isEmpty(); final JobManagerRunner jobManagerRunner0 = TestingJobManagerRunner.newBuilder().build(); final JobManagerRunner jobManagerRunner1 = TestingJobManagerRunner.newBuilder().build(); testIn...
@Override public Path copy(final Path source, final Path copy, final TransferStatus status, final ConnectionCallback callback, final StreamListener listener) throws BackgroundException { try { final String target = new DefaultUrlProvider(session.getHost()).toUrl(copy).find(DescriptiveUrl.Type.pr...
@Test public void testCopyDirectory() throws Exception { final Path directory = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); final String name = new AlphanumericRandomStringService().random(); final P...
@Override public TimestampedKeyValueStore<K, V> build() { KeyValueStore<Bytes, byte[]> store = storeSupplier.get(); if (!(store instanceof TimestampedBytesStore)) { if (store.persistent()) { store = new KeyValueToTimestampedKeyValueByteStoreAdapter(store); } e...
@Test public void shouldNotWrapTimestampedByteStore() { setUp(); when(supplier.get()).thenReturn(new RocksDBTimestampedStore("name", "metrics-scope")); final TimestampedKeyValueStore<String, String> store = builder .withLoggingDisabled() .withCachingDisabled() ...
@SuppressWarnings("unchecked") public static <W extends BoundedWindow> StateContext<W> nullContext() { return (StateContext<W>) NULL_CONTEXT; }
@Test public void nullContextThrowsOnOptions() { StateContext<BoundedWindow> context = StateContexts.nullContext(); thrown.expect(IllegalArgumentException.class); context.getPipelineOptions(); }
@Override public void onStartup() { config = RuleLoaderConfig.load(); List<String> masks = List.of(MASK_PORTAL_TOKEN); ModuleRegistry.registerModule(RuleLoaderConfig.CONFIG_NAME, RuleLoaderStartupHook.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(RuleLoaderConfig...
@Test @Ignore public void testRuleLoader() { RuleLoaderStartupHook ruleLoaderStartupHook = new RuleLoaderStartupHook(); ruleLoaderStartupHook.onStartup(); }
AwsCredentials credentialsEcs() { String response = createRestClient(ecsIamRoleEndpoint, awsConfig).get().getBody(); return parseCredentials(response); }
@Test public void credentialsEcs() { // given String response = """ { "Code": "Success", "AccessKeyId": "Access1234", "SecretAccessKey": "Secret1234", "Token": "Token1234", "Expiration": "2020-0...
@Override protected void processRecord(RowData row) { // limit the materialized table if (materializedTable.size() - validRowPosition >= maxRowCount) { cleanUp(); } materializedTable.add(row); }
@Test void testLimitedSnapshot() throws Exception { final ResolvedSchema schema = ResolvedSchema.physical( new String[] {"f0", "f1"}, new DataType[] {DataTypes.STRING(), DataTypes.INT()}); @SuppressWarnings({"unchecked", "rawtypes"}) ...
@Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } if (!super.equals(object)) { return false; } UpdateEntityResponse<?> that = (UpdateEntityResponse<?...
@Test(dataProvider = "testEqualsDataProvider") public void testEquals ( boolean shouldEquals, @Nonnull UpdateEntityResponse<TestRecordTemplateClass.Foo> updateEntityResponse, @Nullable Object compareObject ) { assertEquals(updateEntityResponse.equals(compareObject), sho...
@Override public void onCycleComplete(com.netflix.hollow.api.producer.Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { boolean isCycleSuccess; long cycleEndTimeNano = System.nanoTime(); if (status.getType() == com.netflix.hollow.api.producer.Status.Status...
@Test public void testCycleCompleteWithSuccess() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void cycleMetricsReporting(CycleMetrics cycleMetrics) { Assert.assertNotNull(cycleMetrics); Assert.ass...
@Override public void close() { userTransactionService.shutdown(true); }
@Test void assertClose() { transactionManagerProvider.close(); verify(userTransactionService).shutdown(true); }
static byte[] generateRandomPayload(Integer recordSize, List<byte[]> payloadByteList, byte[] payload, SplittableRandom random, boolean payloadMonotonic, long recordValue) { if (!payloadByteList.isEmpty()) { payload = payloadByteList.get(random.nextInt(payloadByteList.size())); } ...
@Test public void testGenerateRandomPayloadException() { Integer recordSize = null; byte[] payload = null; List<byte[]> payloadByteList = new ArrayList<>(); SplittableRandom random = new SplittableRandom(0); IllegalArgumentException thrown = assertThrows(IllegalArgumentExcep...
static String joinAndEscapeStrings(final String[] strs, final char delimiterChar, final char escapeChar) { int len = strs.length; // Escape each string in string array. for (int index = 0; index < len; index++) { if (strs[index] == null) { return null; } strs[index] = escapeS...
@Test void testJoinAndEscapeStrings() throws Exception { assertEquals("*!cluster!*!b**o***!xer!oozie**", TimelineReaderUtils.joinAndEscapeStrings( new String[]{"!cluster", "!b*o*!xer", "oozie*"}, '!', '*')); assertEquals("*!cluster!*!b**o***!xer!!", TimelineReaderUtils.joinAndEscap...
@Override public void close() { pos = 0; buffer = null; }
@Test public void testClose() { out.close(); assertEquals(0, out.position()); assertNull(out.buffer); }
@Override public ObjectNode encode(LispTeAddress address, CodecContext context) { checkNotNull(address, "LispTeAddress cannot be null"); final ObjectNode result = context.mapper().createObjectNode(); final ArrayNode jsonRecords = result.putArray(TE_RECORDS); final JsonCodec<LispTeA...
@Test public void testLispTeAddressEncode() { LispTeAddress address = new LispTeAddress.Builder() .withTeRecords(ImmutableList.of(record1, record2)) .build(); ObjectNode addressJson = teAddressCodec.encode(address, context); assertThat("errors in encoding Tr...
@Override public void start() throws Exception { LOG.info("Process starting."); mRunning = true; mJournalSystem.start(); startMasterComponents(false); mServices.forEach(SimpleService::start); // Perform the initial catchup before joining leader election, // to avoid potential delay if thi...
@Test public void startStopStandbyStandbyServer() throws Exception { Configuration.set(PropertyKey.STANDBY_MASTER_GRPC_ENABLED, true); AlluxioMasterProcess master = new AlluxioMasterProcess(new NoopJournalSystem(), new AlwaysStandbyPrimarySelector()); master.registerService( RpcServerServi...
public static <T> T[] getBeans(Class<T> interfaceClass) { Object object = serviceMap.get(interfaceClass.getName()); if(object == null) return null; if(object instanceof Object[]) { return (T[])object; } else { Object array = Array.newInstance(interfaceClass, 1); ...
@Test public void testArrayNotDefined() { Dummy[] dummies = SingletonServiceFactory.getBeans(Dummy.class); Assert.assertNull(dummies); }
public boolean isRoot() { return mUri.getPath().equals(SEPARATOR) || (mUri.getPath().isEmpty() && hasAuthority()); }
@Test public void isRootTests() { assertFalse(new AlluxioURI(".").isRoot()); assertTrue(new AlluxioURI("/").isRoot()); assertTrue(new AlluxioURI("file:/").isRoot()); assertTrue(new AlluxioURI("alluxio://localhost:19998").isRoot()); assertTrue(new AlluxioURI("alluxio://localhost:19998/").isRoot());...
public void createQprofileChangesForRuleUpdates(DbSession dbSession, Set<PluginRuleUpdate> pluginRuleUpdates) { List<QProfileChangeDto> changesToPersist = pluginRuleUpdates.stream() .flatMap(pluginRuleUpdate -> { RuleChangeDto ruleChangeDto = createNewRuleChange(pluginRuleUpdate); insertRuleCh...
@Test public void updateWithoutCommit_whenOneRuleBelongingToTwoQualityProfilesChanged_thenInsertOneRuleChangeAndTwoQualityProfileChanges() { List<ActiveRuleDto> activeRuleDtos = List.of( new ActiveRuleDto().setProfileUuid("profileUuid1").setRuleUuid(RULE_UUID), new ActiveRuleDto().setProfileUuid("prof...
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("type", type) .add("uuid", uuid) .add("component", component) .add("entity", entity) .add("submitter", submitter) .toString(); }
@Test public void verify_toString() { CeTask.Component component = new CeTask.Component("COMPONENT_UUID_1", "COMPONENT_KEY_1", "The component"); CeTask.Component entity = new CeTask.Component("ENTITY_UUID_1", "ENTITY_KEY_1", "The entity"); underTest.setType("TYPE_1"); underTest.setUuid("UUID_1"); ...
public static Map<String, Collection<DataNode>> load(final String databaseName, final DatabaseType protocolType, final Map<String, DataSource> dataSourceMap, final Collection<ShardingSphereRule> builtRules, final Collection<String> configuredTables) { Col...
@Test void assertLoad() { ShardingSphereRule builtRule = mock(ShardingSphereRule.class); TableMapperRuleAttribute ruleAttribute = mock(TableMapperRuleAttribute.class, RETURNS_DEEP_STUBS); when(ruleAttribute.getDistributedTableNames()).thenReturn(Arrays.asList("salary", "employee", "student")...
@Override public LogLevel getLogLevel() { return log != null ? log.getLogLevel() : null; }
@Test public void testBaseStepGetLogLevelWontThrowNPEWithNullLog() { when( mockHelper.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenAnswer( (Answer<LogChannelInterface>) invocation -> { ( (BaseStep) invocation.getArguments()[ 0 ] ).getLogLevel(); retur...
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testMergeStringMapOverwrite() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'tomergemap': {'type': 'STRING_MAP', 'value': {'tomerge': 'hello', 'all': 'allval'}}}"); Map<String, ParamDefinition> paramsToMerge = parseP...
@Override protected License open(final Local file) { // Verify immediately and exit if not a valid receipt final ReceiptVerifier verifier = new ReceiptVerifier(file); if(verifier.verify(new DisabledLicenseVerifierCallback())) { // Set name final Receipt receipt = new ...
@Test public void testOpen() throws Exception { // Expect exit code 173 new ReceiptFactory().open(); }
public static long validateMillisecondInstant(final Instant instant, final String messagePrefix) { try { if (instant == null) { throw new IllegalArgumentException(messagePrefix + VALIDATE_MILLISECOND_NULL_SUFFIX); } return instant.toEpochMilli(); } ca...
@Test public void shouldReturnMillisecondsOnValidInstant() { final Instant sampleInstant = Instant.now(); assertEquals(sampleInstant.toEpochMilli(), validateMillisecondInstant(sampleInstant, "sampleInstant")); }
@Bean("ReadCache") public ReadCache provideReader(AnalysisCacheEnabled analysisCacheEnabled, AnalysisCacheMemoryStorage storage) { if (analysisCacheEnabled.isEnabled()) { storage.load(); return new ReadCacheImpl(storage); } return new NoOpReadCache(); }
@Test public void provide_noop_reader_cache_when_disable() { when(analysisCacheEnabled.isEnabled()).thenReturn(false); var cache = cacheProvider.provideReader(analysisCacheEnabled, storage); assertThat(cache).isInstanceOf(NoOpReadCache.class); }
@Override public long getBackoffTime() { return backoffTimeMS; }
@Test void testBackoffTime() { final long backoffTimeMS = 10_000L; final FailureRateRestartBackoffTimeStrategy restartStrategy = new FailureRateRestartBackoffTimeStrategy(new ManualClock(), 1, 1, backoffTimeMS); assertThat(restartStrategy.getBackoffTime()).isEqualTo(backoff...
@Override public Optional<Lock> unlock(@Nonnull String resource, @Nullable String lockContext) { return doUnlock(resource, getLockedByString(lockContext)); }
@Test void unlockNonExistentLock() { assertThat(lockService.unlock("test-resource", null)).isEmpty(); }
public void setNeedClientAuth(Boolean needClientAuth) { this.needClientAuth = needClientAuth; }
@Test public void testSetNeedClientAuth() throws Exception { configuration.setNeedClientAuth(true); configuration.configure(configurable); assertTrue(configurable.isNeedClientAuth()); }
@Override public void exportData(JsonWriter writer) throws IOException { throw new UnsupportedOperationException("Can not export 1.0 format from this version."); }
@Test(expected = UnsupportedOperationException.class) public void testExportDisabled() throws IOException { JsonWriter writer = new JsonWriter(new StringWriter()); dataService.exportData(writer); }
public static void mergeParams( Map<String, ParamDefinition> params, Map<String, ParamDefinition> paramsToMerge, MergeContext context) { if (paramsToMerge == null) { return; } Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream()) .forEach( name ...
@Test public void testAllowedTypeCastingIntoLong() throws JsonProcessingException { Map<String, ParamDefinition> allParams = ParamsMergeHelperTest.this.parseParamDefMap( "{'tomerge': {'type': 'LONG','value': 123, 'name': 'tomerge'}}"); Map<String, ParamDefinition> paramsToMerge = P...
@Override public RemotingCommand processRequest(final ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { return this.processRequest(ctx.channel(), request, true); }
@Test public void testSingleAck_TopicCheck() throws RemotingCommandException { AckMessageRequestHeader requestHeader = new AckMessageRequestHeader(); requestHeader.setTopic("wrongTopic"); requestHeader.setQueueId(0); requestHeader.setOffset(0L); RemotingCommand request = Remo...
public @CheckForNull String readLink() throws IOException { return null; }
@Test public void testReadLink_AbstractBase() throws Exception { // This test checks the method's behavior in the abstract base class, // which generally does nothing. VirtualFile root = new VirtualFileMinimalImplementation(); assertThat(root.readLink(), nullValue()); }
@Override public void connectTables(DeviceId deviceId, int fromTable, int toTable) { TrafficSelector.Builder selector = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder(); treatment.transition(toTable); FlowRule flowRule = Defau...
@Test public void testConnectTables() { int testFromTable = 1; int testToTable = 2; fros = Sets.newConcurrentHashSet(); TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder(); TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();...
public static Optional<String> getRowUniqueKey(final String rowPath) { Pattern pattern = Pattern.compile(getShardingSphereDataNodePath() + "/([\\w\\-]+)/schemas/([\\w\\-]+)/tables" + "/([\\w\\-]+)" + "/(\\w+)$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(rowPath); return matche...
@Test void assertGetRowUniqueKeyHappyPath() { assertThat(ShardingSphereDataNode.getRowUniqueKey("/statistics/databases/db_name/schemas/db_schema/tables/tbl_name/key"), is(Optional.of("key"))); }
@UdafFactory(description = "Build a value-to-count histogram of input Strings") public static TableUdaf<String, Map<String, Long>, Map<String, Long>> histogramString() { return histogram(); }
@Test public void shouldNotExceedSizeLimit() { final TableUdaf<String, Map<String, Long>, Map<String, Long>> udaf = HistogramUdaf.histogramString(); Map<String, Long> agg = udaf.initialize(); for (int thisValue = 1; thisValue < 2500; thisValue++) { agg = udaf.aggregate(String.valueOf(thisValue), agg...
@Nonnull @Override public List<DataConnectionResource> listResources() { try { try (Connection connection = getConnection()) { DatabaseMetaData databaseMetaData = connection.getMetaData(); ResourceReader reader = new ResourceReader(); switch (...
@Test public void list_resources_should_return_table() throws Exception { jdbcDataConnection = new JdbcDataConnection(SHARED_DATA_CONNECTION_CONFIG); executeJdbc(JDBC_URL_SHARED, "CREATE TABLE MY_TABLE (ID INT, NAME VARCHAR)"); List<DataConnectionResource> dataConnectionResources = jdbcDat...
@Override public void begin() throws TransactionException { begin(DEFAULT_GLOBAL_TX_TIMEOUT); }
@Test public void rollBackNoXIDExceptionTest() throws TransactionException { RootContext.unbind(); GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate(); tx.begin(); Assertions.assertThrows(TransactionException.class, tx::rollback); }
T call() throws IOException, RegistryException { String apiRouteBase = "https://" + registryEndpointRequestProperties.getServerUrl() + "/v2/"; URL initialRequestUrl = registryEndpointProvider.getApiRoute(apiRouteBase); return call(initialRequestUrl); }
@Test public void testCall_logNullExceptionMessage() throws IOException, RegistryException { setUpRegistryResponse(new IOException()); try { endpointCaller.call(); Assert.fail(); } catch (IOException ex) { Mockito.verify(mockEventHandlers) .dispatch( LogEvent.er...
public static <T> RemoteIterator<T> remoteIteratorFromSingleton( @Nullable T singleton) { return new SingletonIterator<>(singleton); }
@Test public void testSingletonNotClosed() throws Throwable { CloseCounter closeCounter = new CloseCounter(); RemoteIterator<CloseCounter> it = remoteIteratorFromSingleton(closeCounter); verifyInvoked(it, 1, this::log); close(it); closeCounter.assertCloseCount(0); }
@GetMapping(value = "/json/{appId}/{clusterName}/{namespace:.+}") public ResponseEntity<String> queryConfigAsJson(@PathVariable String appId, @PathVariable String clusterName, @PathVariable String namespace, ...
@Test public void testQueryConfigAsJson() throws Exception { String someKey = "someKey"; String someValue = "someValue"; Type responseType = new TypeToken<Map<String, String>>(){}.getType(); String someWatchKey = "someWatchKey"; Set<String> watchKeys = Sets.newHashSet(someWatchKey); Map<Str...
private RemotingCommand updateAndCreateSubscriptionGroup(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException { long startTime = System.currentTimeMillis(); final RemotingCommand response = RemotingCommand.createResponseCommand(null); LOGGER.info("AdminBro...
@Test public void testUpdateAndCreateSubscriptionGroup() throws RemotingCommandException { RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_SUBSCRIPTIONGROUP, null); SubscriptionGroupConfig subscriptionGroupConfig = new SubscriptionGroupConfig(); s...
@SqlNullable @Description("Returns the Point value that is the mathematical centroid of a Spherical Geography") @ScalarFunction("ST_Centroid") @SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) public static Slice stSphericalCentroid(@SqlType(SPHERICAL_GEOGRAPHY_TYPE_NAME) Slice input) { OGCGeometry ge...
@Test public void testSTSphericalCentroid() { // Spherical centroid testing assertSphericalCentroid("POINT (3 5)", new Point(3, 5)); assertSphericalCentroid("POINT EMPTY", null); assertSphericalCentroid("MULTIPOINT EMPTY", null); assertSphericalCentroid("MULTIPOINT (3 5)"...
public static String checkComponentKey(String key) { checkArgument(!isNullOrEmpty(key), "Component key can't be empty"); checkArgument(key.length() <= MAX_COMPONENT_KEY_LENGTH, "Component key length (%s) is longer than the maximum authorized (%s). '%s' was provided.", key.length(), MAX_COMPONENT_KEY_LENGT...
@Test void check_key() { String key = repeat("a", 400); assertThat(ComponentValidator.checkComponentKey(key)).isEqualTo(key); }
@JsonIgnore public boolean isInlineWorkflow() { return initiator.getType().isInline(); }
@Test public void testRoundTripSerde() throws Exception { for (String fileName : Arrays.asList( "sample-workflow-instance-created.json", "sample-workflow-instance-succeeded.json")) { WorkflowInstance expected = loadObject("fixtures/instances/" + fileName, WorkflowInstance.class...
@Override public void start() { boolean hasExternalPlugins = pluginRepository.getPlugins().stream().anyMatch(plugin -> plugin.getType().equals(PluginType.EXTERNAL)); try (DbSession session = dbClient.openSession(false)) { PropertyDto property = Optional.ofNullable(dbClient.propertiesDao().selectGlobalPr...
@Test public void do_nothing_when_there_is_no_external_plugin() { setupExternalPluginConsent(NOT_ACCEPTED); setupBundledPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(NOT_ACCEPTED....
public static String getGroupName(final String serviceNameWithGroup) { if (StringUtils.isBlank(serviceNameWithGroup)) { return StringUtils.EMPTY; } if (!serviceNameWithGroup.contains(Constants.SERVICE_INFO_SPLITER)) { return Constants.DEFAULT_GROUP; } retu...
@Test void testGetGroupName() { String validServiceName = "group@@serviceName"; assertEquals("group", NamingUtils.getGroupName(validServiceName)); }
protected void setMethod() { boolean activateBody = RestMeta.isActiveBody( wMethod.getText() ); boolean activateParams = RestMeta.isActiveParameters( wMethod.getText() ); wlBody.setEnabled( activateBody ); wBody.setEnabled( activateBody ); wApplicationType.setEnabled( activateBody ); wlParamet...
@Test public void testSetMethod_PATCH() { doReturn( RestMeta.HTTP_METHOD_PATCH ).when( method ).getText(); dialog.setMethod(); verify( bodyl, times( 1 ) ).setEnabled( true ); verify( body, times( 1 ) ).setEnabled( true ); verify( type, times( 1 ) ).setEnabled( true ); verify( paramsl, times...
@Override public int acquiredPermits() { return get(acquiredPermitsAsync()); }
@Test public void testAcquiredPermits() throws InterruptedException { RPermitExpirableSemaphore semaphore = redisson.getPermitExpirableSemaphore("test-semaphore"); assertThat(semaphore.trySetPermits(2)).isTrue(); Assertions.assertEquals(0, semaphore.acquiredPermits()); String acquire...
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException { final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class); ...
@Test void parseArtifactResolveSessionExpired() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException { ArtifactResolveRequest artifactResolveRequest = getArtifactResolveRequest("success", true,false, SAML_COMBICONNECT, EncryptionType.BSN, ENTRANCE_ENTI...
public Set<? extends AuthenticationRequest> getRequest(final Host bookmark, final LoginCallback prompt) throws LoginCanceledException { final StringBuilder url = new StringBuilder(); url.append(bookmark.getProtocol().getScheme().toString()).append("://"); url.append(bookmark.getHostn...
@Test public void testGetDefault2EmptyTenant() throws Exception { final SwiftAuthenticationService s = new SwiftAuthenticationService(); final SwiftProtocol protocol = new SwiftProtocol() { @Override public String getContext() { return "/v2.0/tokens"; ...
@ConstantFunction(name = "add", argTypes = {INT, INT}, returnType = INT, isMonotonic = true) public static ConstantOperator addInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createInt(Math.addExact(first.getInt(), second.getInt())); }
@Test public void addInt() { assertEquals(20, ScalarOperatorFunctions.addInt(O_INT_10, O_INT_10).getInt()); }
public CreateTableBuilder withPkConstraintName(String pkConstraintName) { this.pkConstraintName = validateConstraintName(pkConstraintName); return this; }
@Test public void withPkConstraintName_throws_IAE_if_name_is_not_lowercase() { assertThatThrownBy(() -> underTest.withPkConstraintName("Too")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Constraint name must be lower case and contain only alphanumeric chars or '_', got 'Too'")...
public static String prepareUrl(@NonNull String url) { url = url.trim(); String lowerCaseUrl = url.toLowerCase(Locale.ROOT); // protocol names are case insensitive if (lowerCaseUrl.startsWith("feed://")) { Log.d(TAG, "Replacing feed:// with http://"); return prepareUrl(ur...
@Test public void testProtocolRelativeUrlIsAbsolute() { final String in = "https://example.com"; final String inBase = "http://examplebase.com"; final String out = UrlChecker.prepareUrl(in, inBase); assertEquals(in, out); }
@Override public ExportResult<CalendarContainerResource> export( UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) { if (!exportInformation.isPresent()) { return exportCalendars(authData, Optional.empty()); } else { StringPaginationToken paginationToke...
@Test public void exportCalendarSubsequentSet() throws IOException { setUpSingleCalendarResponse(); // Looking at subsequent page, with no page after it PaginationData paginationData = new StringPaginationToken(CALENDAR_TOKEN_PREFIX + NEXT_TOKEN); ExportInformation exportInformation = new ExportInfor...
@Override public ConfiguredDataSourceProvenance getProvenance() { return provenance; }
@Test public void loadTest() throws URISyntaxException { URI dataFile = JsonDataSourceTest.class.getResource("/org/tribuo/json/test.json").toURI(); RowProcessor<MockOutput> rowProcessor = buildRowProcessor(); JsonDataSource<MockOutput> source = new JsonDataSource<>(dataFile, rowProcessor, ...
public Properties getProperties() { return properties; }
@Test public void testHibernateProperties() { assertNull(Configuration.INSTANCE.getProperties().getProperty("hibernate.types.nothing")); assertEquals("def", Configuration.INSTANCE.getProperties().getProperty("hibernate.types.abc")); }
public static boolean checkParenthesis(String str) { boolean result = true; if (str != null) { int open = 0; int closed = 0; int i = 0; while ((i = str.indexOf('(', i)) >= 0) { i++; open++; } i = 0; ...
@Test public void testCheckParenthesis() throws Exception { String str = "fred:(((ddd))"; assertFalse(URISupport.checkParenthesis(str)); str += ")"; assertTrue(URISupport.checkParenthesis(str)); }
@Override protected Range get(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Object pgObject = rs.getObject(position); if (pgObject == null) { return null; } String type = ReflectionUtils.invokeGetter(pgObject, ...
@Test public void test() { Restriction ageRestrictionInt = doInJPA(entityManager -> { entityManager.persist(new Restriction()); Restriction restriction = new Restriction(); restriction.setRangeInt(int4Range); restriction.setRangeIntEmpty(int4RangeEmpty); ...
@Override public CompletableFuture<T> toCompletableFuture() { return _task.toCompletionStage().toCompletableFuture(); }
@Test public void testCreateStageFromRunnable_withExecutor() throws Exception { final String[] stringArr = new String[1]; String testResult = "testCreateStageFromCompletableFuture"; ParSeqBasedCompletionStage<Void> stageFromCompletionStage = _parSeqBasedCompletionStageFactory.buildStageFromRunna...
@SuppressWarnings({"deprecation", "checkstyle:linelength"}) public void convertSiteProperties(Configuration conf, Configuration yarnSiteConfig, boolean drfUsed, boolean enableAsyncScheduler, boolean userPercentage, FSConfigToCSConfigConverterParams.PreemptionMode preemptionMode) { yarnSiteConfig...
@SuppressWarnings("deprecation") @Test public void testSiteContinuousSchedulingConversion() { yarnConfig.setBoolean( FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_ENABLED, true); yarnConfig.setInt( FairSchedulerConfiguration.CONTINUOUS_SCHEDULING_SLEEP_MS, 666); converter.convertSite...
@Override public ValidationTaskResult validateImpl(Map<String, String> optionMap) { // Skip this test if NOSASL if (mConf.get(PropertyKey.SECURITY_AUTHENTICATION_TYPE) .equals(AuthType.NOSASL)) { return new ValidationTaskResult(ValidationUtils.State.SKIPPED, getName(), String.f...
@Test public void proxyUserNotWildcard() { String userName = System.getProperty("user.name"); // Configured proxy users and groups, but not wildcard String proxyUserKey = String.format("hadoop.proxyuser.%s.users", userName); String proxyGroupKey = String.format("hadoop.proxyuser.%s.groups", userName)...