focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public String process(final Expression expression) { return formatExpression(expression); }
@Test public void shouldGenerateCorrectCodeForTimestampStringGEQ() { // Given: final ComparisonExpression compExp = new ComparisonExpression( Type.GREATER_THAN_OR_EQUAL, new StringLiteral("2020-01-01T00:00:00"), TIMESTAMPCOL ); // When: final String java = sqlToJavaVisitor...
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { final Map<Path, List<Long>> regular = new HashMap<>(); final Map<Path, List<Long>> trashed = new HashMap<>(); for(Path file : files.keySet(...
@Test public void testDeleteFolderRoomWithContent() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.dire...
private void addPublisherIndexes(Service service, String clientId) { publisherIndexes.computeIfAbsent(service, key -> new ConcurrentHashSet<>()).add(clientId); NotifyCenter.publishEvent(new ServiceEvent.ServiceChangedEvent(service, true)); }
@Test void testAddPublisherIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String clientId = "clientId"; Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class; Method addPublisherIndexes = clientSer...
public static String likeToRegexpLike(String likePattern) { int start = 0; int end = likePattern.length(); String prefix = "^"; String suffix = "$"; switch (likePattern.length()) { case 0: return "^$"; case 1: if (likePattern.charAt(0) == '%') { return ""; ...
@Test public void testLeadingRepeatedWildcards() { String regexpLikePattern = RegexpPatternConverterUtils.likeToRegexpLike("%%%%%%%%%%%%%zz"); assertEquals(regexpLikePattern, "zz$"); }
public static String getClassPath() { return getClassPath(false); }
@Test public void getClassPathTest() { String classPath = ClassUtil.getClassPath(); assertNotNull(classPath); }
@GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response getAlarm(@PathParam("id") String id) { log.debug("HTTP GET alarm for id={}", id); AlarmId alarmId = AlarmId.alarmId(id); Alarm alarm = get(AlarmService.class).getAlarm(alarmId); ObjectNode result = new...
@Test @Ignore public void getAlarm() { WebTarget wt = target(); String response = wt.path("/alarms/1").request().get(String.class); // Ensure hard-coded alarms returned okay assertThat(response, containsString("\"NE is not reachable\",")); assertThat(response, not(contain...
public static InetSocketAddress createSocketAddr(String target) { return createSocketAddr(target, -1); }
@Test public void testCreateSocketAddress() throws Throwable { InetSocketAddress addr = NetUtils.createSocketAddr( "127.0.0.1:12345", 1000, "myconfig"); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(12345, addr.getPort()); addr = NetUtils.createSocketAddr( ...
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldNotThrowOnRowKeyKeyColumn() { // Given: final CreateStream statement = new CreateStream( SOME_NAME, TableElements.of(tableElement("k", new Type(SqlTypes.STRING), KEY_CONSTRAINT)), false, true, withProperties, false ); // When: ...
@Override public void reset() { super.reset(); this.minDeltaInCurrentBlock = Integer.MAX_VALUE; }
@Test public void shouldReset() throws IOException { shouldReadWriteWhenDataIsNotAlignedWithBlock(); int[] data = new int[5 * blockSize]; for (int i = 0; i < blockSize * 5; i++) { data[i] = i * 2; } writer.reset(); shouldWriteAndRead(data); }
private void executeByCondition(String brokerName, String queueId, long offset, long timeValueBegin, long timeValueEnd) { MessageQueue mq = new MessageQueue(topic, brokerName, Integer.parseInt(queueId)); try { long minOffset = defaultMQPullConsumer.minOffset(mq); long maxOffset =...
@Test public void testExecuteByCondition() throws SubCommandException { PrintStream out = System.out; ByteArrayOutputStream bos = new ByteArrayOutputStream(); System.setOut(new PrintStream(bos)); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] s...
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldRequestServerInfo() { // Given: ServerInfo expectedResponse = new ServerInfo("someversion", "kafkaclusterid", "ksqlserviceid", "status"); server.setResponseObject(expectedResponse); // When: KsqlTarget target = ksqlClient.target(serverUri); RestResponse<Server...
public static Criterion matchTcpDst(TpPort tcpPort) { return new TcpPortCriterion(tcpPort, Type.TCP_DST); }
@Test public void testMatchTcpDstMethod() { Criterion matchTcpDst = Criteria.matchTcpDst(tpPort1); TcpPortCriterion tcpPortCriterion = checkAndConvert(matchTcpDst, Criterion.Type.TCP_DST, TcpPortCriterion.class); ...
@Override public void check(Collection<? extends T> collection, ConditionEvents events) { ViolatedAndSatisfiedConditionEvents subEvents = new ViolatedAndSatisfiedConditionEvents(); for (T element : collection) { condition.check(element, subEvents); } if (!subEvents.getAll...
@Test public void satisfied_works_and_description_contains_mismatches() { ConditionEvents events = ConditionEvents.Factory.create(); containAnyElementThat(IS_SERIALIZABLE).check(TWO_NONSERIALIZABLE_OBJECTS, events); assertThat(events).containViolations(messageForTwoTimes(isSerializableMessag...
public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime.get() + interval) { token.set(rate); lastResetTime.set(now); } return token.decrementAndGet() >= 0; }
@Test void testAccuracy() throws Exception { final int EXPECTED_RATE = 5; statItem = new StatItem("test", EXPECTED_RATE, 60_000L); for (int i = 1; i <= EXPECTED_RATE; i++) { assertTrue(statItem.isAllowable()); } // Must block the 6th item assertFalse(stat...
@CheckForNull public FileData fileData(String moduleKeyWithBranch, String path) { SingleProjectRepository repository = repositoriesPerModule.get(moduleKeyWithBranch); return repository == null ? null : repository.fileData(path); }
@Test public void test_file_data_when_module_does_not_exist() { FileData fileData = repository.fileData("unknown", "/Def.java"); assertThat(fileData).isNull(); }
public static Entry entry(String name) throws BlockException { return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0); }
@Test public void testStringEntryAll() throws BlockException { final String arg0 = "foo"; final String arg1 = "baz"; Entry e = SphU.entry("resourceName", EntryType.IN, 2, arg0, arg1); assertSame(e.resourceWrapper.getEntryType(), EntryType.IN); e.exit(2, arg0, arg1); }
@Override public void init() { if(log.isDebugEnabled()) { log.debug("Initialize responder by browsing DNSSD"); } super.init(); try { for(String protocol : this.getServiceTypes()) { if(log.isInfoEnabled()) { log.info(String.f...
@Test public void testInit() throws Exception { final Rendezvous r = new RendezvousResponder(); final CountDownLatch wait = new CountDownLatch(1); final AssertionError[] failure = new AssertionError[1]; r.addListener(new RendezvousListener() { @Override public...
@Override protected boolean isStepCompleted(@NonNull Context context) { return false; // this step is never done! You can always configure more :) }
@Test public void testIsStepCompletedAlwaysFalse() { Assert.assertFalse( startFragment().isStepCompleted(ApplicationProvider.getApplicationContext())); }
public boolean isBetween(ConnectPoint src, ConnectPoint dst) { return (this.src.equals(src) && this.dst.equals(dst)); }
@Test public void testIsBetween() { ConnectPoint cp1 = new ConnectPoint(DeviceId.deviceId("of:0000000000000001"), PortNumber.portNumber(1L)); ConnectPoint cp2 = new ConnectPoint(DeviceId.deviceId("of:0000000000000002"), PortNumber.portNumber(2L)); ConnectPoint cp3 = new ConnectPoint(DeviceId...
@Override public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK); Mode mode =...
@Test public void resetContextFromZkUriToNonZkUri() throws Exception { org.apache.hadoop.conf.Configuration conf = getConf(); URI uri = URI.create(Constants.HEADER + "zk@zkHost:2181/tmp/path.txt"); FileSystem fs = getHadoopFilesystem(org.apache.hadoop.fs.FileSystem.get(uri, conf)); assertTrue(fs.mFile...
public static ScalarOperator compoundAnd(Collection<ScalarOperator> nodes) { return createCompound(CompoundPredicateOperator.CompoundType.AND, nodes); }
@Test public void compoundAnd3() { ScalarOperator tree1 = Utils.compoundAnd(ConstantOperator.createInt(1), ConstantOperator.createInt(2), ConstantOperator.createInt(3), ConstantOperator.createInt(4), ConstantOperator.createInt(5), ...
@Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { return super.touch(file, status.withChecksum(write.checksum(file, status).compute(new NullInputStream(0L), status))); }
@Test public void testTouchCarriageReturnKey() throws Exception { final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory)); final Path test = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch( new Path(...
public NamedRuleItemNodePath getNamedItem(final String itemType) { return namedItems.get(itemType); }
@Test void assertGetNamedItem() { NamedRuleItemNodePath namedRulePath = ruleNodePath.getNamedItem("tables"); assertThat(namedRulePath.getPath("foo_table"), is("tables/foo_table")); Optional<String> path = namedRulePath.getName("/metadata/foo_db/rules/foo/tables/foo_table/versions/0"); ...
@Activate public void activate() { deviceToPipeconf = storageService.<DeviceId, PiPipeconfId>consistentMapBuilder() .withName("onos-pipeconf-table") .withSerializer(Serializer.using(KryoNamespaces.API)) .build(); deviceToPipeconf.addListener(mapListene...
@Test public void activate() { assertNotNull(store.storageService); assertTrue("Store must have delegate", store.hasDelegate()); assertTrue("No value should be in the map", store.deviceToPipeconf.isEmpty()); assertTrue("No value should be in the map", store.pipeconfToDevices.isEmpty(...
@Override public List<SubscriptionPath> listSubscriptions(ProjectPath project, TopicPath topic) throws IOException { Subscriptions.List request = pubsub.projects().subscriptions().list(project.getPath()); ListSubscriptionsResponse response = request.execute(); if (response.getSubscriptions() == null...
@Test public void listSubscriptions() throws Exception { ListSubscriptionsResponse expectedResponse1 = new ListSubscriptionsResponse(); expectedResponse1.setSubscriptions(Collections.singletonList(buildSubscription(1))); expectedResponse1.setNextPageToken("AVgJH3Z7aHxiDBs"); ListSubscriptionsResponse...
public static List<TriStateSelection> forAgentsResources(Set<ResourceConfig> resourceConfigs, Agents agents) { return convert(resourceConfigs, agents, new Assigner<>() { @Override public boolean shouldAssociate(Agent agent, ResourceConfig resourceConfig) { return agent.ge...
@Test public void shouldHaveActionRemoveIfNoAgentsHaveResource() { resourceConfigs.add(new ResourceConfig("none")); agents.add(new Agent("uuid1", "host1", "127.0.0.1", List.of("one"))); agents.add(new Agent("uuid2", "host2", "127.0.0.2", List.of("two"))); List<TriStateSelection> sel...
public static String toOperationDesc(Operation op) { Class<? extends Operation> operationClass = op.getClass(); if (PartitionIteratingOperation.class.isAssignableFrom(operationClass)) { PartitionIteratingOperation partitionIteratingOperation = (PartitionIteratingOperation) op; Op...
@Test public void testNormalOperation() { assertEquals(DummyOperation.class.getName(), toOperationDesc(new DummyOperation())); }
void shutdown(final boolean clean) { shutdownStateUpdater(); shutdownSchedulingTaskManager(); final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); // TODO: change type to `StreamTask` final Set<Task> activeTasks = new TreeSet<>(Comparator.compar...
@Test public void shouldShutDownStateUpdaterAndCloseFailedTasksDirty() { final TasksRegistry tasks = mock(TasksRegistry.class); final StreamTask failedStatefulTask = statefulTask(taskId01, taskId01ChangelogPartitions) .inState(State.RESTORING).build(); final StandbyTask failedSta...
@Nullable static String channelKind(@Nullable Destination destination) { if (destination == null) return null; return isQueue(destination) ? "queue" : "topic"; }
@Test void channelKind_queueAndTopic_topicOnNoQueueName() throws JMSException { QueueAndTopic destination = mock(QueueAndTopic.class); when(destination.getTopicName()).thenReturn("topic-foo"); assertThat(MessageParser.channelKind(destination)) .isEqualTo("topic"); }
public CompletableFuture<NotifyClientTerminationResponse> notifyClientTermination(ProxyContext ctx, NotifyClientTerminationRequest request) { CompletableFuture<NotifyClientTerminationResponse> future = new CompletableFuture<>(); try { String clientId = ctx.getClientID(); ...
@Test public void testProducerNotifyClientTermination() throws Throwable { ProxyContext context = createContext(); when(this.grpcClientSettingsManager.removeAndGetClientSettings(any())).thenReturn(Settings.newBuilder() .setClientType(ClientType.PRODUCER) .setPublishing(Publi...
@Override @Nonnull public List<Sdk> selectSdks(Configuration configuration, UsesSdk usesSdk) { Config config = configuration.get(Config.class); Set<Sdk> sdks = new TreeSet<>(configuredSdks(config, usesSdk)); if (enabledSdks != null) { sdks = Sets.intersection(sdks, enabledSdks); } return L...
@Test public void withAllSdksConfig_shouldUseFullSdkRangeFromAndroidManifest() throws Exception { when(usesSdk.getTargetSdkVersion()).thenReturn(22); when(usesSdk.getMinSdkVersion()).thenReturn(19); when(usesSdk.getMaxSdkVersion()).thenReturn(23); assertThat( sdkPicker.selectSdks( ...
@Override public double cdf(double k) { if (k < 0) { return 0.0; } else if (k == 0) { return q; } else { return 1.0; } }
@Test public void testCdf() { System.out.println("cdf"); BernoulliDistribution instance = new BernoulliDistribution(0.3); instance.rand(); assertEquals(0.7, instance.cdf(0), 1E-7); assertEquals(1.0, instance.cdf(1), 1E-7); }
@Override public void writeLong(final long v) throws IOException { ensureAvailable(LONG_SIZE_IN_BYTES); Bits.writeLong(buffer, pos, v, isBigEndian); pos += LONG_SIZE_IN_BYTES; }
@Test public void testWriteLongForPositionV() throws Exception { long expected = 100; out.writeLong(2, expected); long actual = Bits.readLongB(out.buffer, 2); assertEquals(expected, actual); }
public static Map<TopicPartition, Long> parseSinkConnectorOffsets(Map<Map<String, ?>, Map<String, ?>> partitionOffsets) { Map<TopicPartition, Long> parsedOffsetMap = new HashMap<>(); for (Map.Entry<Map<String, ?>, Map<String, ?>> partitionOffset : partitionOffsets.entrySet()) { Map<String, ...
@Test public void testValidateAndParseStringPartitionValue() { Map<Map<String, ?>, Map<String, ?>> partitionOffsets = createPartitionOffsetMap("topic", "10", "100"); Map<TopicPartition, Long> parsedOffsets = SinkUtils.parseSinkConnectorOffsets(partitionOffsets); assertEquals(1, parsedOffsets...
@Override public Object merge(T mergingValue, T existingValue) { if (mergingValue == null) { return existingValue.getRawValue(); } return mergingValue.getRawValue(); }
@Test public void merge_mergingNotNull() { MapMergeTypes existing = mergingValueWithGivenValue(EXISTING); MapMergeTypes merging = mergingValueWithGivenValue(MERGING); assertEquals(MERGING, mergePolicy.merge(merging, existing)); }
public static <T> List<T> batchTransform(final Class<T> clazz, List<?> srcList) { if (CollectionUtils.isEmpty(srcList)) { return Collections.emptyList(); } List<T> result = new ArrayList<>(srcList.size()); for (Object srcObject : srcList) { result.add(transform(clazz, srcObject)); } ...
@Test public void testBatchTransformListNotEmpty() { someList.add(77); assertNotNull(BeanUtils.batchTransform(String.class, someList)); }
@Override public Object getBody() throws Exception { MultipartFile target = super.getFile(DEFAULT_FILE_NAME); if (Objects.nonNull(target)) { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); parts.add(DEFAULT_FILE_NAME, target.getResource()); retu...
@Test void testGetBodyWithoutFile() throws Exception { Object body = reuseUploadFileHttpServletRequest.getBody(); assertEquals(HttpUtils.encodingParams(HttpUtils.translateParameterMap(new HashMap<>()), StandardCharsets.UTF_8.name()), body); }
@Override public int read() throws EOFException { return (pos < size) ? (data[pos++] & 0xff) : -1; }
@Test public void testReadForBOffLen() throws Exception { int read = in.read(INIT_DATA, 0, 5); assertEquals(5, read); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testUnpartitionedDays() throws Exception { createUnpartitionedTable(spark, tableName); SparkScanBuilder builder = scanBuilder(); DaysFunction.TimestampToDaysFunction function = new DaysFunction.TimestampToDaysFunction(); UserDefinedScalarFunc udf = toUDF(function, expressio...
@Override public int selectChannel(SerializationDelegate<StreamRecord<T>> record) { return random.nextInt(numberOfChannels); }
@Test void testSelectChannelsInterval() { assertSelectedChannelWithSetup(0, 1); streamPartitioner.setup(2); assertThat(streamPartitioner.selectChannel(serializationDelegate)) .isGreaterThanOrEqualTo(0) .isLessThan(2); streamPartitioner.setup(1024); ...
boolean isUseNodeNameAsExternalAddress() { return useNodeNameAsExternalAddress; }
@Test public void kubernetesApiNodeNameAsExternalAddress() { // given Map<String, Comparable> properties = createProperties(); properties.put(KubernetesProperties.USE_NODE_NAME_AS_EXTERNAL_ADDRESS.key(), true); // when KubernetesConfig config = new KubernetesConfig(propertie...
@Override protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selectorData, final RuleData rule) { SignRuleHandler ruleHandler = SignPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule)); if (ObjectUtils.isE...
@Test public void testSignPluginSimple2() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("localhost").build()); when(signService.signatureVerify(exchange)).thenReturn(VerifyResult.fail("")); RuleData data = mock(RuleData.class); SelectorData selectorData = mo...
@Override public boolean shouldSample() { long now = nanoClock.nanoTimeNow(); long period = now / periodLengthInNanos; synchronized (this) { if (period != currentSamplingPeriod) { currentSamplingPeriod = period; samplesInCurrentPeriod = 1; ...
@Test void first_sample_in_period_returns_true() { var clock = MockUtils.mockedClockReturning(1000L); var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L); assertTrue(sampler.shouldSample()); }
public static <OutputT> PTransform<PCollection<Row>, PCollection<OutputT>> fromRows( Class<OutputT> clazz) { return to(clazz); }
@Test @Category(NeedsRunner.class) public void testFromRows() { PCollection<POJO1> pojos = pipeline .apply(Create.of(EXPECTED_ROW1).withRowSchema(EXPECTED_SCHEMA1)) .apply(Convert.fromRows(POJO1.class)); PAssert.that(pojos).containsInAnyOrder(new POJO1()); pipeline.run();...
@VisibleForTesting public static UClassIdent create(String qualifiedName) { List<String> topLevelPath = new ArrayList<>(); for (String component : Splitter.on('.').split(qualifiedName)) { topLevelPath.add(component); if (Character.isUpperCase(component.charAt(0))) { break; } } ...
@Test public void serialization() { SerializableTester.reserializeAndAssert(UClassIdent.create("java.math.BigInteger")); }
private void addRunningOne(WorkflowInstance.Status status, WorkflowRollupOverview overview) { if (runningStats == null) { runningStats = new EnumMap<>(WorkflowInstance.Status.class); } runningStats.put(status, runningStats.getOrDefault(status, 0L) + 1); if (runningRollup == null) { runningR...
@Test public void testAddRunningOne() throws Exception { ForeachStepOverview overview = loadObject( "fixtures/instances/sample-foreach-step-overview.json", ForeachStepOverview.class); WorkflowRollupOverview.CountReference ref = new WorkflowRollupOverview.CountReference(); ref.setCnt(1)...
@Override public void bootup() { startComponents(); }
@Test public void bootup_starts_components_lazily_unless_they_are_annotated_with_EagerStart() { DefaultStartable defaultStartable = new DefaultStartable(); EagerStartable eagerStartable = new EagerStartable(); TaskContainerImpl ceContainer = new TaskContainerImpl(parent, container -> { container.add...
public void setExcludedProtocols(String protocols) { this.excludedProtocols = protocols; }
@Test public void testSetExcludedProtocols() throws Exception { configurable.setSupportedProtocols(new String[] { "A", "B" }); configuration.setExcludedProtocols("A"); configuration.configure(configurable); assertTrue(Arrays.equals(new String[] { "B" }, configurable.getEnabledProtocols())); ...
@Override public E intern(E sample) { E canonical = map.get(sample); if (canonical != null) { return canonical; } var value = map.putIfAbsent(sample, sample); return (value == null) ? sample : value; }
@Test public void intern_weak_replace() { var canonical = new Int(1); var other = new Int(1); Interner<Int> interner = Interner.newWeakInterner(); assertThat(interner.intern(canonical)).isSameInstanceAs(canonical); var signal = new WeakReference<>(canonical); canonical = null; GcFinaliz...
public void sendMessage(M message, MessageHeaders headers) { this.sendMessage(responseTopic, message, headers); }
@Test public void testMessagePostProcessingHeaders() throws JMSException { AfnemersberichtAanDGL afnemersberichtAanDGL = new AfnemersberichtAanDGL(); Map<String, Object> headers = new HashMap<>(); headers.put("header1", "header1 value"); headers.put("header2", "header2 value"); ...
public static Locale getLocale(String param) { int pointIndex = param.indexOf('.'); if (pointIndex > 0) param = param.substring(0, pointIndex); param = param.replace("-", "_"); int index = param.indexOf("_"); if (index < 0) { return new Locale(param); ...
@Test public void testGetLocale() { assertEquals(Locale.GERMAN, Helper.getLocale("de")); assertEquals(Locale.GERMANY, Helper.getLocale("de_DE")); assertEquals(Locale.GERMANY, Helper.getLocale("de-DE")); assertEquals(Locale.ENGLISH, Helper.getLocale("en")); assertEquals(Locale...
public Duration durationBetweenRecurringJobInstances() { Instant base = Instant.EPOCH.plusSeconds(3600); Schedule schedule = ScheduleExpressionType.getSchedule(scheduleExpression); Instant run1 = schedule.next(base, base, ZoneOffset.UTC); Instant run2 = schedule.next(base, run1, ZoneOffs...
@Test void testDurationBetweenRecurringJobInstancesForCronJob() { RecurringJob recurringJob1 = aDefaultRecurringJob().withCronExpression("* * * * * *").build(); assertThat(recurringJob1.durationBetweenRecurringJobInstances()).isEqualTo(ofSeconds(1)); RecurringJob recurringJob2 = aDefaultRec...
public static void main(String[] args) throws IOException { runSqlLine(args, null, System.out, System.err); }
@Test public void testSqlLine_emptyArgs() throws Exception { BeamSqlLine.main(new String[] {}); }
public boolean checkStateUpdater(final long now, final java.util.function.Consumer<Set<TopicPartition>> offsetResetter) { addTasksToStateUpdater(); if (stateUpdater.hasExceptionsAndFailedTasks()) { handleExceptionsFromStateUpdater(); } if ...
@Test public void shouldRethrowStreamsExceptionFromStateUpdater() { final StreamTask statefulTask = statefulTask(taskId00, taskId00ChangelogPartitions) .inState(State.RESTORING) .withInputPartitions(taskId00Partitions).build(); final StreamsException exception = new StreamsEx...
@SuppressWarnings({"unchecked"}) public static <T> T[] replace(T[] buffer, int index, T... values) { if (isEmpty(values)) { return buffer; } if (isEmpty(buffer)) { return values; } if (index < 0) { // 从头部追加 return insert(buffer, 0, values); } if (index >= buffer.length) { // 超出长度,尾部追加 r...
@Test public void replaceTest() { String[] a = {"1", "2", "3", "4"}; String[] b = {"a", "b", "c"}; // 在小于0的位置,-1位置插入,返回b+a,新数组 String[] result = ArrayUtil.replace(a, -1, b); assertArrayEquals(new String[]{"a", "b", "c", "1", "2", "3", "4"}, result); // 在第0个位置开始替换,返回a result = ArrayUtil.replace(ArrayUti...
public static void validateFineGrainedAuth(Method endpointMethod, UriInfo uriInfo, HttpHeaders httpHeaders, FineGrainedAccessControl accessControl) { if (endpointMethod.isAnnotationPresent(Authorize.class)) { final Authorize auth = endpointMethod.getAnnotation(Authorize.class); String targetId = n...
@Test public void testValidateFineGrainedAuthWithNoSuchMethodError() { FineGrainedAccessControl ac = Mockito.mock(FineGrainedAccessControl.class); Mockito.when(ac.hasAccess(Mockito.any(HttpHeaders.class), Mockito.any(), Mockito.any(), Mockito.any())) .thenThrow(new NoSuchMethodError("Method not found"...
@Override protected String getAnalyzerEnabledSettingKey() { return Settings.KEYS.ANALYZER_CPE_ENABLED; }
@Test public void testGetAnalyzerEnabledSettingKey() { CPEAnalyzer instance = new CPEAnalyzer(); String expResult = Settings.KEYS.ANALYZER_CPE_ENABLED; String result = instance.getAnalyzerEnabledSettingKey(); assertEquals(expResult, result); }
static ApiError validateQuotaKeyValue( Map<String, ConfigDef.ConfigKey> validKeys, String key, double value ) { // Ensure we have an allowed quota key ConfigDef.ConfigKey configKey = validKeys.get(key); if (configKey == null) { return new ApiError(Errors.I...
@Test public void testValidateQuotaKeyValueForUnknownQuota() { assertEquals(new ApiError(Errors.INVALID_REQUEST, "Invalid configuration key foobar"), ClientQuotaControlManager.validateQuotaKeyValue( VALID_CLIENT_ID_QUOTA_KEYS, "foobar", 1.0)); }
public static XMLInputFactory createSecureXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty( IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE ); return factory; }
@Test public void secureXmlInputStream() { XMLInputFactory factory = XMLParserFactoryProducer.createSecureXMLInputFactory(); assertEquals( false, factory.getProperty( IS_SUPPORTING_EXTERNAL_ENTITIES ) ); }
@Override public Flux<Subscriber> resolve(Reason reason) { var reasonType = reason.getSpec().getReasonType(); return subscriptionService.listByPerPage(reasonType) .filter(this::isNotDisabled) .filter(subscription -> { var interestReason = subscription.getSpec(...
@Test void distinct() { // same subscriber to different subscriptions var subscriber = new Subscription.Subscriber(); subscriber.setName("test"); final var subscription1 = createSubscription(subscriber); subscription1.getMetadata().setName("sub-1"); final var subscr...
@Override public GroupAssignment assign( GroupSpec groupSpec, SubscribedTopicDescriber subscribedTopicDescriber ) throws PartitionAssignorException { if (groupSpec.memberIds().isEmpty()) return new GroupAssignment(Collections.emptyMap()); if (groupSpec.subscriptionTy...
@Test public void testAssignWithNoSubscribedTopic() { SubscribedTopicDescriberImpl subscribedTopicMetadata = new SubscribedTopicDescriberImpl( Collections.singletonMap( TOPIC_1_UUID, new TopicMetadata( TOPIC_1_UUID, TOPIC_1_...
public static URI parse(String featureIdentifier) { requireNonNull(featureIdentifier, "featureIdentifier may not be null"); if (featureIdentifier.isEmpty()) { throw new IllegalArgumentException("featureIdentifier may not be empty"); } // Legacy from the Cucumber Eclipse plug...
@Test void can_parse_root_package() { URI uri = FeaturePath.parse("classpath:/"); assertAll( () -> assertThat(uri.getScheme(), is("classpath")), () -> assertThat(uri.getSchemeSpecificPart(), is("/"))); }
public Preference<String> getString(@StringRes int prefKey, @StringRes int defaultValue) { return getString(mResources.getString(prefKey), defaultValue); }
@Test public void testConvertQuickKey() { SharedPrefsHelper.setPrefsValue( "settings_key_ordered_active_quick_text_keys", "623e21f5-9200-4c0b-b4c7-9691129d7f1f,1057806d-4f6e-42aa-8dfd-eea57995c2ee"); SharedPrefsHelper.setPrefsValue(RxSharedPrefs.CONFIGURATION_VERSION, 10); SharedPreferenc...
public static String fromBytes(byte[] bytes) throws IOException { DataInputBuffer dbuf = new DataInputBuffer(); dbuf.reset(bytes, 0, bytes.length); StringBuilder buf = new StringBuilder(bytes.length); readChars(dbuf, buf, bytes.length); return buf.toString(); }
@Test public void testInvalidUTF8Truncated() throws Exception { // Truncated CAT FACE character -- this is a 4-byte sequence, but we // only have the first three bytes. byte[] truncated = new byte[] { (byte)0xF0, (byte)0x9F, (byte)0x90 }; try { UTF8.fromBytes(truncated); fail("did ...
@Override public Collection<ShutdownAwarePlugin> getShutdownAwarePluginList() { return mainLock.applyWithReadLock(shutdownAwarePluginList::getPlugins); }
@Test public void testGetShutdownAwarePluginList() { manager.register(new TestShutdownAwarePlugin()); Assert.assertEquals(1, manager.getShutdownAwarePluginList().size()); }
@Override public ShardingSphereUser swapToObject(final YamlUserConfiguration yamlConfig) { if (null == yamlConfig) { return null; } Grantee grantee = convertYamlUserToGrantee(yamlConfig.getUser()); return new ShardingSphereUser(grantee.getUsername(), yamlConfig.getPasswor...
@Test void assertSwapToObject() { YamlUserConfiguration user = new YamlUserConfiguration(); user.setUser("foo_user@127.0.0.1"); user.setPassword("foo_pwd"); ShardingSphereUser actual = new YamlUserSwapper().swapToObject(user); assertNotNull(actual); assertThat(actual....
@VisibleForTesting static int checkJar(Path file) throws Exception { final URI uri = file.toUri(); int numSevereIssues = 0; try (final FileSystem fileSystem = FileSystems.newFileSystem( new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment...
@Test void testRejectedOnMissingNoticeFile(@TempDir Path tempDir) throws Exception { assertThat( JarFileChecker.checkJar( createJar( tempDir, Entry.fileEntry( ...
public abstract ResourceMethod getResourceMethod();
@Test(dataProvider = "envelopeResourceMethodDataProvider") public void testEnvelopeResourceMethodType(RestLiResponseEnvelope responseEnvelope, ResourceMethod resourceMethod) { Assert.assertEquals(responseEnvelope.getResourceMethod(), resourceMethod); }
public Schema find(String name, String namespace) { Schema.Type type = PRIMITIVES.get(name); if (type != null) { return Schema.create(type); } String fullName = fullName(name, namespace); Schema schema = getNamedSchema(fullName); if (schema == null) { schema = getNamedSchema(name); ...
@Test public void validateSchemaRetrievalBySimpleName() { assertSame(fooRecord, fooBarBaz.find(fooRecord.getName(), fooRecord.getNamespace())); }
@Override boolean isCacheable() { return false; }
@Test public void test_isCacheable() { boolean cacheable = NullGetter.NULL_GETTER.isCacheable(); assertFalse(cacheable); }
public static TimestampExtractionPolicy create( final KsqlConfig ksqlConfig, final LogicalSchema schema, final Optional<TimestampColumn> timestampColumn ) { if (!timestampColumn.isPresent()) { return new MetadataTimestampExtractionPolicy(getDefaultTimestampExtractor(ksqlConfig)); } ...
@Test public void shouldFailIfCantFindTimestampField() { // When: assertThrows( KsqlException.class, () -> TimestampExtractionPolicyFactory .create( ksqlConfig, schemaBuilder2.build(), Optional.of( new TimestampCol...
public boolean removeShardById(final int shardId) { if (shardMap.containsKey(shardId)) { shardMap.remove(shardId); return true; } else { return false; } }
@Test void testRemoveShardById() { try { var shard = new Shard(1); shardManager.addNewShard(shard); boolean flag = shardManager.removeShardById(1); var field = ShardManager.class.getDeclaredField("shardMap"); field.setAccessible(true); var map = (Map<Integer, Shard>) field.get(...
@Override public Object decode(Response response, Type type) throws IOException, DecodeException { if (response.status() == 404 || response.status() == 204) if (JSONObject.class.isAssignableFrom((Class<?>) type)) return new JSONObject(); else if (JSONArray.class.isAssignableFrom((Class<?>) typ...
@Test void decodesExtendedArray() throws IOException { String json = "[{\"a\":\"b\",\"c\":1},123]"; Response response = Response.builder() .status(200) .reason("OK") .headers(Collections.emptyMap()) .body(json, UTF_8) .request(request) .build(); assertThat(j...
public void write(CruiseConfig configForEdit, OutputStream output, boolean skipPreprocessingAndValidation) throws Exception { LOGGER.debug("[Serializing Config] Starting to write. Validation skipped? {}", skipPreprocessingAndValidation); MagicalGoConfigXmlLoader loader = new MagicalGoConfigXmlLoader(con...
@Test public void shouldNotThrowUpWhenTfsWorkspaceIsNotSpecified() { CruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("tfs_pipeline"); cruiseConfig.initializeServer(); PipelineConfig tfs_pipeline = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("tfs_pipeline")); ...
@Override public Collection<IExternalResourceInfo> getResourcesFromRow( Rest step, RowMetaInterface rowMeta, Object[] row ) { Set<IExternalResourceInfo> resources = new HashSet<>(); RestMeta meta = (RestMeta) step.getStepMetaInterface(); if ( meta == null ) { meta = (RestMeta) step.getStepMeta().ge...
@Test public void testGetResourcesFromRow_fieldsForMethodAndBody() throws Exception { when( meta.isUrlInField() ).thenReturn( true ); when( meta.getUrlField() ).thenReturn( "url" ); when( meta.getHeaderField() ).thenReturn( null ); when( meta.getParameterField() ).thenReturn( null ); when( meta.is...
public FEELFnResult<Range> invoke(@ParameterName("from") String from) { if (from == null || from.isEmpty() || from.isBlank()) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "from", "cannot be null")); } Range.RangeBoundary startBoundary; if...
@Test void invokeNull() { List<String> from = Arrays.asList(null, " ", "", "[..]"); from.forEach(it -> FunctionTestUtil.assertResultError(rangeFunction.invoke(it), InvalidParametersEvent.class, it)); }
public SegmentCommitter createSegmentCommitter(SegmentCompletionProtocol.Request.Params params, String controllerVipUrl) throws URISyntaxException { boolean uploadToFs = _streamConfig.isServerUploadToDeepStore(); String peerSegmentDownloadScheme = _tableConfig.getValidationConfig().getPeerSegmentDow...
@Test(description = "use upload to deepstore when either serverUploadToDeepStore is set or peer segment download " + "scheme is non-null") public void testUploadToDeepStoreConfig() throws URISyntaxException { ServerSegmentCompletionProtocolHandler protocolHandler = new ServerSegmentCompletionP...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QueryEntry that = (QueryEntry) o; if (!key.equals(that.key)) { return false; } ...
@Test public void test_equality_differentKey() { QueryableEntry queryEntry = createEntry("dataKey", "dataValue"); QueryableEntry queryEntryOther = createEntry("dataKeyOther", "dataValue"); assertFalse(queryEntry.equals(queryEntryOther)); }
@Override public void removeKey(DeviceKeyId deviceKeyId) { checkNotNull(deviceKeyId, "Device key identifier cannot be null"); store.deleteDeviceKey(deviceKeyId); }
@Test public void testRemoveKey() { DeviceKeyId deviceKeyId = DeviceKeyId.deviceKeyId(deviceKeyIdValue); DeviceKey deviceKey = DeviceKey.createDeviceKeyUsingCommunityName(deviceKeyId, deviceKeyLabel, deviceKeySnmpName); ...
public void start() { if (isStarted()) return; int errorCount = 0; if (port <= 0) { errorCount++; addError("No port was configured for appender" + name + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_port"); } if (remoteHost == null)...
@Test public void shutsDownOnInterruptWhileWaitingForSocketConnection() throws Exception { // given doThrow(new InterruptedException()).when(socketConnector).call(); // when appender.start(); // then verify(socketConnector, timeout(TIMEOUT)).call(); }
@ScalarFunction public static String splitPart(String input, String delimiter, int index) { String[] splitString = StringUtils.splitByWholeSeparator(input, delimiter); if (index >= 0 && index < splitString.length) { return splitString[index]; } else if (index < 0 && index >= -splitString.length) { ...
@Test(dataProvider = "splitPartTestCases") public void testSplitPart(String input, String delimiter, int index, int limit, String expectedToken, String expectedTokenWithLimitCounts) { assertEquals(StringFunctions.splitPart(input, delimiter, index), expectedToken); assertEquals(StringFunctions.splitPart(...
@Override public void addCorsMappings(final CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("Access-Control-Allow-Origin", "*", "Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE", ...
@Test public void testAddCorsMappings() { CorsRegistry registry = new CorsRegistry(); WebConfiguration webConfiguration = new WebConfiguration(); webConfiguration.addCorsMappings(registry); assertEquals(getCorsConfigurationsString(registry), getCorsConfigurationsString(corsRegistryJS...
public ProtocolBuilder status(String status) { this.status = status; return getThis(); }
@Test void status() { ProtocolBuilder builder = new ProtocolBuilder(); builder.status("mockstatuschecker"); Assertions.assertEquals("mockstatuschecker", builder.build().getStatus()); }
@Override public NewAnalysisError onFile(InputFile inputFile) { checkArgument(inputFile != null, "Cannot use a inputFile that is null"); checkState(this.inputFile == null, "onFile() already called"); this.inputFile = inputFile; return this; }
@Test public void test_save() { DefaultAnalysisError analysisError = new DefaultAnalysisError(storage); analysisError.onFile(inputFile).save(); Mockito.verify(storage).store(analysisError); Mockito.verifyNoMoreInteractions(storage); }
Writer getWriter( Object source ) throws KettleException { try { Writer outputStreamWriter = writers.get( source ); if ( outputStreamWriter != null ) { return outputStreamWriter; } FileObject file = getReplayFilename( destinationDirectory, processingFilename, dateString, file...
@Test public void getWriterEmptyEncoding() throws Exception { Object source = Mockito.mock( Object.class ); setupErrorHandler( "", source ); OutputStreamWriter outputStreamWriter = (OutputStreamWriter) abstractFileErrorHandler.getWriter( source ); assertEquals( DEFAULT_ENCODING, outputStreamWriter.get...
@Override public double get(int index) { return elements[index]; }
@Test public void serialization431Test() throws URISyntaxException, IOException { Path vectorPath = Paths.get(DenseVectorTest.class.getResource("dense-vector-431.tribuo").toURI()); try (InputStream fis = Files.newInputStream(vectorPath)) { TensorProto proto = TensorProto.parseFrom(fis); ...
@Override public void run() { try { interceptorChain.doInterceptor(task); } catch (Exception e) { Loggers.SRV_LOG.info("Interceptor health check task {} failed", task.getTaskId(), e); } }
@Test void testRunHealthyInstanceWithTimeoutFromMetadata() throws InterruptedException { InstancePublishInfo instance = injectInstance(true, System.currentTimeMillis()); Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME); InstanceMetadata metadata = new InstanceMetadat...
public List<Stream> match(Message message) { final Set<Stream> result = Sets.newHashSet(); final Set<String> blackList = Sets.newHashSet(); for (final Rule rule : rulesList) { if (blackList.contains(rule.getStreamId())) { continue; } final St...
@Test public void testInvertedContainsMatch() throws Exception { final StreamMock stream = getStreamMock("test"); final StreamRuleMock rule = new StreamRuleMock( ImmutableMap.<String, Object>builder() .put("_id", new ObjectId()) .put("f...
public void processRow(GenericRow decodedRow, Result reusedResult) throws Exception { reusedResult.reset(); if (_complexTypeTransformer != null) { // TODO: consolidate complex type transformer into composite type transformer decodedRow = _complexTypeTransformer.transform(decodedRow); } ...
@Test public void testSingleRowFailure() throws Exception { TableConfig config = createTestTableConfig(); Schema schema = Fixtures.createSchema(); TransformPipeline pipeline = new TransformPipeline(config, schema); GenericRow simpleRow = Fixtures.createInvalidSingleRow(9527); boolean excepti...
@Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); }
@Test public void testIsDebugEnabled() { Logger mockLogger = mock(Logger.class); when(mockLogger.getName()).thenReturn("foo"); when(mockLogger.isDebugEnabled()).thenReturn(true); InternalLogger logger = new Slf4JLogger(mockLogger); assertTrue(logger.isDebugEnabled()); ...
public Map<V, Integer> inDegree() { Map<V, Integer> result = new HashMap<>(); for (V vertex : neighbors.keySet()) { result.put(vertex, 0); // all in-degrees are 0 } for (V from : neighbors.keySet()) { for (V to : neighbors.get(from)) { result.put(t...
@Test void inDegree() { Map<Character, Integer> result = graph.inDegree(); Map<Character, Integer> expected = new HashMap<>(7); expected.put('A', 0); expected.put('B', 1); expected.put('C', 1); expected.put('D', 0); expected.put('E', 1); expected.put('...
public Optional<Object> getLiteralValue(final int index) { ExpressionSegment valueExpression = valueExpressions.get(index); if (valueExpression instanceof ParameterMarkerExpressionSegment) { return Optional.ofNullable(parameters.get(getParameterIndex((ParameterMarkerExpressionSegment) valueE...
@Test void assertGetLiteralValueWithParameterMarker() { Collection<ExpressionSegment> assignments = makeParameterMarkerExpressionSegment(); String parameterValue = "test"; InsertValueContext insertValueContext = new InsertValueContext(assignments, Collections.singletonList(parameterValue), 0...
@Override public boolean isEmpty() { return mask == 0; }
@Test public void testIsEmpty() { assertThat(new LongBitMask(1L).isEmpty()).isFalse(); assertThat(new LongBitMask(0L).isEmpty()).isTrue(); }
public final long encodeLatLon(double lat, double lon) { return encode(x(lon), y(lat)); }
@Test public void testEdgeCases() { double minLon = -1, maxLon = 1.6; double minLat = -1, maxLat = 0.5; int parts = 4; int bits = (int) (Math.log(parts * parts) / Math.log(2)); SpatialKeyAlgo spatialKeyAlgo = new SpatialKeyAlgo(bits, new BBox(minLon, maxLon, minLat, maxLat));...
public static CommonsConfigurationCircuitBreakerConfiguration of(final Configuration configuration) throws ConfigParseException{ CommonsConfigurationCircuitBreakerConfiguration obj = new CommonsConfigurationCircuitBreakerConfiguration(); try { obj.getConfigs().putAll(obj.getProperties(config...
@Test public void testFromYamlFile() throws ConfigurationException { Configuration config = CommonsConfigurationUtil.getConfiguration(YAMLConfiguration.class, TestConstants.RESILIENCE_CONFIG_YAML_FILE_NAME); CommonsConfigurationCircuitBreakerConfiguration commonsConfigurationCircuitBreakerConfigura...
public boolean fence(HAServiceTarget fromSvc) { return fence(fromSvc, null); }
@Test public void testShortNameSshWithPort() throws BadFencingConfigurationException { NodeFencer fencer = setupFencer("sshfence(:123)"); assertFalse(fencer.fence(MOCK_TARGET)); }
@Override String getFileName(double lat, double lon) { int intKey = calcIntKey(lat, lon); String str = areas.get(intKey); if (str == null) return null; int minLat = Math.abs(down(lat)); int minLon = Math.abs(down(lon)); str += "/"; if (lat >= 0) ...
@Test public void testGetFileString() { assertEquals("Eurasia/N49E011", instance.getFileName(49, 11)); assertEquals("Eurasia/N52W002", instance.getFileName(52.268157, -1.230469)); assertEquals("Africa/S06E034", instance.getFileName(-5.965754, 34.804687)); assertEquals("Australia/S29E...
@Override public void endInput(int inputId) throws Exception { inputSelectionHandler.endInput(inputId); InputSpec inputSpec = inputSpecMap.get(inputId); inputSpec.getOutput().endOperatorInput(inputSpec.getOutputOpInputId()); }
@Test public void testProcess() throws Exception { TestingBatchMultipleInputStreamOperator op = createMultipleInputStreamOperator(); List<StreamElement> outputData = op.getOutputData(); TestingTwoInputStreamOperator joinOp2 = (TestingTwoInputStreamOperator) op.getTailWrapper...
@Override @Deprecated public <VR> KStream<K, VR> flatTransformValues(final org.apache.kafka.streams.kstream.ValueTransformerSupplier<? super V, Iterable<VR>> valueTransformerSupplier, final String... stateStoreNames) { Objects.requireNonNull(valueTransf...
@Test @SuppressWarnings("deprecation") public void shouldNotAllowNullStoreNameOnFlatTransformValuesWithFlatValueSupplierAndNamed() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.flatTransformValues( flatValueTra...
@Override @VisibleForTesting public CompletableFuture<JarUploadResponseBody> handleRequest( @Nonnull final HandlerRequest<EmptyRequestBody> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException { Collection<File> uploadedFiles = request.getUpload...
@Test void testRejectNonJarFiles() throws Exception { final Path uploadedFile = Files.createFile(jarDir.resolve("katrin.png")); final HandlerRequest<EmptyRequestBody> request = createRequest(uploadedFile); assertThatThrownBy( () -> jarUploadHandler.handleRequest(requ...