focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static AssertionResult getResult(SMIMEAssertionTestElement testElement, SampleResult response, String name) { checkForBouncycastle(); AssertionResult res = new AssertionResult(name); try { MimeMessage msg; final int msgPos = testElement.getSpecificMessagePositionAs...
@Test public void testSignerSignerDN() { SMIMEAssertionTestElement testElement = new SMIMEAssertionTestElement(); testElement.setSignerCheckConstraints(true); String signerDn = "C=AU, L=Wherever, O=Example Ltd, E=alice@a.example.com, CN=alice example"; testElement .se...
@PostMapping("") public ShenyuAdminResult createTag(@Valid @RequestBody final TagDTO tagDTO) { Integer createCount = tagService.create(tagDTO); return ShenyuAdminResult.success(ShenyuResultMessage.CREATE_SUCCESS, createCount); }
@Test public void testCreateTag() throws Exception { TagDTO tagDTO = buildTagDTO(); given(tagService.create(tagDTO)).willReturn(1); this.mockMvc.perform(MockMvcRequestBuilders.post("/tag") .contentType(MediaType.APPLICATION_JSON) .content(GsonU...
@Override public ClientDetailsEntity saveNewClient(ClientDetailsEntity client) { if (client.getId() != null) { // if it's not null, it's already been saved, this is an error throw new IllegalArgumentException("Tried to save a new client with an existing ID: " + client.getId()); } if (client.getRegisteredRedi...
@Test(expected = IllegalArgumentException.class) public void heartMode_noJwks() { Mockito.when(config.isHeartMode()).thenReturn(true); ClientDetailsEntity client = new ClientDetailsEntity(); Set<String> grantTypes = new LinkedHashSet<>(); grantTypes.add("authorization_code"); client.setGrantTypes(grantTypes...
@Override public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { throw new ReadOnlyBufferException(); }
@Test public void shouldRejectSetBytes4() { assertThrows(UnsupportedOperationException.class, new Executable() { @Override public void execute() { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ByteBuf) null, 0, 0); } }); }
@Override public void applySchemaChange(SchemaChangeEvent schemaChangeEvent) throws SchemaEvolveException { if (!isOpened) { isOpened = true; catalog.open(); } SchemaChangeEventVisitor.visit( schemaChangeEvent, addColumnEve...
@Test public void testAddColumn() throws Exception { TableId tableId = TableId.parse("test.tbl2"); Schema schema = Schema.newBuilder() .physicalColumn("col1", new IntType()) .primaryKey("col1") .build(); ...
@Override public void releaseAllResources() throws IOException { synchronized (lock) { for (ResultSubpartitionView view : allViews.values()) { view.releaseAllResources(); } allViews.clear(); for (ResultSubpartitionView view : unregisteredAvail...
@Test void testReleaseAllResources() throws IOException { assertThat(view.isReleased()).isFalse(); assertThat(view0.isReleased()).isFalse(); assertThat(view1.isReleased()).isFalse(); assertThat(buffers0).allMatch(x -> !x.isRecycled()); assertThat(buffers1).allMatch(x -> !x.is...
public static SegmentAssignmentStrategy getSegmentAssignmentStrategy(HelixManager helixManager, TableConfig tableConfig, String assignmentType, InstancePartitions instancePartitions) { String assignmentStrategy = null; TableType currentTableType = tableConfig.getTableType(); // TODO: Handle segment a...
@Test public void testBalancedNumSegmentAssignmentStrategyForRealtimeTables() { Map<String, String> streamConfigs = FakeStreamConfigUtils.getDefaultLowLevelStreamConfigs().getStreamConfigsMap(); TableConfig tableConfig = new TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME).setStream...
public static NamingSelector newIpSelector(String regex) { if (regex == null) { throw new IllegalArgumentException("The parameter 'regex' cannot be null."); } return new DefaultNamingSelector(instance -> Pattern.matches(regex, instance.getIp())); }
@Test public void testNewIpSelector() { Instance ins1 = new Instance(); ins1.setIp("172.18.137.120"); Instance ins2 = new Instance(); ins2.setIp("172.18.137.121"); Instance ins3 = new Instance(); ins3.setIp("172.18.136.111"); NamingContext namingConte...
public void updateTaskConfig(Map<String, String> taskConfig) { try { taskLifecycleLock.lock(); if (!Objects.equals(this.taskConfigReference, taskConfig)) { logger.info("Updating task '" + name + "' configuration"); taskConfigReference = taskConfig; ...
@Test public void should_not_poll_data_without_task_config() { taskRunner.updateTaskConfig(null); assertPolledRecordsSize(0); }
@SuppressWarnings("IntLongMath") public long getExpirationDelay() { for (int i = 0; i < SHIFT.length; i++) { Node<K, V>[] timerWheel = wheel[i]; long ticks = (nanos >>> SHIFT[i]); long spanMask = SPANS[i] - 1; int start = (int) (ticks & spanMask); int end = start + timerWheel.length...
@Test(dataProvider = "clock") public void getExpirationDelay_empty(long clock) { when(cache.evictEntry(any(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; assertThat(timerWheel.getExpirationDelay()).isEqualTo(Long.MAX_VALUE); }
boolean isPublicAndStatic() { int modifiers = mainMethod.getModifiers(); return isPublic(modifiers) && isStatic(modifiers); }
@Test public void testPublicAndStaticForSelf() throws NoSuchMethodException { Method method = MainMethodFinderTest.class.getDeclaredMethod("testPublicAndStaticForSelf"); MainMethodFinder mainMethodFinder = new MainMethodFinder(); mainMethodFinder.mainMethod = method; boolean publicA...
public void translate(Pipeline pipeline) { this.flinkBatchEnv = null; this.flinkStreamEnv = null; final boolean hasUnboundedOutput = PipelineTranslationModeOptimizer.hasUnboundedOutput(pipeline); if (hasUnboundedOutput) { LOG.info("Found unbounded PCollection. Switching to streaming execu...
@Test public void shouldProvideParallelismToTransformOverrides() { FlinkPipelineOptions options = getDefaultPipelineOptions(); options.setStreaming(true); options.setRunner(FlinkRunner.class); FlinkPipelineExecutionEnvironment flinkEnv = new FlinkPipelineExecutionEnvironment(options); Pipeline p =...
public WorkflowDefinition addWorkflowDefinition( WorkflowDefinition workflowDef, Properties changes) { LOG.info("Adding a new workflow definition with an id [{}]", workflowDef.getWorkflow().getId()); final Workflow workflow = workflowDef.getWorkflow(); final Metadata metadata = workflowDef.getMetadata...
@Test public void testAddWorkflowDefinitionWithOutputSignals() throws Exception { WorkflowDefinition wfd = loadWorkflow(TEST_WORKFLOW_ID7); WorkflowDefinition definition = workflowDao.addWorkflowDefinition(wfd, wfd.getPropertiesSnapshot().extractProperties()); assertEquals(wfd, definition); as...
public String getContextPath() { return contextPath; }
@Test public void sanitize_context_path_from_settings() { settings.setProperty(CONTEXT_PROPERTY, "/my_path///"); assertThat(underTest().getContextPath()).isEqualTo("/my_path"); }
public void runExtractor(Message msg) { try(final Timer.Context ignored = completeTimer.time()) { final String field; try (final Timer.Context ignored2 = conditionTimer.time()) { // We can only work on Strings. if (!(msg.getField(sourceField) instanceof St...
@Test public void testCursorStrategyCopyWithMultipleResults() throws Exception { final TestExtractor extractor = new TestExtractor.Builder() .cursorStrategy(COPY) .sourceField("msg") .callback(new Callable<Result[]>() { @Override ...
@Override public void failover(NamedNode master) { connection.sync(RedisCommands.SENTINEL_FAILOVER, master.getName()); }
@Test public void testFailover() throws InterruptedException { Collection<RedisServer> masters = connection.masters(); connection.failover(masters.iterator().next()); Thread.sleep(10000); RedisServer newMaster = connection.masters().iterator().next(); assert...
public static Ip6Prefix valueOf(byte[] address, int prefixLength) { return new Ip6Prefix(Ip6Address.valueOf(address), prefixLength); }
@Test public void testValueOfByteArrayIPv6() { Ip6Prefix ipPrefix; byte[] value; value = new byte[] {0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x77, 0x77, (byte) 0x88, (byte) 0x...
public DirectGraph getGraph() { checkState(finalized, "Can't get a graph before the Pipeline has been completely traversed"); return DirectGraph.create( producers, viewWriters, perElementConsumers, rootTransforms, stepNames); }
@Test public void getViewsReturnsViews() { PCollectionView<List<String>> listView = p.apply("listCreate", Create.of("foo", "bar")) .apply( ParDo.of( new DoFn<String, String>() { @ProcessElement public void processE...
public Future<KafkaVersionChange> reconcile() { return getVersionFromController() .compose(i -> getPods()) .compose(this::detectToAndFromVersions) .compose(i -> prepareVersionChange()); }
@Test public void testUpgradeWithMixedPodsAndNewSpsWhenUpgradingKafka(VertxTestContext context) { String oldKafkaVersion = KafkaVersionTestUtils.PREVIOUS_KAFKA_VERSION; String oldInterBrokerProtocolVersion = KafkaVersionTestUtils.PREVIOUS_PROTOCOL_VERSION; String oldLogMessageFormatVersion =...
@Override public String getTaskType() { return "killallchildprocess"; }
@Test public void shouldKnowItsType() { assertThat(new KillAllChildProcessTask().getTaskType(), is("killallchildprocess")); }
@Override public Batch toBatch() { return new SparkBatch( sparkContext, table, readConf, groupingKeyType(), taskGroups(), expectedSchema, hashCode()); }
@TestTemplate public void testPartitionedBucketLong() throws Exception { createPartitionedTable(spark, tableName, "bucket(5, id)"); SparkScanBuilder builder = scanBuilder(); BucketFunction.BucketLong function = new BucketFunction.BucketLong(DataTypes.LongType); UserDefinedScalarFunc udf = toUDF(func...
static ConfigNode propsToNode(Map<String, String> properties) { String rootNode = findRootNode(properties); ConfigNode root = new ConfigNode(rootNode); for (Map.Entry<String, String> e : properties.entrySet()) { parseEntry(e.getKey().replaceFirst(rootNode + ".", ""), e.getValue(), r...
@Test public void shouldParse() { Map<String, String> m = new HashMap<>(); m.put("foo.bar1", "1"); m.put("foo.bar2", "2"); m.put("foo.bar3.bar4", "4"); ConfigNode configNode = PropertiesToNodeConverter.propsToNode(m); assertNull(configNode.getValue()); assert...
public Optional<YamlRuleConfiguration> swapToYamlRuleConfiguration(final Collection<RepositoryTuple> repositoryTuples, final Class<? extends YamlRuleConfiguration> toBeSwappedType) { RepositoryTupleEntity tupleEntity = toBeSwappedType.getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) ...
@Test void assertSwapToYamlRuleConfigurationWithoutRepositoryTupleEntityAnnotation() { assertFalse(new RepositoryTupleSwapperEngine().swapToYamlRuleConfiguration(Collections.emptyList(), NoneYamlRuleConfiguration.class).isPresent()); }
@Override public ICardinality merge(ICardinality... estimators) throws CardinalityMergeException { HyperLogLog merged = new HyperLogLog(log2m, new RegisterSet(this.registerSet.count)); merged.addAll(this); if (estimators == null) { return merged; } for (ICardina...
@Test public void testMerge() throws CardinalityMergeException { int numToMerge = 5; int bits = 16; int cardinality = 1000000; HyperLogLog[] hyperLogLogs = new HyperLogLog[numToMerge]; HyperLogLog baseline = new HyperLogLog(bits); for (int i = 0; i < numToMerge; i++)...
public static PostgreSQLCommandPacket newInstance(final CommandPacketType commandPacketType, final PostgreSQLPacketPayload payload) { if (!OpenGaussCommandPacketType.isExtendedProtocolPacketType(commandPacketType)) { payload.getByteBuf().skipBytes(1); return getCommandPacket(commandPacke...
@Test void assertNewPostgreSQLPacket() { assertThat(OpenGaussCommandPacketFactory.newInstance(mock(PostgreSQLCommandPacketType.class), payload), instanceOf(PostgreSQLCommandPacket.class)); }
@Override public boolean isImmutableType() { return false; }
@Test void arrayTypeIsMutable() { StringArraySerializer serializer = (StringArraySerializer) createSerializer(); assertThat(serializer.isImmutableType()).isFalse(); }
private List<Object> getTargetInstancesByRules(String targetName, List<Object> instances, String path, Map<String, List<String>> header) { RouterConfiguration configuration = ConfigCache.getLabel(RouterConstant.SPRING_CACHE_NAME); if (RouterConfiguration.isInValid(configuration, RouterConsta...
@Test public void testGetTargetInstancesByRules() { RuleInitializationUtils.initFlowMatchRule(); List<Object> instances = new ArrayList<>(); ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0"); instances.add(instance1); ServiceInstanc...
public void transmit(final int msgTypeId, final DirectBuffer srcBuffer, final int srcIndex, final int length) { checkTypeId(msgTypeId); checkMessageLength(length); final AtomicBuffer buffer = this.buffer; long currentTail = buffer.getLong(tailCounterIndex); int recordOffset ...
@Test void shouldTransmitIntoEndOfBuffer() { final int length = 8; final int recordLength = length + HEADER_LENGTH; final int recordLengthAligned = align(recordLength, RECORD_ALIGNMENT); final long tail = CAPACITY - recordLengthAligned; final int recordOffset = (int)tail;...
@Override protected void propagationField(String keyName, String value) { if (keyName == null) throw new NullPointerException("keyName == null"); if (value == null) throw new NullPointerException("value == null"); Key<String> key = nameToKey.get(keyName); if (key == null) { assert false : "We cur...
@Test void propagationField_replace() { headers.put(b3Key, "0"); request.propagationField("b3", "1"); assertThat(request.headers.get(b3Key)).isEqualTo("1"); }
@Udf(description = "Converts a number of milliseconds since 1970-01-01 00:00:00 UTC/GMT into the" + " string representation of the timestamp in the given format. Single quotes in the" + " timestamp format can be escaped with '', for example: 'yyyy-MM-dd''T''HH:mm:ssX'." + " The system default time zon...
@Test public void shouldThrowIfFormatInvalid() { // When: final KsqlException e = assertThrows( KsqlFunctionException.class, () -> udf.timestampToString(1638360611123L, "invalid") ); // Then: assertThat(e.getMessage(), containsString("Unknown pattern letter: i")); }
public static boolean isValidCard18(String idcard) { return isValidCard18(idcard, true); }
@Test public void isValidCard18Test(){ boolean isValidCard18 = IdcardUtil.isValidCard18("3301022011022000D6"); assertFalse(isValidCard18); // 不忽略大小写情况下,X严格校验必须大写 isValidCard18 = IdcardUtil.isValidCard18("33010219200403064x", false); assertFalse(isValidCard18); isValidCard18 = IdcardUtil.isValidCard18("330...
@Override public void run() { serverMonitoringMetrics.setNumberOfConnectedSonarLintClients(sonarLintClientsRegistry.countConnectedClients()); }
@Test public void run_when5ConnectedClients_updateWith5() { when(sonarLintClientsRegistry.countConnectedClients()).thenReturn(5L); underTest.run(); verify(metrics).setNumberOfConnectedSonarLintClients(5L); }
public Map<String, StepRuntimeState> getStepStates( String workflowId, long workflowInstanceId, long workflowRunId, List<String> stepIds) { return withMetricLogError( () -> withRetryableTransaction( conn -> { try (PreparedStatement stmt = ...
@Test public void testGetStepStates() { Map<String, StepRuntimeState> stats = stepDao.getStepStates(TEST_WORKFLOW_ID, 1, 1, Arrays.asList("job1", "job2")); assertEquals(singletonMap(si.getStepId(), si.getRuntimeState()), stats); }
@JsonCreator public static AuditEventType create(@JsonProperty(FIELD_NAMESPACE) String namespace, @JsonProperty(FIELD_OBJECT) String object, @JsonProperty(FIELD_ACTION) String action) { return new AutoValue_AuditEventType(namesp...
@Test public void testInvalid3() throws Exception { expectedException.expect(IllegalArgumentException.class); AuditEventType.create(null); }
@Override public void createDb(String dbName, Map<String, String> properties) throws AlreadyExistsException { if (dbExists(dbName)) { throw new AlreadyExistsException("Database Already Exists"); } icebergCatalog.createDb(dbName, properties); }
@Test(expected = IllegalArgumentException.class) public void testCreateDbWithErrorConfig() throws AlreadyExistsException { IcebergHiveCatalog hiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), new HashMap<>()); IcebergMetadata metadata = new IcebergMetadata(CATALOG_NAME, HDFS_EN...
public void handleAssignment(final Map<TaskId, Set<TopicPartition>> activeTasks, final Map<TaskId, Set<TopicPartition>> standbyTasks) { log.info("Handle new assignment with:\n" + "\tNew active tasks: {}\n" + "\tNew standby tasks: {}\n" +...
@Test public void shouldRemoveUnusedFailedActiveTaskFromStateUpdaterAndCloseDirty() { final StreamTask activeTaskToClose = statefulTask(taskId03, taskId03ChangelogPartitions) .inState(State.RESTORING) .withInputPartitions(taskId03Partitions).build(); final TasksRegistry tasks...
public long timeout() { long timer = this.timer.timeout(); long ticket = this.ticket.timeout(); if (timer < 0 || ticket < 0) { return Math.max(timer, ticket); } else { return Math.min(timer, ticket); } }
@Test public void testNoTicket() { assertThat(ticker.timeout(), is(-1L)); }
@Override public int remainingCapacity() { return createSemaphore(null).availablePermits(); }
@Test public void testRemainingCapacity() throws InterruptedException { RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("bounded-queue:testRemainingCapacity"); assertThat(queue1.trySetCapacity(3)).isTrue(); assertThat(queue1.remainingCapacity()).isEqualTo(3); ...
@Override @MethodNotAvailable public void removeAll() { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testRemoveAll() { adapter.removeAll(); }
public static String calculateTypeName(CompilationUnit compilationUnit, FullyQualifiedJavaType fqjt) { if (fqjt.isArray()) { // if array, then calculate the name of the base (non-array) type // then add the array indicators back in String fqn = fqjt.getFullyQualifiedName(); ...
@Test void testGenericTypeNothingImported() { Interface interfaze = new Interface(new FullyQualifiedJavaType("com.foo.UserMapper")); FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("java.util.Map<java.math.BigDecimal, java.util.List<com.beeant.dto.User>>"); assertEquals("java.util....
public synchronized boolean getHasError() { return hasError; }
@Test public void shouldDefaultToFalseForHasError() { // Given: final ProcessingQueue queue = new ProcessingQueue(new QueryId("a")); // Then: assertThat(queue.getHasError(),is(false)); }
@Override public Set<String> getWorkerUUIDs() { Set<UUID> connectedWorkerUUIDs = hazelcastMember.getMemberUuids(); return getClusteredWorkerUUIDs().entrySet().stream() .filter(e -> connectedWorkerUUIDs.contains(e.getKey())) .map(Map.Entry::getValue) .flatMap(Set::stream) .collect(Coll...
@Test public void getWorkerUUIDs_must_filter_absent_client() { when(hzClientWrapper.getUuid()).thenReturn(clientUUID1); when(hzClientWrapper.getMemberUuids()).thenReturn(ImmutableSet.of(clientUUID1, clientUUID2)); when(hzClientWrapper.<UUID, Set<String>>getReplicatedMap(WORKER_UUIDS)).thenReturn(workerMap...
@Override public SCMPropertyConfiguration responseMessageForSCMConfiguration(String responseBody) { try { SCMPropertyConfiguration scmConfiguration = new SCMPropertyConfiguration(); Map<String, Map> configurations; try { configurations = parseResponseToMap...
@Test public void shouldBuildSCMConfigurationFromResponseBody() throws Exception { String responseBody = "{" + "\"key-one\":{}," + "\"key-two\":{\"default-value\":\"two\",\"part-of-identity\":true,\"secure\":true,\"required\":true,\"display-name\":\"display-two\",\"display-or...
@PostMapping("create-review") public Mono<String> createReview(@ModelAttribute("product") Mono<Product> productMono, NewProductReviewPayload payload, Model model, ServerHttpResponse response) { ret...
@Test void createReview_RequestIsInvalid_ReturnsProductPageWithPayloadAndErrors() { // given var model = new ConcurrentModel(); var response = new MockServerHttpResponse(); var favouriteProduct = new FavouriteProduct(UUID.fromString("af5f9496-cbaa-11ee-a407-27b46917819e"), 1); ...
public static boolean isSentinelResource(HasMetadata resource) { Map<String, String> labels = resource.getMetadata().getLabels(); if (labels == null) { return false; } String namespace = resource.getMetadata().getNamespace(); return shouldSentinelWatchGivenNamespace(namespace) && Boole...
@Test @Order(1) void testIsSentinelResource() { SparkApplication sparkApplication = new SparkApplication(); Map<String, String> lableMap = sparkApplication.getMetadata().getLabels(); lableMap.put(Constants.LABEL_SENTINEL_RESOURCE, "true"); Set<String> namespaces = new HashSet<>(); sparkApplicati...
@Override public void replay( long offset, long producerId, short producerEpoch, CoordinatorRecord record ) throws RuntimeException { ApiMessageAndVersion key = record.key(); ApiMessageAndVersion value = record.value(); switch (key.version()) { ...
@Test public void testReplayConsumerGroupTargetAssignmentMember() { GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class); OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class); CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.c...
@Override public ObjectNode encode(Criterion criterion, CodecContext context) { EncodeCriterionCodecHelper encoder = new EncodeCriterionCodecHelper(criterion, context); return encoder.encode(); }
@Test public void matchTcpSrcTest() { Criterion criterion = Criteria.matchTcpSrc(tpPort); ObjectNode result = criterionCodec.encode(criterion, context); assertThat(result, matchesCriterion(criterion)); }
@Override public void commit() { throw new UnsupportedOperationException("StateStores can't access commit."); }
@Test public void shouldThrowOnCommit() { assertThrows(UnsupportedOperationException.class, () -> context.commit()); }
@Override public String getRawSourceHash(Component file) { checkComponentArgument(file); if (rawSourceHashesByKey.containsKey(file.getKey())) { return checkSourceHash(file.getKey(), rawSourceHashesByKey.get(file.getKey())); } else { String newSourceHash = computeRawSourceHash(file); rawS...
@Test void getRawSourceHash_reads_lines_from_SourceLinesRepository_only_the_first_time() { when(mockedSourceLinesRepository.readLines(FILE_COMPONENT)).thenReturn(CloseableIterator.from(Arrays.asList(SOME_LINES).iterator())); String rawSourceHash = mockedUnderTest.getRawSourceHash(FILE_COMPONENT); String ...
@Override public void received(Channel channel, Object message) throws RemotingException { if (message instanceof Decodeable) { decode(message); } if (message instanceof Request) { decode(((Request) message).getData()); } if (message instanceof Respo...
@Test void test() throws Exception { ChannelHandler handler = Mockito.mock(ChannelHandler.class); Channel channel = Mockito.mock(Channel.class); DecodeHandler decodeHandler = new DecodeHandler(handler); MockData mockData = new MockData(); decodeHandler.received(channel, mock...
public static ViewMetadata fromJson(String metadataLocation, String json) { return JsonUtil.parse(json, node -> ViewMetadataParser.fromJson(metadataLocation, node)); }
@Test public void failReadingViewMetadataInvalidSchemaId() throws Exception { String json = readViewMetadataInputFile("org/apache/iceberg/view/ViewMetadataInvalidCurrentSchema.json"); ViewMetadata metadata = ViewMetadataParser.fromJson(json); assertThatThrownBy(metadata::currentSchemaId) ....
static void readFromGetEndpointExample(List<String> urls, Pipeline pipeline) { // Pipeline pipeline = Pipeline.create(); // List<String> urls = ImmutableList.of( // "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg", // "https://storage.go...
@Test public void testReadFromGetEndpointExample() { Pipeline pipeline = Pipeline.create(); List<String> urls = ImmutableList.of( "https://storage.googleapis.com/generativeai-downloads/images/cake.jpg", "https://storage.googleapis.com/generativeai-downloads/images/chocolate.pn...
public static CharSequence unescapeCsv(CharSequence value) { int length = checkNotNull(value, "value").length(); if (length == 0) { return value; } int last = length - 1; boolean quoted = isDoubleQuote(value.charAt(0)) && isDoubleQuote(value.charAt(last)) && length !=...
@Test public void unescapeCsvWithLFAndWithoutQuote() { assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() { unescapeCsv("\n"); } }); }
protected void resolveProvider( FileDialogOperation op ) { if ( op.getProvider() == null ) { if ( isVfsPath( op.getPath() ) ) { op.setProvider( VFSFileProvider.TYPE ); } else if ( spoonSupplier.get().getRepository() != null ) { op.setProvider( RepositoryFileProvider.TYPE ); } else ...
@Test public void testResolveProvider_AlreadySet() throws Exception { // SETUP FileOpenSaveExtensionPoint testInstance = new FileOpenSaveExtensionPoint( null, null ); FileDialogOperation opAlreadySet = new FileDialogOperation( FILE_OP_DUMMY_COMMAND ); String providerNonProductionValue = "DontChangeM...
@Override public BufferedSink writeUtf8(String string) throws IOException { if (closed) throw new IllegalStateException("closed"); buffer.writeUtf8(string); return emitCompleteSegments(); }
@Test public void incompleteSegmentsNotEmitted() throws Exception { Buffer sink = new Buffer(); BufferedSink bufferedSink = new RealBufferedSink(sink); bufferedSink.writeUtf8(repeat('a', Segment.SIZE * 3 - 1)); assertEquals(Segment.SIZE * 2, sink.size()); }
public static <T> byte[] encodeToByteArray(Coder<T> coder, T value) throws CoderException { return encodeToByteArray(coder, value, Coder.Context.OUTER); }
@Test public void testClosingCoderFailsWhenEncodingToByteArray() throws Exception { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Caller does not own the underlying"); CoderUtils.encodeToByteArray(new ClosingCoder(), "test-value"); }
public <T> void resolve(T resolvable) { ParamResolver resolver = this; if (ParamScope.class.isAssignableFrom(resolvable.getClass())) { ParamScope newScope = (ParamScope) resolvable; resolver = newScope.applyOver(resolver); } resolveStringLeaves(resolvable, resolve...
@Test public void shouldResolve_ConfigValue_MappedAsObject() { SecurityConfig securityConfig = new SecurityConfig(); securityConfig.adminsConfig().add(new AdminUser(new CaseInsensitiveString("lo#{foo}"))); securityConfig.addRole(new RoleConfig(new CaseInsensitiveString("boo#{bar}"), new Role...
@Override public ExecuteContext before(ExecuteContext context) { Object object = context.getObject(); String serviceId = getServiceId(object).orElse(null); if (StringUtils.isBlank(serviceId)) { return context; } Object obj = context.getMemberFieldValue("serviceIns...
@Test public void testBeforeWhenInvalid() { interceptor.before(context); ServiceInstanceListSupplier supplier = (ServiceInstanceListSupplier) context.getObject(); List<ServiceInstance> instances = supplier.get().blockFirst(); Assert.assertNotNull(instances); Assert.assertEqua...
@VisibleForTesting void handleResponse(DiscoveryResponseData response) { ResourceType resourceType = response.getResourceType(); switch (resourceType) { case NODE: handleD2NodeResponse(response); break; case D2_URI_MAP: handleD2URIMapResponse(response); break;...
@Test public void testHandleD2NodeResponseWithRemoval() { XdsClientImplFixture fixture = new XdsClientImplFixture(); fixture._nodeSubscriber.setData(NODE_UPDATE1); fixture._xdsClientImpl.handleResponse(DISCOVERY_RESPONSE_NODE_DATA_WITH_REMOVAL); fixture.verifyAckSent(1); verify(fixture._resource...
public String getExpectedValue() { return getPropertyAsString(EXPECTEDVALUE); }
@Test void testGetExpectedValue() { JSONPathAssertion instance = new JSONPathAssertion(); String expResult = ""; String result = instance.getExpectedValue(); assertEquals(expResult, result); }
@Override public ConsumeMessageDirectlyResult consumeMessageDirectly(MessageExt msg, String brokerName) { ConsumeMessageDirectlyResult result = new ConsumeMessageDirectlyResult(); result.setOrder(true); List<MessageExt> msgs = new ArrayList<>(); msgs.add(msg); MessageQueue m...
@Test public void testConsumeMessageDirectlyWithCrThrowException() { when(messageListener.consumeMessage(any(), any(ConsumeOrderlyContext.class))).thenThrow(new RuntimeException("exception")); ConsumeMessageDirectlyResult actual = popService.consumeMessageDirectly(createMessageExt(), defaultBroker);...
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected) { return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected)); }
@Test public void iterableContainsAtLeastFailsWithSameToStringAndHeterogeneousListWithDuplicates() { expectFailureWhenTestingThat(asList(1, 2, 2L, 3L, 3L)).containsAtLeast(2L, 2L, 3, 3); assertFailureValue("missing (3)", "2 (java.lang.Long), 3 (java.lang.Integer) [2 copies]"); assertFailureValue( ...
@Override public RelativeRange apply(final Period period) { if (period != null) { return RelativeRange.Builder.builder() .from(period.withYears(0).withMonths(0).plusDays(period.getYears() * 365).plusDays(period.getMonths() * 30).toStandardSeconds().getSeconds()) ...
@Test void testDayConversion() { final RelativeRange result = converter.apply(Period.days(2)); verifyResult(result, 172800); }
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_FieldAndParentIsNonEmptyMultiResult_nullValueFirst_thenInferReturnType() throws Exception { OuterObject object = new OuterObject("name", new InnerObject("inner", null, 0, 1, 2, 3)); Getter parentGetter = GetterFactor...
public static boolean analyzeRebalance(final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable) { return true; }
@Test public void testAnalyzeRebalance() { boolean result = ConsumerRunningInfo.analyzeRebalance(criTable); assertThat(result).isTrue(); }
@Override public List<FileEntriesLayer> createLayers() throws IOException { // Clear the exploded-artifact root first if (Files.exists(targetExplodedJarRoot)) { MoreFiles.deleteRecursively(targetExplodedJarRoot, RecursiveDeleteOption.ALLOW_INSECURE); } try (JarFile jarFile = new JarFile(jarPath...
@Test public void testCreateLayers_layered_singleEmptyLayerListed() throws IOException, URISyntaxException { // BOOT-INF/layers.idx for this spring-boot jar is as follows: // - "dependencies": // - "BOOT-INF/lib/dependency1.jar" // - "BOOT-INF/lib/dependency2.jar" // - "spring-boot-loade...
public Set<Integer> nodesThatShouldBeDown(ClusterState state) { return calculate(state).nodesThatShouldBeDown(); }
@Test void implicitly_downed_node_at_state_end_is_counted_as_explicitly_down() { GroupAvailabilityCalculator calc = calcForHierarchicCluster( DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99); assertThat(calc.nodesThatShouldBeDown(clusterState( "distributo...
public static Future<Integer> authTlsHash(SecretOperator secretOperations, String namespace, KafkaClientAuthentication auth, List<CertSecretSource> certSecretSources) { Future<Integer> tlsFuture; if (certSecretSources == null || certSecretSources.isEmpty()) { tlsFuture = Future.succeededFutu...
@Test void testAuthTlsPlainSecretAndPasswordFound() { SecretOperator secretOperator = mock(SecretOperator.class); Map<String, String> data = new HashMap<>(); data.put("passwordKey", "my-password"); Secret secret = new Secret(); secret.setData(data); CompletionStage<Se...
public void poll(RequestFuture<?> future) { while (!future.isDone()) poll(time.timer(Long.MAX_VALUE), future); }
@Test public void testInvalidTopicExceptionPropagatedFromMetadata() { MetadataResponse metadataResponse = RequestTestUtils.metadataUpdateWith("clusterId", 1, Collections.singletonMap("topic", Errors.INVALID_TOPIC_EXCEPTION), Collections.emptyMap()); metadata.updateWithCurrentRequestV...
public T run() throws Exception { try { return execute(); } catch(Exception e) { if (e.getClass().equals(retryExceptionType)){ tries++; if (MAX_RETRIES == tries) { throw e; } else { return run(); } } else { throw e; } } }
@Test public void testRetryFailure() { Retry<Void> retriable = new Retry<Void>(NullPointerException.class) { @Override public Void execute() { throw new RuntimeException(); } }; try { retriable.run(); Assert.fail(); } catch (Exception e) { Assert.assertEqual...
public Optional<Throwable> run(String... arguments) { try { if (isFlag(HELP, arguments)) { parser.printHelp(stdOut); } else if (isFlag(VERSION, arguments)) { parser.printVersion(stdOut); } else { final Namespace namespace = pars...
@Test void handlesLongHelpSubcommands() throws Exception { assertThat(cli.run("check", "--help")) .isEmpty(); assertThat(stdOut) .hasToString(String.format( "usage: java -jar dw-thing.jar check [-h] [file]%n" + ...
@Override public AdminUserDO authenticate(String username, String password) { final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME; // 校验账号是否存在 AdminUserDO user = userService.getUserByUsername(username); if (user == null) { createLoginLog(null, username, l...
@Test public void testAuthenticate_success() { // 准备参数 String username = randomString(); String password = randomString(); // mock user 数据 AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setUsername(username) .setPassword(password).setStatus(CommonStat...
public SerializableFunction<Row, T> getFromRowFunction() { return fromRowFunction; }
@Test public void testNestedRowToProto() throws InvalidProtocolBufferException { ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(Nested.getDescriptor()); SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction(); Nested proto = parseFrom(fromRow.apply(NESTED_R...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .precision(column.getColumnLength()) .length(column.getColumn...
@Test public void testReconvertInt() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.INT_TYPE).build(); BasicTypeDefine typeDefine = IrisTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName()); Assertions.a...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void zeroFailureRateThresholdShouldFail() { custom().failureRateThreshold(0).build(); }
public static void refreshSuperUserGroupsConfiguration() { //load server side configuration; refreshSuperUserGroupsConfiguration(new Configuration()); }
@Test public void testNetgroups () throws IOException{ if(!NativeCodeLoader.isNativeCodeLoaded()) { LOG.info("Not testing netgroups, " + "this test only runs when native code is compiled"); return; } String groupMappingClassName = System.getProperty("TestProxyUsersGroupMappin...
@Override public MaterialPollResult responseMessageForLatestRevisionsSince(String responseBody) { if (isEmpty(responseBody)) return new MaterialPollResult(); Map responseBodyMap = getResponseMap(responseBody); return new MaterialPollResult(toMaterialDataMap(responseBodyMap), toSCMRevisions(r...
@Test public void shouldBuildSCMDataFromLatestRevisionsSinceResponse() throws Exception { String responseBodyWithSCMData = "{\"revisions\":[],\"scm-data\":{\"key-one\":\"value-one\"}}"; MaterialPollResult pollResult = messageHandler.responseMessageForLatestRevisionsSince(responseBodyWithSCMData); ...
public Node parse() throws ScanException { if (tokenList == null || tokenList.isEmpty()) return null; return E(); }
@Test public void literalWithAccolade0() throws ScanException { Tokenizer tokenizer = new Tokenizer("{}"); Parser parser = new Parser(tokenizer.tokenize()); Node node = parser.parse(); Node witness = new Node(Node.Type.LITERAL, "{"); witness.next = new Node(Node.Type.LITERAL, "}"); assertEqual...
@Override public void setApplicationContext(@NonNull final ApplicationContext applicationContext) throws BeansException { SpringBeanUtils.getInstance().setApplicationContext(applicationContext); ShenyuConfig shenyuConfig = SpringBeanUtils.getInstance().getBean(ShenyuConfig.class); Singleton....
@Test public void applicationContextAwareTest() { ConfigurableApplicationContext applicationContext = mock(ConfigurableApplicationContext.class); SpringBeanUtils.getInstance().setApplicationContext(applicationContext); when(SpringBeanUtils.getInstance().getBean(ShenyuConfig.class)) ...
public static String hashpw(String password, String salt) throws IllegalArgumentException { BCrypt B; String real_salt; byte passwordb[], saltb[], hashed[]; char minor = (char) 0; int rounds, off = 0; StringBuilder rs = new StringBuilder(); if (salt == null) { ...
@Test public void testHashpwInvalidSaltRevision2() throws IllegalArgumentException { thrown.expect(IllegalArgumentException.class); BCrypt.hashpw("foo", "$2a+10$....................."); }
public static boolean isCompressData(byte[] bytes) { if (bytes != null && bytes.length > 2) { int header = ((bytes[0] & 0xff)) | (bytes[1] & 0xff) << 8; return GZIPInputStream.GZIP_MAGIC == header; } return false; }
@Test public void testIsCompressData() { Assertions.assertFalse(CompressUtil.isCompressData(null)); Assertions.assertFalse(CompressUtil.isCompressData(new byte[0])); Assertions.assertFalse(CompressUtil.isCompressData(new byte[]{31, 11})); Assertions.assertFalse( Compr...
public static short translateBucketAcl(GSAccessControlList acl, String userId) { short mode = (short) 0; for (GrantAndPermission gp : acl.getGrantAndPermissions()) { Permission perm = gp.getPermission(); GranteeInterface grantee = gp.getGrantee(); if (perm.equals(Permission.PERMISSION_READ)) {...
@Test public void translateEveryoneFullPermission() { GroupGrantee allUsersGrantee = GroupGrantee.ALL_USERS; mAcl.grantPermission(allUsersGrantee, Permission.PERMISSION_FULL_CONTROL); assertEquals((short) 0700, GCSUtils.translateBucketAcl(mAcl, ID)); assertEquals((short) 0700, GCSUtils.translateBucket...
@Override public void setResult(CeTaskResult taskResult) { requireNonNull(taskResult, "taskResult can not be null"); checkState(this.result == null, "CeTaskResult has already been set in the holder"); this.result = taskResult; }
@Test public void setResult_throws_NPE_if_CeTaskResult_argument_is_null() { assertThatThrownBy(() -> underTest.setResult(null)) .isInstanceOf(NullPointerException.class) .hasMessage("taskResult can not be null"); }
@SuppressWarnings("MethodLength") public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { final MessageHeaderDecoder headerDecoder = decoders.header; headerDecoder.wrap(buffer, offset); final int schemaId = headerDecoder.schemaId(); ...
@Test void shouldHandleBoundedReplayRequest() { final ControlSessionDemuxer controlSessionDemuxer = new ControlSessionDemuxer( new ControlRequestDecoders(), mockImage, mockConductor, mockAuthorisationService); setupControlSession(controlSessionDemuxer, CONTROL_SESSION_ID); f...
public void toPdf() throws IOException { try { document.open(); // il serait possible d'ouvrir la boîte de dialogue Imprimer de Adobe Reader // if (writer instanceof PdfWriter) { // ((PdfWriter) writer).addJavaScript("this.print(true);", false); // } pdfCoreReport.toPdf(); ...
@Test public void testEmptyPdfCounterRequestContext() throws IOException, DocumentException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PdfDocumentFactory pdfDocumentFactory = new PdfDocumentFactory(TEST_APP, null, output); final Document document = pdfDocumentFactory.createDocu...
@Override public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { String originalString = values[0].execute(); String mode = null; // default if (values.length > 1) { mode = values[1].execute(); } if(StringUtils...
@Test public void testChangeCaseLower() throws Exception { String returnValue = execute("myUpperTest", "LOWER"); assertEquals("myuppertest", returnValue); }
@Override public void applyToConfiguration(Configuration configuration) { super.applyToConfiguration(configuration); merge(configuration, pythonConfiguration); }
@Test void testCreateProgramOptionsWithPythonCommandLine() throws CliArgsException { String[] parameters = { "-py", "test.py", "-pym", "test", "-pyfs", "test1.py,test2.zip,test3.egg,test4_dir", "-pyreq", "a.txt#b_dir", "-pyarch", "c.zip#venv,d.zip"...
@Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("minLatitude="); stringBuilder.append(this.minLatitude); stringBuilder.append(", minLongitude="); stringBuilder.append(this.minLongitude); stringBuilder.append...
@Test public void toStringTest() { BoundingBox boundingBox = new BoundingBox(MIN_LATITUDE, MIN_LONGITUDE, MAX_LATITUDE, MAX_LONGITUDE); Assert.assertEquals(BOUNDING_BOX_TO_STRING, boundingBox.toString()); }
@Override public AppResponse process(Flow flow, MultipleSessionsRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException { var authAppSession = appSessionService.getSession(request.getAuthSessionId()); if (!isAppSessionAuthenticated(authAppSession)) return new NokRespon...
@Test public void processSessionInformationReceivedActivateResponseOk() throws FlowNotDefinedException, IOException, NoSuchAlgorithmException { //given Map<String, String> activateResponse = Map.of("status", "OK", "faultReason", "NotUnique", "pip", "testpip"); when(appAuthenticatorService.fi...
protected static String assureRoot(String queueName) { if (queueName != null && !queueName.isEmpty()) { if (!queueName.startsWith(ROOT_QUEUE + DOT) && !queueName.equals(ROOT_QUEUE)) { queueName = ROOT_QUEUE + DOT + queueName; } } else { LOG.warn("AssureRoot: queueName is empt...
@Test public void testAssureRoot() { // permutations of rooted queue names final String queueName = "base"; final String rootOnly = "root"; final String rootNoDot = "rootbase"; final String alreadyRoot = "root.base"; String rooted = assureRoot(queueName); assertTrue("Queue should have roo...
@Override public void startAsync() { if (!shouldCheckPreconditions()) { LOG.info("All preconditions passed, skipping precondition server start"); return; } LOG.info("Some preconditions not passed, starting precondition server"); server.start(); }
@Test public void shouldNotStartServerIfPreconditionsPass() { // When: checker.startAsync(); // Then: verifyNoInteractions(server); }
@Override public Mono<UserDetails> findByUsername(String username) { return userService.getUser(username) .onErrorMap(UserNotFoundException.class, e -> new BadCredentialsException("Invalid Credentials")) .flatMap(user -> { var name = user.getMetadata()...
@Test void shouldNotFindUserDetailsByNonExistingUsername() { when(userService.getUser("non-existing-user")).thenReturn( Mono.error(() -> new UserNotFoundException("non-existing-user"))); var userDetailsMono = userDetailService.findByUsername("non-existing-user"); StepVerifier.c...
public static void recursivelyRegisterType( TypeInformation<?> typeInfo, SerializerConfig config, Set<Class<?>> alreadySeen) { if (typeInfo instanceof GenericTypeInfo) { GenericTypeInfo<?> genericTypeInfo = (GenericTypeInfo<?>) typeInfo; Serializers.recursivelyRegisterType( ...
@Test void testTypeRegistrationFromTypeInfo() { SerializerConfigImpl conf = new SerializerConfigImpl(); Serializers.recursivelyRegisterType( new GenericTypeInfo<>(ClassWithNested.class), conf, new HashSet<Class<?>>()); KryoSerializer<String> kryo = new KryoSe...
public static Long getLongOrNull(String property, JsonNode node) { if (!node.hasNonNull(property)) { return null; } return getLong(property, node); }
@Test public void getLongOrNull() throws JsonProcessingException { assertThat(JsonUtil.getLongOrNull("x", JsonUtil.mapper().readTree("{}"))).isNull(); assertThat(JsonUtil.getLongOrNull("x", JsonUtil.mapper().readTree("{\"x\": 23}"))) .isEqualTo(23); assertThat(JsonUtil.getLongOrNull("x", JsonUtil....
@Override public CommandLineImpl parse(final List<String> originalArgs, final Logger logger) { return CommandLineImpl.of(originalArgs, logger); }
@Test public void testRun() throws Exception { final CommandLineParserImpl parser = new CommandLineParserImpl(); final CommandLineImpl commandLine = parse( parser, "-R--dev", "--log-level", "warn", "--log-path", "/var/log/some", ...
@Override public int size() { return get(sizeAsync()); }
@Test public void testSize() { RSetCache<Integer> set = redisson.getSetCache("set"); set.add(1); set.add(2); set.add(3); set.add(3); set.add(4); set.add(5); set.add(5); Assertions.assertEquals(5, set.size()); set.destroy(); }
@Override public void close() { close(Duration.ofMillis(0)); }
@Test public void shouldThrowOnCommitTransactionIfProducerIsClosed() { buildMockProducer(true); producer.close(); assertThrows(IllegalStateException.class, producer::commitTransaction); }
public static PredicateTreeAnnotations createPredicateTreeAnnotations(Predicate predicate) { PredicateTreeAnalyzerResult analyzerResult = PredicateTreeAnalyzer.analyzePredicateTree(predicate); // The tree size is used as the interval range. int intervalEnd = analyzerResult.treeSize; Anno...
@Test void require_that_ands_below_ors_get_different_intervals() { Predicate p = or( and( feature("key1").inSet("value1"), feature("key1").inSet("value1"), feature("key1")....
public String queryParam(String queryParamName) { return optionalQueryParam(queryParamName).orElse(null); }
@Test void testRequestUrlQueryParamWhichIsNotPresentUsingClass() { RequestUrl requestUrl = new MatchUrl("/api/jobs").toRequestUrl("/api/jobs"); assertThat(requestUrl.queryParam("state", StateName.class, ENQUEUED)).isEqualTo(ENQUEUED); }
@Override public CompletableFuture<JoinGroupResponseData> joinGroup( RequestContext context, JoinGroupRequestData request, BufferSupplier bufferSupplier ) { if (!isActive.get()) { return CompletableFuture.completedFuture(new JoinGroupResponseData() .se...
@Test public void testJoinGroup() { CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime(); GroupCoordinatorService service = new GroupCoordinatorService( new LogContext(), createConfig(), runtime, new GroupCoordinatorMetr...