focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Object convert(String value) { if (isNullOrEmpty(value)) { return value; } if (value.contains("=")) { final Map<String, String> fields = new HashMap<>(); Matcher m = PATTERN.matcher(value); while (m.find()) { ...
@Test public void testFilterWithIDAdditionalField() { TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>()); @SuppressWarnings("unchecked") Map<String, String> result = (Map<String, String>) f.convert("otters _id=123 more otters"); assertEquals(1, result.size(...
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertCompressedObjectMessageToAmqpMessageWithDataBody() throws Exception { ActiveMQObjectMessage outbound = createObjectMessage(TEST_OBJECT_VALUE, true); outbound.onSend(); outbound.storeContent(); JMSMappingOutboundTransformer transformer = new JMSMappingOut...
public Set<String> makeReady(final Map<String, InternalTopicConfig> topics) { // we will do the validation / topic-creation in a loop, until we have confirmed all topics // have existed with the expected number of partitions, or some create topic returns fatal errors. log.debug("Starting to vali...
@Test public void shouldThrowInformativeExceptionForOlderBrokers() { final AdminClient admin = new MockAdminClient() { @Override public CreateTopicsResult createTopics(final Collection<NewTopic> newTopics, final CreateTopicsOptions o...
public synchronized Map<String, Object> getSubtaskOnWorkerProgress(String subtaskState, Executor executor, HttpClientConnectionManager connMgr, Map<String, String> selectedMinionWorkerEndpoints, Map<String, String> requestHeaders, int timeoutMs) throws JsonProcessingException { return getSubtaskOn...
@Test public void testGetSubtaskWithGivenStateProgress() throws IOException { CompletionServiceHelper httpHelper = mock(CompletionServiceHelper.class); CompletionServiceHelper.CompletionServiceResponse httpResp = new CompletionServiceHelper.CompletionServiceResponse(); String taskIdPrefix = ...
public static MonthsWindows months(int number) { return new MonthsWindows(number, 1, DEFAULT_START_DATE, DateTimeZone.UTC); }
@Test public void testDefaultWindowMappingFnGlobal() { MonthsWindows windowFn = CalendarWindows.months(2); WindowMappingFn<?> mapping = windowFn.getDefaultWindowMappingFn(); thrown.expect(IllegalArgumentException.class); mapping.getSideInputWindow(GlobalWindow.INSTANCE); }
@Nullable @Override public String getMainClassFromJarPlugin() { Plugin mavenJarPlugin = project.getPlugin("org.apache.maven.plugins:maven-jar-plugin"); if (mavenJarPlugin != null) { return getChildValue( (Xpp3Dom) mavenJarPlugin.getConfiguration(), "archive", "manifest", "mainClass") ...
@Test public void testGetMainClassFromJar_missingConfiguration() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(mockPlugin); assertThat(mavenProjectProperties.getMainClassFromJarPlugin()).isNull(); }
public <T> T create(Class<T> clazz) { return create(clazz, new Class<?>[]{}, new Object[]{}); }
@Test void testProxyHandlesErrors() { assertThatIllegalStateException().isThrownBy(()-> new UnitOfWorkAwareProxyFactory("default", sessionFactory) .create(BrokenAuthenticator.class) .authenticate("b812ae4")) .withMessage("Session cluster is down"); ...
public Path getAtomicWorkPath() { return atomicWorkPath; }
@Test public void testSetWorkPath() { final DistCpOptions.Builder builder = new DistCpOptions.Builder( Collections.singletonList(new Path("hdfs://localhost:8020/source")), new Path("hdfs://localhost:8020/target/")); Assert.assertNull(builder.build().getAtomicWorkPath()); builder.withAtomi...
@Override public double variance() { return variance; }
@Test public void testVariance() { System.out.println("variance"); WeibullDistribution instance = new WeibullDistribution(1.5, 1.0); instance.rand(); assertEquals(0.37569028, instance.variance(), 1E-7); }
void print(List<Line> lines, AnsiEscapes... border) { int maxLength = lines.stream().map(Line::length).max(comparingInt(a -> a)) .orElseThrow(NoSuchElementException::new); StringBuilder out = new StringBuilder(); Format borderFormat = monochrome ? monochrome() : color(border); ...
@Test void printsMonochromeBanner() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); Banner banner = new Banner(new PrintStream(bytes, false, StandardCharsets.UTF_8.name()), true); banner.print(asList( new Banner.Line("Bla"), new Banner.L...
public void updateCheckboxes( EnumSet<RepositoryFilePermission> permissionEnumSet ) { updateCheckboxes( false, permissionEnumSet ); }
@Test public void testUpdateCheckboxesNoPermissionsAppropriateFalse() { permissionsCheckboxHandler.updateCheckboxes( false, EnumSet.noneOf( RepositoryFilePermission.class ) ); verify( readCheckbox, times( 1 ) ).setChecked( false ); verify( writeCheckbox, times( 1 ) ).setChecked( false ); verify( delet...
@Override public RecordCursor cursor() { return new JdbcRecordCursor(jdbcClient, session, split, columnHandles); }
@Test public void testIdempotentClose() { RecordSet recordSet = new JdbcRecordSet(jdbcClient, session, split, ImmutableList.of( columnHandles.get("value"), columnHandles.get("value"), columnHandles.get("text"))); RecordCursor cursor = recordSet.cu...
@VisibleForTesting static File doUnpackNar(final File nar, final File baseWorkingDirectory, Runnable extractCallback) throws IOException { File parentDirectory = new File(baseWorkingDirectory, nar.getName() + "-unpacked"); if (!parentDirectory.exists()) { if (parentDirectory....
@Test void shouldExtractFilesOnceInSameProcess() throws InterruptedException { int threads = 20; CountDownLatch countDownLatch = new CountDownLatch(threads); AtomicInteger exceptionCounter = new AtomicInteger(); AtomicInteger extractCounter = new AtomicInteger(); for (int i =...
public ClientSession toClientSession() { return new ClientSession( parseServer(server), user, source, Optional.empty(), parseClientTags(clientTags), clientInfo, catalog, schema, ...
@Test public void testDefault() { ClientSession session = new ClientOptions().toClientSession(); assertEquals(session.getServer().toString(), "http://localhost:8080"); assertEquals(session.getSource(), "presto-cli"); }
public Span nextSpan(TraceContextOrSamplingFlags extracted) { if (extracted == null) throw new NullPointerException("extracted == null"); TraceContext context = extracted.context(); if (context != null) return newChild(context); TraceIdContext traceIdContext = extracted.traceIdContext(); if (traceI...
@Test void localRootId_nextSpan_flags_empty() { TraceContextOrSamplingFlags flags = TraceContextOrSamplingFlags.EMPTY; localRootId(flags, flags, ctx -> tracer.nextSpan(ctx)); }
@VisibleForTesting void validateExperienceOutRange(List<MemberLevelDO> list, Long id, Integer level, Integer experience) { for (MemberLevelDO levelDO : list) { if (levelDO.getId().equals(id)) { continue; } if (levelDO.getLevel() < level) { ...
@Test public void testUpdateLevel_experienceOutRange() { // 准备参数 int level = 10; int experience = 10; Long id = randomLongId(); String name = randomString(); // mock 数据 memberlevelMapper.insert(randomLevelDO(o -> { o.setLevel(level); o...
public void check(@NotNull Set<Long> partitionIds, long currentTimeMs) throws CommitRateExceededException, CommitFailedException { Preconditions.checkNotNull(partitionIds, "partitionIds is null"); // Does not limit the commit rate of compaction transactions if (transactionState.getSo...
@Test public void testPartitionHasNoStatistics() throws CommitRateExceededException { long partitionId = 54321; Set<Long> partitions = new HashSet<>(Collections.singletonList(partitionId)); long currentTimeMs = System.currentTimeMillis(); transactionState.setPrepareTime(currentTimeM...
@Override public void startIt() { // do nothing }
@Test public void startIt_does_nothing() { new NoopDatabaseMigrationImpl().startIt(); }
void handleFinish(Resp response, Span span) { if (response == null) throw new NullPointerException("response == null"); if (span.isNoop()) return; if (response.error() != null) { span.error(response.error()); // Ensures MutableSpan.error() for SpanHandler } try { parseResponse(response...
@Test void handleFinish_nothingOnNoop() { when(span.isNoop()).thenReturn(true); handler.handleFinish(response, span); verify(span, never()).finish(); }
@Command(description = "Starts a new Hazelcast member", mixinStandardHelpOptions = true, sortOptions = false) void start( @Option(names = {"-c", "--config"}, paramLabel = "<file>", description = "Use <file> for Hazelcast " + "configuration. " + "Accepted formats a...
@Test void test_start() { // when hazelcastServerCommandLine.start(null, null, null); // then verify(start, times(1)).run(); }
public static Applications mergeApplications(Applications first, Applications second) { Set<String> firstNames = selectApplicationNames(first); Set<String> secondNames = selectApplicationNames(second); Set<String> allNames = new HashSet<>(firstNames); allNames.addAll(secondNames); ...
@Test public void testMergeApplicationsIfNotNullAndHasAppNameReturnApplications() { Application application = createSingleInstanceApp("foo", "foo", InstanceInfo.ActionType.ADDED); Applications applications = createApplications(application); Assert.assertEquals(1, EurekaEn...
protected static String anonymizeLog(String log) { return log.replaceAll( "(/((home)|(Users))/[^/\n]*)|(\\\\Users\\\\[^\\\\\n]*)", "/ANONYMIZED_HOME_DIR"); // NOI18N }
@Test public void testAnonymizeWindowsLog() { String log = "" + " Java Home = C:\\Program Files\\Java\\jre1.8.0_311\n" + " System Locale; Encoding = en_US (gephi); Cp1254\n" + " Home Directory = C:\\Users\\RickAstley\n" + ...
@Override public ICardinality merge(ICardinality... estimators) throws LinearCountingMergeException { if (estimators == null) { return new LinearCounting(map); } LinearCounting[] lcs = Arrays.copyOf(estimators, estimators.length + 1, LinearCounting[].class); lcs[lcs.lengt...
@Test public void testMerge() throws LinearCountingMergeException { int numToMerge = 5; int size = 65536; int cardinality = 1000; LinearCounting[] lcs = new LinearCounting[numToMerge]; LinearCounting baseline = new LinearCounting(size); for (int i = 0; i < numToMerge...
public final BarcodeParameters getParams() { return params; }
@Test final void testConstructorWithImageType() throws IOException { try (BarcodeDataFormat barcodeDataFormat = new BarcodeDataFormat(BarcodeImageType.JPG)) { this.checkParams(BarcodeImageType.JPG, BarcodeParameters.WIDTH, BarcodeParameters.HEIGHT, BarcodeParameters.FORMAT, b...
@Override public V get() { return result; }
@Test public void testGet_WithTimeout() throws Exception { try { promise.get(100); failBecauseExceptionWasNotThrown(OMSRuntimeException.class); } catch (OMSRuntimeException e) { assertThat(e).hasMessageContaining("Get request result is timeout or interrupted"); ...
@Override public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) { final ModelId modelId = entityDescriptor.id(); return cacheService.get(modelId.id()).map(cacheDto -> exportNativeEntity(cacheDto, entityDescriptorIds)); }
@Test @MongoDBFixtures("LookupCacheFacadeTest.json") public void exportEntity() { final EntityDescriptor descriptor = EntityDescriptor.create("5adf24b24b900a0fdb4e52dd", ModelTypes.LOOKUP_CACHE_V1); final EntityDescriptorIds entityDescriptorIds = EntityDescriptorIds.of(descriptor); final...
@SuppressWarnings("unchecked") @Override public void configure(final Map<String, ?> configs, final boolean isKey) { //check to see if the window size config is set and the window size is already set from the constructor final Long configWindowSize; if (configs.get(StreamsConfig.WINDOW_SI...
@Test public void shouldThrowErrorIfWindowSizeIsNotSet() { props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, Serdes.ByteArraySerde.class.getName()); final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>(); assertThrows(IllegalArgumentException.class, () -> deseria...
@Override public long clear() { return get(clearAsync()); }
@Test public void testClear() { RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class)); TestType t = new TestType(); t.setName("name1"); al.set(t); assertThat(al.clear()).isEqualTo(1); TestType n = al.get(new JacksonCodec<>(new ...
@Override public void sync() throws IOException { lock(); try { fileStream.flush(); openNewPartIfNecessary(userDefinedMinPartSize); Committer committer = upload.snapshotAndGetCommitter(); committer.commitAfterRecovery(); closeForCommit(); ...
@Test(expected = Exception.class) public void testSync() throws IOException { streamUnderTest.write(bytesOf("hello")); streamUnderTest.write(bytesOf(" world")); streamUnderTest.sync(); assertThat(multipartUploadUnderTest, hasContent(bytesOf("hello world"))); streamUnderTest.w...
@Override public EntityExcerpt createExcerpt(RuleDao ruleDao) { return EntityExcerpt.builder() .id(ModelId.of(ruleDao.id())) .type(ModelTypes.PIPELINE_RULE_V1) .title(ruleDao.title()) .build(); }
@Test public void createExcerpt() { final RuleDao pipelineRule = RuleDao.builder() .id("id") .title("title") .description("description") .source("rule \"debug\"\nwhen\n true\nthen\n debug($message.message);\nend") .build(); ...
public static Status unblock( final UnsafeBuffer logMetaDataBuffer, final UnsafeBuffer termBuffer, final int blockedOffset, final int tailOffset, final int termId) { Status status = NO_ACTION; int frameLength = frameLengthVolatile(termBuffer, blockedOffset); ...
@Test void shouldTakeNoActionToEndOfPartitionIfMessageCompleteAfterScan() { final int messageLength = HEADER_LENGTH * 4; final int termOffset = TERM_BUFFER_CAPACITY - messageLength; final int tailOffset = TERM_BUFFER_CAPACITY; when(mockTermBuffer.getIntVolatile(termOffset)) ...
@Override public CurrentStateInformation trigger(MigrationStep step, Map<String, Object> args) { context.setCurrentStep(step); if (Objects.nonNull(args) && !args.isEmpty()) { context.addActionArguments(step, args); } String errorMessage = null; try { s...
@Test public void smSetsErrorOnExceptionInAction() { String errorMessage = "Error 40: Insufficient Coffee."; StateMachine<MigrationState, MigrationStep> stateMachine = testStateMachineWithAction((context) -> { throw new RuntimeException(errorMessage); }); migrationStateMa...
public static String parseNormalTopic(String topic, String cid) { if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) { if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX + cid + POP_RETRY_SEPARATOR_V2)) { return topic.substring((MixAll.RETRY_GROUP_TOPIC_PREFIX + cid + POP_RETRY...
@Test public void testParseNormalTopic() { String popRetryTopic = KeyBuilder.buildPopRetryTopicV2(topic, group); assertThat(KeyBuilder.parseNormalTopic(popRetryTopic, group)).isEqualTo(topic); String popRetryTopicV1 = KeyBuilder.buildPopRetryTopicV1(topic, group); assertThat(KeyBuil...
@Override public int size() { return 0; }
@Test public void testIntSpliteratorForEachRemaining() { Set<Integer> results = new HashSet<>(); es.intSpliterator().forEachRemaining((IntConsumer) results::add); assertEquals(0, results.size()); }
static Object actualCoerceValue(DMNType requiredType, Object valueToCoerce) { Object toReturn = valueToCoerce; if (!requiredType.isCollection() && valueToCoerce instanceof Collection && ((Collection) valueToCoerce).size() == 1) { // spec defines that "a=[a]", i.e., singleton ...
@Test void actualCoerceValueCollectionToArray() { Object item = "TESTED_OBJECT"; Object value = Collections.singleton(item); DMNType requiredType = new SimpleTypeImpl("http://www.omg.org/spec/DMN/20180521/FEEL/", "string", ...
public final void setStrictness(Strictness strictness) { this.strictness = Objects.requireNonNull(strictness); }
@Test public void testNonFiniteFloatsWhenStrict() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteFloatsExceptions(jsonWriter); }
public static <T> String render(ClassPluginDocumentation<T> classPluginDocumentation) throws IOException { return render("task", JacksonMapper.toMap(classPluginDocumentation)); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void defaultBool() throws IOException { PluginScanner pluginScanner = new PluginScanner(ClassPluginDocumentationTest.class.getClassLoader()); RegisteredPlugin scan = pluginScanner.scan(); Class bash = scan.findClass(Subflow.class.getName...
@Override public void unsubscribeService(Service service, Subscriber subscriber, String clientId) { Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service); Client client = clientManager.getClient(clientId); checkClientIsLegal(client, clientId); ...
@Test void testUnSubscribeWhenClientPersistent() { assertThrows(NacosRuntimeException.class, () -> { Client persistentClient = new IpPortBasedClient(ipPortBasedClientId, false); when(clientManager.getClient(anyString())).thenReturn(persistentClient); // Excepted exception...
private PortDescription toPortDescription(HierarchicalConfiguration component) { try { return toPortDescriptionInternal(component); } catch (Exception e) { log.error("Unexpected exception parsing component {} on {}", component.getString("name"), ...
@Test public void testToPortDescription() throws ConfigurationException, IOException { // CHECKSTYLE:OFF String input = "<data>\n" + " <interfaces xmlns=\"http://openconfig.net/yang/interfaces\">\n" + " <interface>\n" + " <name>CARRIERCTP.1-L1-1</name...
public boolean isChild(final Path directory) { if(directory.isFile()) { // If a file we don't have any children at all return false; } return new SimplePathPredicate(this).isChild(new SimplePathPredicate(directory)); }
@Test public void testIsChild() { Path p = new Path("/a/t", EnumSet.of(Path.Type.file)); assertTrue(p.isChild(new Path("/a", EnumSet.of(Path.Type.directory)))); assertTrue(p.isChild(new Path("/", EnumSet.of(Path.Type.directory)))); assertFalse(p.isChild(new Path("/a", EnumSet.of(Path...
public static Builder<String, String> builder(String bootstrapServers, String... topics) { return new Builder<String, String>(bootstrapServers, topics).withStringDeserializers(); }
@Test public void testThrowsIfEnableAutoCommitIsSet() { Assertions.assertThrows(IllegalStateException.class, () -> KafkaSpoutConfig.builder("localhost:1234", "topic") .setProp(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true) .build()); }
@Override public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException { ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE); }
@Test void givenTypeCircleAndConfigWithCircleDefined_whenOnMsg_thenFalse() throws TbNodeException { // GIVEN var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration(); config.setFetchPerimeterInfoFromMessageMetadata(false); config.setPerimeterType(PerimeterType...
@Override public State state() { return task.state(); }
@Test public void shouldDelegateState() { final ReadOnlyTask readOnlyTask = new ReadOnlyTask(task); readOnlyTask.state(); verify(task).state(); }
public static String between(final String text, String after, String before) { String ret = after(text, after); if (ret == null) { return null; } return before(ret, before); }
@Test public void testBetween() { assertEquals("foo bar", StringHelper.between("Hello 'foo bar' how are you", "'", "'")); assertEquals("foo bar", StringHelper.between("Hello ${foo bar} how are you", "${", "}")); assertNull(StringHelper.between("Hello ${foo bar} how are you", "'", "'")); ...
public double calculateDensity(Graph graph, boolean isGraphDirected) { double result; double edgesCount = graph.getEdgeCount(); double nodesCount = graph.getNodeCount(); double multiplier = 1; if (!isGraphDirected) { multiplier = 2; } result = (multi...
@Test public void testNullGraphDensity() { GraphModel graphModel = GraphGenerator.generateNullUndirectedGraph(5); Graph graph = graphModel.getGraph(); GraphDensity d = new GraphDensity(); double density = d.calculateDensity(graph, false); assertEquals(density, 0.0); }
public RepositoryList getRepos(String serverUrl, String token, @Nullable String project, @Nullable String repo) { String projectOrEmpty = Optional.ofNullable(project).orElse(""); String repoOrEmpty = Optional.ofNullable(repo).orElse(""); HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/repos?projectn...
@Test public void get_repos() { server.enqueue(new MockResponse() .setHeader("Content-Type", "application/json;charset=UTF-8") .setBody("{\n" + " \"isLastPage\": true,\n" + " \"values\": [\n" + " {\n" + " \"slug\": \"banana\",\n" + " \"id\": 2,\n"...
public String getFormattedMessage() { if (formattedMessage != null) { return formattedMessage; } if (argumentArray != null) { formattedMessage = MessageFormatter.arrayFormat(message, argumentArray).getMessage(); } else { formattedMessage = message; ...
@Test public void testFormattingOneArg() { String message = "x={}"; Throwable throwable = null; Object[] argArray = new Object[] { 12 }; LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); assertNull(event.formattedMessage); a...
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testCleanupOptionalEmptyParams() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap("{'optional': {'type': 'STRING', 'internal_mode': 'OPTIONAL'}}"); Map<String, ParamDefinition> cleanedParams = ParamsMergeHelper.cleanupParams(allParams); a...
public static String toUriAuthority(NetworkEndpoint networkEndpoint) { return toHostAndPort(networkEndpoint).toString(); }
@Test public void toUriString_withHostnameAndPortEndpoint_returnsHostnameAndPort() { NetworkEndpoint hostnameAndPortEndpoint = NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.HOSTNAME_PORT) .setPort(Port.newBuilder().setPortNumber(8888)) .setHostname(Hostname...
@SuppressWarnings("checkstyle:magicnumber") @Nonnull public static String idToString(long id) { char[] buf = Arrays.copyOf(ID_TEMPLATE, ID_TEMPLATE.length); String hexStr = Long.toHexString(id); for (int i = hexStr.length() - 1, j = 18; i >= 0; i--, j--) { buf[j] = hexStr.cha...
@Test public void when_idToString() { assertEquals("0000-0000-0000-0000", idToString(0)); assertEquals("0000-0000-0000-0001", idToString(1)); assertEquals("7fff-ffff-ffff-ffff", idToString(Long.MAX_VALUE)); assertEquals("8000-0000-0000-0000", idToString(Long.MIN_VALUE)); asse...
@Override public void onHeartbeatSuccess(ConsumerGroupHeartbeatResponseData response) { if (response.errorCode() != Errors.NONE.code()) { String errorMessage = String.format( "Unexpected error in Heartbeat response. Expected no error, but received: %s", Er...
@Test public void testSameAssignmentReconciledAgainWhenFenced() { ConsumerMembershipManager membershipManager = createMemberInStableState(); Uuid topic1 = Uuid.randomUuid(); final Assignment assignment1 = new ConsumerGroupHeartbeatResponseData.Assignment(); final Assignment assignmen...
@Override public void register(@NonNull Scheme scheme) { if (!schemes.contains(scheme)) { indexSpecRegistry.indexFor(scheme); schemes.add(scheme); getWatchers().forEach(watcher -> watcher.onChange(new SchemeRegistered(scheme))); } }
@Test void shouldThrowExceptionWhenNoGvkAnnotation() { class WithoutGvkExtension extends AbstractExtension { } assertThrows(IllegalArgumentException.class, () -> schemeManager.register(WithoutGvkExtension.class)); }
public ConfigResponse resolveConfig(GetConfigRequest req, ConfigResponseFactory responseFactory) { long start = System.currentTimeMillis(); metricUpdater.incrementRequests(); ConfigKey<?> configKey = req.getConfigKey(); String defMd5 = req.getRequestDefMd5(); if (defMd5 == null |...
@Test public void require_that_known_config_defs_are_found() { handler.resolveConfig(createSimpleConfigRequest()); }
@CanIgnoreReturnValue public GsonBuilder setDateFormat(String pattern) { if (pattern != null) { try { new SimpleDateFormat(pattern); } catch (IllegalArgumentException e) { // Throw exception if it is an invalid date format throw new IllegalArgumentException("The date pattern '"...
@Test public void testSetDateFormatWithValidPattern() { GsonBuilder builder = new GsonBuilder(); String validPattern = "yyyy-MM-dd"; // Should not throw an exception builder.setDateFormat(validPattern); }
@Override public boolean match(Message msg, StreamRule rule) { if (msg.getField(rule.getField()) == null) return rule.getInverted(); try { final Pattern pattern = patternCache.get(rule.getValue()); final CharSequence charSequence = new InterruptibleCharSequence(m...
@Test public void testSuccessfulMatchInArray() { StreamRule rule = getSampleRule(); rule.setValue("foobar"); Message msg = getSampleMessage(); msg.addField("something", Collections.singleton("foobar")); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matche...
@Transactional public boolean block(ResourceId resourceId, TimeSlot timeSlot, Owner requester) { ResourceGroupedAvailability toBlock = findGrouped(resourceId, timeSlot); return block(requester, toBlock); }
@Test void cantBlockWhenNoSlotsCreated() { //given ResourceId resourceId = ResourceId.newOne(); TimeSlot oneDay = TimeSlot.createDailyTimeSlotAtUTC(2021, 1, 1); Owner owner = Owner.newOne(); //when boolean result = availabilityFacade.block(resourceId, oneDay, owner);...
@Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = ...
@Test public void testChronicleAddSingleCharge() { ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHRONICLE_ADD_SINGLE_CHARGE, "", 0); itemChargePlugin.onChatMessage(chatMessage); verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_CHRON...
public static CoderProvider fromStaticMethods(Class<?> rawType, Class<?> coderClazz) { checkArgument( Coder.class.isAssignableFrom(coderClazz), "%s is not a subtype of %s", coderClazz.getName(), Coder.class.getSimpleName()); return new CoderProviderFromStaticMethods(rawType, code...
@Test public void testIterableCoderProvider() throws Exception { TypeDescriptor<Iterable<Double>> type = TypeDescriptors.iterables(TypeDescriptors.doubles()); CoderProvider iterableCoderProvider = CoderProviders.fromStaticMethods(Iterable.class, IterableCoder.class); assertEquals( Iterabl...
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testSuccessfulDoubleMatchWithNegativeValue() { StreamRule rule = getSampleRule(); rule.setValue("-54354.42"); Message msg = getSampleMessage(); msg.addField("something", "-90000.12"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher...
public static Map<String, Object> compare(byte[] baselineImg, byte[] latestImg, Map<String, Object> options, Map<String, Object> defaultOptions) throws MismatchException { boolean allowScaling = toBool(defaultOptions.get("allowScaling")); ImageComparison im...
@Test void testScaleMismatch() { ImageComparison.MismatchException exception = assertThrows(ImageComparison.MismatchException.class, () -> ImageComparison.compare(R_1x1_IMG, R_2x2_IMG, opts(), opts())); assertTrue(exception.getMessage().contains("latest image dimensions != baseline ...
@Override public List<SimpleColumn> toColumns( final ParsedSchema schema, final SerdeFeatures serdeFeatures, final boolean isKey) { SerdeUtils.throwOnUnsupportedFeatures(serdeFeatures, format.supportedFeatures()); Schema connectSchema = connectSrTranslator.toConnectSchema(schema); if (...
@Test public void shouldPassConnectSchemaReturnedBySubclassToTranslator() { // When: translator.toColumns(parsedSchema, SerdeFeatures.of(), false); // Then: verify(connectKsqlTranslator).toKsqlSchema(connectSchema); }
@Override public List<Service> getServiceDefinitions() throws MockRepositoryImportException { List<Service> result = new ArrayList<>(); List<Element> interfaceNodes = getConfigDirectChildren(projectElement, "interface"); for (Element interfaceNode : interfaceNodes) { // Filter complete in...
@Test void testHelloAPIProjectImport() { SoapUIProjectImporter importer = null; try { importer = new SoapUIProjectImporter( "target/test-classes/io/github/microcks/util/soapui/HelloAPI-soapui-project.xml"); } catch (Exception e) { fail("Exception should not be throw...
public static GoPluginBundleDescriptor parseXML(InputStream pluginXml, BundleOrPluginFileDetails bundleOrPluginJarFile) throws IOException, JAXBException, XMLStreamException, SAXException { return parseXML(pluginXml, bundleOrPluginJarFile.file().getAbsolutePat...
@Test void shouldPerformPluginXsdValidationAndFailWhenVersionIsNotPresent() throws IOException { try (InputStream pluginXml = IOUtils.toInputStream("<go-plugin id=\"some\"></go-plugin>", StandardCharsets.UTF_8)) { JAXBException e = assertThrows(JAXBException.class, () -> GoPlugin...
@Deprecated public TransMeta getTransMeta( Repository rep, VariableSpace space ) throws KettleException { return getTransMeta( rep, null, space ); }
@Test public void testGetTransMeta() throws KettleException { String param1 = "param1"; String param2 = "param2"; String param3 = "param3"; String parentValue1 = "parentValue1"; String parentValue2 = "parentValue2"; String childValue3 = "childValue3"; JobEntryTrans jobEntryTrans = spy( ge...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseWindows10WithIeMobileLumia520Test() { final String uaStr = "Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537 "; final UserAgent ua = User...
@ApiOperation(value = "Create Device (saveDevice) with credentials ", notes = "Create or update the Device. When creating device, platform generates Device Id as " + UUID_WIKI_LINK + "Requires to provide the Device Credentials object as well as an existing device profile ID or use \"defa...
@Test public void testSaveDeviceWithCredentials() throws Exception { String testToken = "TEST_TOKEN"; Device device = new Device(); device.setName("My device"); device.setType("default"); DeviceCredentials deviceCredentials = new DeviceCredentials(); deviceCredentia...
public static DeletionTask convertProtoToDeletionTask( DeletionServiceDeleteTaskProto proto, DeletionService deletionService) { int taskId = proto.getId(); if (proto.hasTaskType() && proto.getTaskType() != null) { if (proto.getTaskType().equals(DeletionTaskType.FILE.name())) { LOG.debug("Con...
@Test public void testConvertProtoToDeletionTask() throws Exception { DeletionService deletionService = mock(DeletionService.class); DeletionServiceDeleteTaskProto.Builder protoBuilder = DeletionServiceDeleteTaskProto.newBuilder(); int id = 0; protoBuilder.setId(id); DeletionServiceDeleteT...
public synchronized boolean insertDocument(String tableName, Map<String, Object> document) { return insertDocuments(tableName, ImmutableList.of(document)); }
@Test public void testInsertDocumentsShouldThrowErrorWhenCassandraThrowsException() { doThrow(RejectedExecutionException.class) .when(cassandraClient) .execute(any(SimpleStatement.class)); assertThrows( CassandraResourceManagerException.class, () -> testManager.insertDocument...
public final void fail() { metadata().fail(ImmutableList.<Fact>of()); }
@Test public void failNoMessage() { expectFailure.whenTesting().fail(); assertThatFailure().hasMessageThat().isEmpty(); }
public static Config merge(Config config, Config fallback) { var root1 = config.root(); var root2 = fallback.root(); var origin = new ContainerConfigOrigin(config.origin(), fallback.origin()); var path = ConfigValuePath.root(); var newRoot = mergeObjects(origin, path, root1, roo...
@Test void testSubobjectsMerge() { var config1 = MapConfigFactory.fromMap(Map.of( "field1", Map.of( "f1", "v1", "f2", "v2" ) )); var config2 = MapConfigFactory.fromMap(Map.of( "field1", Map.of( "f2", "v3", ...
public static NamenodeRole convert(NamenodeRoleProto role) { switch (role) { case NAMENODE: return NamenodeRole.NAMENODE; case BACKUP: return NamenodeRole.BACKUP; case CHECKPOINT: return NamenodeRole.CHECKPOINT; } return null; }
@Test public void TestConvertDatanodeStorage() { DatanodeStorage dns1 = new DatanodeStorage( "id1", DatanodeStorage.State.NORMAL, StorageType.SSD); DatanodeStorageProto proto = PBHelperClient.convert(dns1); DatanodeStorage dns2 = PBHelperClient.convert(proto); compare(dns1, dns2); }
@Override public Mono<CategoryVo> getByName(String name) { return client.fetch(Category.class, name) .map(CategoryVo::from); }
@Test void getByName() throws JSONException { when(client.fetch(eq(Category.class), eq("hello"))) .thenReturn(Mono.just(category())); CategoryVo categoryVo = categoryFinder.getByName("hello").block(); categoryVo.getMetadata().setCreationTimestamp(null); JSONAssert.assertE...
@Override public ParseResult parsePath(String path) { String original = path; path = path.replace('/', '\\'); if (WORKING_DIR_WITH_DRIVE.matcher(path).matches()) { throw new InvalidPathException( original, "Jimfs does not currently support the Windows syntax for a relative path ...
@Test public void testWindows_uncPaths() { PathType windows = PathType.windows(); PathType.ParseResult path = windows.parsePath("\\\\host\\share"); assertParseResult(path, "\\\\host\\share\\"); path = windows.parsePath("\\\\HOST\\share\\foo\\bar"); assertParseResult(path, "\\\\HOST\\share\\", "fo...
public QueryParseResult parse(String sql, @Nonnull SqlSecurityContext ssc) { try { return parse0(sql, ssc); } catch (QueryException e) { throw e; } catch (Exception e) { String message; // Check particular type of exception which causes typical lon...
@Test public void when_multipleStatements_then_fails() { assertThatThrownBy(() -> parser.parse("SELECT * FROM t; SELECT * FROM t")) .isInstanceOf(QueryException.class) .hasMessage("The command must contain a single statement"); }
@Override public List<User> loadByIds(Collection<String> ids) { final HashSet<String> userIds = new HashSet<>(ids); final List<User> users = new ArrayList<>(); // special case for the locally defined user, we don't store that in MongoDB. if (!configuration.isRootUserDisabled() && us...
@Test @MongoDBFixtures("UserServiceImplTest.json") public void testLoadByUserIds() throws Exception { final List<User> users = userService.loadByIds(ImmutableSet.of( "54e3deadbeefdeadbeef0001", "54e3deadbeefdeadbeef0002", UserImpl.LocalAdminUser.LOCAL_ADMI...
public double distanceToAsDouble(final IGeoPoint other) { final double lat1 = DEG2RAD * getLatitude(); final double lat2 = DEG2RAD * other.getLatitude(); final double lon1 = DEG2RAD * getLongitude(); final double lon2 = DEG2RAD * other.getLongitude(); return RADIUS_EARTH_METERS *...
@Test public void test_distanceTo_Parallels() { final double ratioDelta = 1E-5; final int iterations = 100; for (int i = 0; i < iterations; i++) { final double latitude = getRandomLatitude(); final double longitude1 = getRandomLongitude(); final double lon...
public static String describe(List<org.apache.iceberg.expressions.Expression> exprs) { return exprs.stream().map(Spark3Util::describe).collect(Collectors.joining(", ")); }
@Test public void testDescribeSortOrder() { Schema schema = new Schema( required(1, "data", Types.StringType.get()), required(2, "time", Types.TimestampType.withoutZone())); Assert.assertEquals( "Sort order isn't correct.", "data DESC NULLS FIRST", Spar...
public List<Ce.Task> formatQueue(DbSession dbSession, List<CeQueueDto> dtos) { DtoCache cache = DtoCache.forQueueDtos(dbClient, dbSession, dtos); return dtos.stream().map(input -> formatQueue(input, cache)).toList(); }
@Test public void formatQueues() { CeQueueDto dto1 = new CeQueueDto(); dto1.setUuid("UUID1"); dto1.setTaskType("TYPE1"); dto1.setStatus(CeQueueDto.Status.IN_PROGRESS); dto1.setCreatedAt(1_450_000_000_000L); CeQueueDto dto2 = new CeQueueDto(); dto2.setUuid("UUID2"); dto2.setTaskType("T...
static Function<SeaTunnelRow, SeaTunnelRow> createKeyExtractor(int[] pkFields) { return row -> { Object[] fields = new Object[pkFields.length]; for (int i = 0; i < pkFields.length; i++) { fields[i] = row.getField(pkFields[i]); } SeaTunnelRow newRow...
@Test public void testKeyExtractor() { SeaTunnelRowType rowType = new SeaTunnelRowType( new String[] {"id", "name", "age"}, new SeaTunnelDataType[] { BasicType.INT_TYPE, BasicType.STRING_TYPE, BasicType.INT_TYPE ...
public Optional<EventProcessorStateDto> setState(EventProcessorStateDto dto) { return setState(dto.eventDefinitionId(), dto.minProcessedTimestamp(), dto.maxProcessedTimestamp()); }
@Test public void persistence() { final DateTime now = DateTime.now(DateTimeZone.UTC); final DateTime min = now.minusHours(1); final DateTime max = now; final EventProcessorStateDto stateDto = EventProcessorStateDto.builder() .eventDefinitionId("abc123") ...
protected Object getValidJMSHeaderValue(String headerName, Object headerValue) { if (headerValue instanceof String) { return headerValue; } else if (headerValue instanceof BigInteger) { return headerValue.toString(); } else if (headerValue instanceof BigDecimal) { ...
@Test public void testGetValidJmsHeaderValueWithDateShouldSucceed() { Object value = jmsBindingUnderTest.getValidJMSHeaderValue("foo", Date.from(instant)); assertNotNull(value); // We can't assert further as the returned value is bound to the machine time zone and locale }
@Override public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) { Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems); Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems); //remove comment and blank item map. ...
@Test public void testUpdateItem() { ItemChangeSets changeSets = resolver.resolve(1, "a=d", mockBaseItemHas3Key()); List<ItemDTO> updateItems = changeSets.getUpdateItems(); Assert.assertEquals(1, updateItems.size()); Assert.assertEquals("d", updateItems.get(0).getValue()); }
@Override public boolean authorize(P principal, String role, @Nullable ContainerRequestContext requestContext) { try (Timer.Context context = getsTimer.time()) { final AuthorizationContext<P> cacheKey = getAuthorizationContext(principal, role, requestContext); return Boolean.TRUE.equ...
@Test void cachesTheFirstReturnedPrincipal() throws Exception { assertThat(cached.authorize(principal, role, requestContext)).isTrue(); assertThat(cached.authorize(principal, role, requestContext)).isTrue(); verify(underlying, times(1)).authorize(principal, role, requestContext); }
public MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long now, OperationProgress operationProgress) throws NotEnoughValidWindowsEx...
@Test public void testTooManyFlaws() throws NotEnoughValidWindowsException { KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(getLoadMonitorProperties()); Metadata metadata = getMetadata(Collections.singleton(TP)); KafkaPartitionMetricSampleAggregator metricSampleAggregator = new Kaf...
@Override public AuthorityRuleConfiguration swapToObject(final YamlAuthorityRuleConfiguration yamlConfig) { Collection<ShardingSphereUser> users = yamlConfig.getUsers().stream().map(userSwapper::swapToObject).collect(Collectors.toList()); AlgorithmConfiguration provider = algorithmSwapper.swapToObje...
@Test void assertSwapToObject() { YamlAuthorityRuleConfiguration authorityRuleConfig = new YamlAuthorityRuleConfiguration(); authorityRuleConfig.setUsers(Collections.singletonList(getYamlUser())); authorityRuleConfig.setPrivilege(createYamlAlgorithmConfiguration()); authorityRuleConf...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testReadFieldsPojo() { String[] readFields = {"int2; string1"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); SemanticPropUtil.getSemanticPropsSingleFromString( sp, null, null, readFields, pojoType, threeIntTupleType); FieldSet fs...
@Override public boolean checkCredentials(String username, String password) { if (username == null || password == null) { return false; } Credentials credentials = new Credentials(username, password); if (validCredentialsCache.contains(credentials)) { return ...
@Test public void test_upperCase() throws Exception { String[] algorithms = new String[] {"SHA-1", "SHA-256", "SHA-512"}; for (String algorithm : algorithms) { String hash = hash(algorithm, VALID_PASSWORD, SALT).toUpperCase(); MessageDigestAuthenticator messageDigestAuthent...
@VisibleForTesting static List<Reporter> getReporters() { return self.reporters; }
@Test public void allReportersHiveConfig() throws Exception { String jsonFile = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "TestMetricsOutput.json"; Configuration conf = MetastoreConf.newMetastoreConf(); conf.set(MetastoreConf.ConfVars.HIVE_CODAHALE_METRICS_REPOR...
@Override public void processWatermark(Instant watermark, OpEmitter<OutT> emitter) { // propagate watermark immediately if no bundle is in progress and all the previous bundles have // completed. if (shouldProcessWatermark()) { LOG.debug("Propagating watermark: {} directly since no bundle in progres...
@Test public void testProcessWatermarkWhenBundleNotStarted() { Instant watermark = new Instant(); portableBundleManager = new PortableBundleManager<>(bundleProgressListener, 4, 1, bundleTimerScheduler, TIMER_ID); portableBundleManager.processWatermark(watermark, emitter); verify(bundleProgress...
@Override public void childEntriesWillBecomeVisible(final Entry submenu) { UserRole userRole = currentUserRole(); childEntriesWillBecomeVisible(submenu, userRole); }
@Test public void activatesSelectOnPopup_forCheckSelectionOnPopup() { Entry menuEntry = new Entry(); Entry actionEntry = new Entry(); menuEntry.addChild(actionEntry); final AFreeplaneAction someAction = Mockito.mock(AFreeplaneAction.class); when(someAction.checkSelectionOnPopup()).thenReturn(true); when(so...
public Properties apply(final Properties properties) { if (properties == null) { throw new IllegalArgumentException("properties must not be null"); } else { if (properties.isEmpty()) { return new Properties(); } else { final Properties filtered = new Properties(); for (...
@Test public void filtersMatchingKey() { // Given Properties properties = new Properties(); properties.put("one", 1); properties.put("two", 2); Set<String> removeOneKey = new HashSet<>(); removeOneKey.add("one"); Filter f = new Filter(removeOneKey); // When Properties filtered = f...
public Rule<ProjectNode> projectNodeRule() { return new PullUpExpressionInLambdaProjectNodeRule(); }
@Test public void testRegexpLikeExpression() { tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).projectNodeRule()) .setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true") .on(p -> { p.variable("expr", ...
public Pet getPetById(Long petId) throws RestClientException { return getPetByIdWithHttpInfo(petId).getBody(); }
@Test public void getPetByIdTest() { Long petId = null; Pet response = api.getPetById(petId); // TODO: test validations }
@Override public void run() { if (backgroundJobServer.isNotReadyToProcessJobs()) return; try (PeriodicTaskRunInfo runInfo = taskStatistics.startRun(backgroundJobServerConfiguration())) { tasks.forEach(task -> task.run(runInfo)); runInfo.markRunAsSucceeded(); } catch ...
@Test void jobHandlerDoesNothingIfItIsNotInitialized() { Task mockedTask = mock(Task.class); JobHandler jobHandler = createJobHandlerWithTask(mockedTask); when(backgroundJobServer.isNotReadyToProcessJobs()).thenReturn(true); jobHandler.run(); verifyNoInteractions(mockedTas...
public static boolean sortAndMerge(short[] array, short[] mergeArray, int pivotIndex, int toIndex, ShortComparator comparator) { if (array.length == 1) return false; sort(array, 0, pivotIndex, comparator); if (pivotIndex == toIndex || comparator.compare(array[pivotIndex - 1], array[pivotIndex]) ...
@Test void test_sortandmerge_returns_false_when_sort_is_in_place() { short[] array = {3, 2, 1, 0, 4, 5, 6}; short[] mergeArray = new short[array.length]; assertFalse(PrimitiveArraySorter.sortAndMerge(array, mergeArray, 4, 7, Short::compare)); assertIsSorted(array); array = n...
@SuppressWarnings("MethodLength") static void dissectControlRequest( final ArchiveEventCode eventCode, final MutableDirectBuffer buffer, final int offset, final StringBuilder builder) { int encodedLength = dissectLogHeader(CONTEXT, eventCode, buffer, offset, builder); ...
@Test void controlRequestListRecording() { internalEncodeLogHeader(buffer, 0, 32, 32, () -> 100_000_000L); final ListRecordingRequestEncoder requestEncoder = new ListRecordingRequestEncoder(); requestEncoder.wrapAndApplyHeader(buffer, LOG_HEADER_LENGTH, headerEncoder) .contro...
@Override public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer) { return aggregate(initializer, Materialized.with(null, null)); }
@Test public void shouldNotHaveNullInitializerTwoOptionMaterializedOnAggregate() { assertThrows(NullPointerException.class, () -> windowedCogroupedStream.aggregate(null, Materialized.as("test"))); }
@Override public Collection<RedisServer> slaves(NamedNode master) { List<Map<String, String>> slaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, master.getName()); return toRedisServersList(slaves); }
@Test public void testSlaves() { Collection<RedisServer> masters = connection.masters(); Collection<RedisServer> slaves = connection.slaves(masters.iterator().next()); assertThat(slaves).hasSize(2); }
@SuppressWarnings("NullAway") protected final @PolyNull V copyValue(@PolyNull Expirable<V> expirable) { if (expirable == null) { return null; } V copy = copier.copy(expirable.get(), cacheManager.getClassLoader()); return requireNonNull(copy); }
@Test public void copyValue_null() { assertThat(jcache.copyValue(null)).isNull(); }
public SearchQuery parse(String encodedQueryString) { if (Strings.isNullOrEmpty(encodedQueryString) || "*".equals(encodedQueryString)) { return new SearchQuery(encodedQueryString); } final var queryString = URLDecoder.decode(encodedQueryString, StandardCharsets.UTF_8); fina...
@Test void emptyFieldPrefixDoesNotChangeDefaultBehavior() { final SearchQueryParser parser = new SearchQueryParser("name", ImmutableSet.of("name", "breed"), ""); final SearchQuery searchQuery = parser.parse("Bobby breed:terrier"); final Multimap<String, SearchQueryParser.FieldValue> queryMa...