diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..47d127a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +insert_final_newline = true +end_of_line = lf + +[*.{kt,kts}] +indent_style = space +indent_size = 2 +max_line_length = 100 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 524f096..06bf5d0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,34 @@ -# Compiled class file -*.class +.gradle +.kotlin +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ -# Log file -*.log +### IntelliJ IDEA ### +.idea -# BlueJ files -*.ctxt +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ -# Mobile Tools for Java (J2ME) -.mtj.tmp/ +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar +### VS Code ### +.vscode/ -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -replay_pid* +### Mac OS ### +.DS_Store diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..6f678d2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "jsonpath-compliance-test-suite"] + path = src/test/resources/compliance-test-suite + url = git@github.com:jsonpath-standard/jsonpath-compliance-test-suite.git diff --git a/README.md b/README.md index cf4440d..151595c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ -# vertx-json-path +# Vert.x JSON Path + A complete implementation of the JSON Path Standard (RFC 9535) for use with Vert.x diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..81d05bb --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,137 @@ +import org.jetbrains.dokka.gradle.DokkaTask + +plugins { + kotlin("jvm") version "2.0.0" + + `java-library` + `maven-publish` + + id("org.jetbrains.kotlinx.kover") + id("org.sonarqube") version "3.5.0.2730" + + id("org.jetbrains.dokka") version "1.9.20" + + id("org.jlleitschuh.gradle.ktlint") +} + +group = "com.kobil.vertx" +version = "1.0.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +val arrowVersion: String by project +val caffeineVersion: String by project +val kotlinCoroutinesVersion: String by project +val vertxVersion: String by project + +val junitJupiterVersion: String by project +val kotestVersion: String by project +val kotestArrowVersion: String by project + +dependencies { + implementation(kotlin("stdlib-jdk8")) + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutinesVersion") + + implementation(platform("io.arrow-kt:arrow-stack:$arrowVersion")) + implementation("io.arrow-kt:arrow-core") + + implementation("com.github.ben-manes.caffeine:caffeine:$caffeineVersion") + + implementation(platform("io.vertx:vertx-stack-depchain:$vertxVersion")) + implementation("io.vertx:vertx-core") + implementation("io.vertx:vertx-lang-kotlin") + implementation("io.vertx:vertx-lang-kotlin-coroutines") + + testImplementation(platform("io.kotest:kotest-bom:$kotestVersion")) + testImplementation("io.kotest:kotest-runner-junit5") + testImplementation("io.kotest:kotest-assertions-core") + testImplementation("io.kotest:kotest-property") + testImplementation("io.kotest.extensions:kotest-assertions-arrow:$kotestArrowVersion") + + testImplementation("org.junit.jupiter:junit-jupiter:$junitJupiterVersion") +} + +tasks.test { + useJUnitPlatform() + + finalizedBy(tasks.koverHtmlReport, tasks.koverXmlReport) +} + +kotlin { + jvmToolchain(17) + + compilerOptions { + allWarningsAsErrors.set(true) + } +} + +java { + withSourcesJar() +} + +ktlint { + version.set("1.3.1") +} + +kover { + reports { + filters { + excludes { + classes("com.kobil.vertx.jsonpath.Build", "com.kobil.vertx.jsonpath.Compile") + } + } + } +} + +tasks.withType().configureEach { + suppressObviousFunctions.set(true) + failOnWarning.set(true) + + dokkaSourceSets.configureEach { + reportUndocumented.set(true) + } +} + +val dokkaJavadocJar: Jar by tasks.creating(Jar::class) { + group = "documentation" + + dependsOn(tasks.dokkaJavadoc) + from(tasks.dokkaJavadoc.flatMap { it.outputDirectory }) + archiveClassifier.set("javadoc") +} + +tasks.assemble.configure { + dependsOn(dokkaJavadocJar) +} + +val documentationElements: Configuration by configurations.creating { + outgoing { + artifact(dokkaJavadocJar) { + type = "jar" + classifier = "javadoc" + builtBy(dokkaJavadocJar) + } + } + + attributes { + attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category::class, Category.DOCUMENTATION)) + attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling::class, Bundling.EXTERNAL)) + attribute(DocsType.DOCS_TYPE_ATTRIBUTE, objects.named(DocsType::class, DocsType.JAVADOC)) + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class, Usage.JAVA_RUNTIME)) + } +} + +components.getByName("java") { + addVariantsFromConfiguration(documentationElements) {} +} + +publishing { + publications { + create("vertx-json-path") { + artifactId = "vertx-json-path" + from(components["java"]) + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..3a06f9c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,19 @@ +kotlin.code.style=official + +# Dependencies +arrowVersion=1.2.4 +caffeineVersion=3.1.8 +kotlinCoroutinesVersion=1.8.1 +vertxVersion=4.5.9 + +# Test Dependencies +junitJupiterVersion=5.11.2 + +kotestVersion=5.9.1 +kotestArrowVersion=1.4.0 + +# Tools +koverVersion=0.8.3 + +ktlintVersion=1.3.1 +ktlintGradleVersion=12.1.0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..63d9f7a --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Aug 19 14:04:19 CEST 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..f865bc1 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,21 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } + + val koverVersion: String by settings + val ktlintGradleVersion: String by settings + + plugins { + id("org.jetbrains.kotlinx.kover") version koverVersion + + id("org.jlleitschuh.gradle.ktlint") version ktlintGradleVersion + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} + +rootProject.name = "vertx-json-path" diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/ComparableExpression.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/ComparableExpression.kt new file mode 100644 index 0000000..711aecc --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/ComparableExpression.kt @@ -0,0 +1,172 @@ +package com.kobil.vertx.jsonpath + +/** + * The base interface for all expressions that may occur as operands of a comparison. + * + * It includes methods to build comparison expressions and some function expressions. One simple + * subclass is a [Literal] expression. + * + * @see FilterExpression.Comparison + * @see FunctionExpression + * @see QueryExpression + */ +sealed interface ComparableExpression { + /** + * Construct a [FilterExpression.Comparison] checking for equality of this expression and [other] + * + * @param other the right hand side of the comparison + * @return a '==' comparison + */ + infix fun eq(other: ComparableExpression): FilterExpression = isEqualTo(other) + + /** + * Construct a [FilterExpression.Comparison] checking for equality of this expression and [other] + * + * @param other the right hand side of the comparison + * @return a '==' comparison + */ + fun isEqualTo(other: ComparableExpression): FilterExpression = + FilterExpression.Comparison.eq(this, other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is not equal to [other] + * + * @param other the right hand side of the comparison + * @return a '!=' comparison + */ + infix fun neq(other: ComparableExpression): FilterExpression = isNotEqualTo(other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is not equal to [other] + * + * @param other the right hand side of the comparison + * @return a '!=' comparison + */ + fun isNotEqualTo(other: ComparableExpression): FilterExpression = + FilterExpression.Comparison.neq(this, other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is greater than [other] + * + * @param other the right hand side of the comparison + * @return a '>' comparison + */ + infix fun gt(other: ComparableExpression): FilterExpression = isGreaterThan(other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is greater than [other] + * + * @param other the right hand side of the comparison + * @return a '>' comparison + */ + fun isGreaterThan(other: ComparableExpression): FilterExpression = + FilterExpression.Comparison.greaterThan(this, other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is greater than or + * equal to [other] + * + * @param other the right hand side of the comparison + * @return a '>=' comparison + */ + infix fun ge(other: ComparableExpression): FilterExpression = isGreaterOrEqual(other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is greater than or + * equal to [other] + * + * @param other the right hand side of the comparison + * @return a '>=' comparison + */ + fun isGreaterOrEqual(other: ComparableExpression): FilterExpression = + FilterExpression.Comparison.greaterOrEqual(this, other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is less than [other] + * + * @param other the right hand side of the comparison + * @return a '<' comparison + */ + infix fun lt(other: ComparableExpression): FilterExpression = isLessThan(other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is less than [other] + * + * @param other the right hand side of the comparison + * @return a '<' comparison + */ + fun isLessThan(other: ComparableExpression): FilterExpression = + FilterExpression.Comparison.lessThan(this, other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is less than or equal + * to [other] + * + * @param other the right hand side of the comparison + * @return a '<=' comparison + */ + infix fun le(other: ComparableExpression): FilterExpression = isLessOrEqual(other) + + /** + * Construct a [FilterExpression.Comparison] checking that this expression is less than or equal + * to [other] + * + * @param other the right hand side of the comparison + * @return a '<=' comparison + */ + fun isLessOrEqual(other: ComparableExpression): FilterExpression = + FilterExpression.Comparison.lessOrEqual(this, other) + + /** + * Construct a [FunctionExpression.Length] that calculates the length of a string or size of a + * [io.vertx.core.json.JsonObject] or [io.vertx.core.json.JsonArray] + * + * @return a [FunctionExpression.Length] call taking this expression as the argument + */ + fun length(): ComparableExpression = FunctionExpression.Length(this) + + /** + * Construct a `match` function call that matches this expression to some regex [pattern]. Both + * operands may either be strings or singular query expressions (relative or absolute). The + * `match` function always matches the entire subject string. + * + * @see FilterExpression.Match + * @param pattern the expression specifying the pattern to match + * @return a `match` function expression using this as the subject and [pattern] as the pattern + */ + fun match(pattern: ComparableExpression): FilterExpression = + FilterExpression.Match(this, pattern, true) + + /** + * Construct a `search` function call that matches this expression to some regex [pattern]. Both + * operands may either be strings or singular query expressions (relative or absolute). The + * `search` function looks for a matching substring inside the subject string. + * + * @see FilterExpression.Match + * @param pattern the expression specifying the pattern to match + * @return a `search` function expression using this as the subject and [pattern] as the pattern + */ + fun search(pattern: ComparableExpression): FilterExpression = + FilterExpression.Match(this, pattern, false) + + /** + * A literal expression, which may be an integer, floating point number, string, + * boolean or `null`. + * + * @param value the literal value, can be any JSON value + */ + data class Literal( + val value: Any?, + ) : ComparableExpression { + /** + * Returns the literal value as a string. If the value itself is a string, it is enclosed in + * double quotes. + */ + override fun toString(): String = + when (value) { + null -> "null" + is String -> "\"$value\"" + else -> value.toString() + } + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/FilterExpression.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/FilterExpression.kt new file mode 100644 index 0000000..17bd163 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/FilterExpression.kt @@ -0,0 +1,379 @@ +package com.kobil.vertx.jsonpath + +import arrow.core.Either +import arrow.core.NonEmptyList +import arrow.core.nonEmptyListOf +import com.kobil.vertx.jsonpath.FilterExpression.Comparison.Op +import com.kobil.vertx.jsonpath.JsonNode.Companion.rootNode +import com.kobil.vertx.jsonpath.compiler.JsonPathCompiler +import com.kobil.vertx.jsonpath.error.JsonPathError +import com.kobil.vertx.jsonpath.interpreter.test +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject + +/** + * A base type for filter expressions which may be used in a filter selector, + * or on its own as a predicate. + */ +sealed class FilterExpression { + /** + * Tests whether this filter expression matches the given JSON object. + * + * @param obj the JSON object to match + * @return true, if the filter matches the object, false, otherwise + */ + fun test(obj: JsonObject): Boolean = test(obj.rootNode) + + /** + * Tests whether this filter expression matches the given JSON array. + * + * @param arr the JSON array to match + * @return true, if the filter matches the array, false, otherwise + */ + fun test(arr: JsonArray): Boolean = test(arr.rootNode) + + /** + * Constructs a filter expression testing that both, this expression and [other], are satisfied. + * This is equivalent to the '&&' operator in JSON Path. + * + * @param other the right hand operand of the '&&' operator + * @return the '&&' expression testing both operands + */ + infix fun and(other: FilterExpression): FilterExpression = + if (this is And && other is And) { + And(operands + other.operands) + } else if (this is And) { + And(operands + other) + } else if (other is And) { + And(NonEmptyList(this, other.operands.toList())) + } else { + And(nonEmptyListOf(this, other)) + } + + /** + * Constructs a filter expression testing that at least one of this expression and [other], + * is satisfied. This is equivalent to the '||' operator in JSON Path. + * + * @param other the right hand operand of the '||' operator + * @return the '||' expression testing that at least one operand is satisfied + */ + infix fun or(other: FilterExpression): FilterExpression = + if (this is Or && other is Or) { + Or(operands + other.operands) + } else if (this is Or) { + Or(operands + other) + } else if (other is Or) { + Or(NonEmptyList(this, other.operands.toList())) + } else { + Or(nonEmptyListOf(this, other)) + } + + /** + * Inverts this filter expression. This is equivalent to the '!' operator in JSON Path. + * + * @return the inverted filter expression + */ + operator fun not(): FilterExpression = + when (this) { + is Not -> operand + is Comparison -> copy(op = op.inverse) + else -> Not(this) + } + + /** + * A logical AND connection of the operands + * + * @param operands a non-empty list of operands + */ + data class And( + val operands: NonEmptyList, + ) : FilterExpression() { + /** + * An alternative constructor, taking the operands as varargs. + * + * @param firstOperand the first operand of '&&' + * @param secondOperand the second operand of '&&' + * @param moreOperands all remaining operands of '&&', if any + */ + constructor( + firstOperand: FilterExpression, + secondOperand: FilterExpression, + vararg moreOperands: FilterExpression, + ) : this( + nonEmptyListOf(firstOperand, secondOperand, *moreOperands), + ) + + /** + * Returns the JSON path representation of this And expression. + */ + override fun toString(): String = + operands.joinToString(" && ") { + if (it is Or) { + "($it)" + } else { + "$it" + } + } + } + + /** + * A logical Or connection of the operands + * + * @param operands a non-empty list of operands + */ + data class Or( + val operands: NonEmptyList, + ) : FilterExpression() { + /** + * An alternative constructor, taking the operands as varargs. + * + * @param firstOperand the first operand of '&&' + * @param secondOperand the second operand of '&&' + * @param moreOperands all remaining operands of '&&', if any + */ + constructor( + firstOperand: FilterExpression, + secondOperand: FilterExpression, + vararg moreOperands: FilterExpression, + ) : this( + nonEmptyListOf(firstOperand, secondOperand, *moreOperands), + ) + + /** + * Returns the JSON path representation of this Or expression. + */ + override fun toString(): String = operands.joinToString(" || ") + } + + /** + * The logical inversion of the operand. + * + * @param operand the operand that is inverted + */ + data class Not( + val operand: FilterExpression, + ) : FilterExpression() { + /** + * Returns the JSON path representation of this Not expression. + */ + override fun toString(): String = + if (operand is Comparison || operand is And || operand is Or) { + "!($operand)" + } else { + "!$operand" + } + } + + /** + * A comparison expression. + * + * @param op the comparison operator, see [Op] + * @param lhs the left hand operand of the comparison + * @param rhs the right hand operand of the comparison + */ + data class Comparison( + val op: Op, + val lhs: ComparableExpression, + val rhs: ComparableExpression, + ) : FilterExpression() { + /** + * A comparison operator. + * + * @param str the string representation of the operator + */ + enum class Op( + val str: String, + ) { + /** + * The '==' operator + */ + EQ("=="), + + /** + * The '"="=' operator + */ + NOT_EQ("!="), + + /** + * The '<' operator + */ + LESS("<"), + + /** + * The '<=' operator + */ + LESS_EQ("<="), + + /** + * The '>' operator + */ + GREATER(">"), + + /** + * The '>=' operator + */ + GREATER_EQ(">="), + ; + + /** + * The logical inverse of the operator + */ + val inverse: Op + get() = + when (this) { + EQ -> NOT_EQ + NOT_EQ -> EQ + LESS -> GREATER_EQ + LESS_EQ -> GREATER + GREATER -> LESS_EQ + GREATER_EQ -> LESS + } + } + + /** + * Returns the JSON path representation of this comparison expression. + */ + override fun toString(): String = "$lhs ${op.str} $rhs" + + /** + * Provides useful helper functions to construct comparison expressions. + */ + companion object { + /** + * Construct a [FilterExpression.Comparison] checking that [lhs] is equal to [rhs] + * + * @param lhs the left hand side of the comparison + * @param rhs the right hand side of the comparison + * @return a '==' comparison + */ + fun eq( + lhs: ComparableExpression, + rhs: ComparableExpression, + ): Comparison = Comparison(Op.EQ, lhs, rhs) + + /** + * Construct a [FilterExpression.Comparison] checking that [lhs] is not equal to [rhs] + * + * @param lhs the left hand side of the comparison + * @param rhs the right hand side of the comparison + * @return a '!=' comparison + */ + fun neq( + lhs: ComparableExpression, + rhs: ComparableExpression, + ): Comparison = Comparison(Op.NOT_EQ, lhs, rhs) + + /** + * Construct a [FilterExpression.Comparison] checking that [lhs] is greater than [rhs] + * + * @param lhs the left hand side of the comparison + * @param rhs the right hand side of the comparison + * @return a '>' comparison + */ + fun greaterThan( + lhs: ComparableExpression, + rhs: ComparableExpression, + ): Comparison = Comparison(Op.GREATER, lhs, rhs) + + /** + * Construct a [FilterExpression.Comparison] checking that [lhs] is greater than + * or equal to [rhs] + * + * @param lhs the left hand side of the comparison + * @param rhs the right hand side of the comparison + * @return a '>=' comparison + */ + fun greaterOrEqual( + lhs: ComparableExpression, + rhs: ComparableExpression, + ): Comparison = Comparison(Op.GREATER_EQ, lhs, rhs) + + /** + * Construct a [FilterExpression.Comparison] checking that [lhs] is less than [rhs] + * + * @param lhs the left hand side of the comparison + * @param rhs the right hand side of the comparison + * @return a '<' comparison + */ + fun lessThan( + lhs: ComparableExpression, + rhs: ComparableExpression, + ): Comparison = Comparison(Op.LESS, lhs, rhs) + + /** + * Construct a [FilterExpression.Comparison] checking that [lhs] is less than + * or equal to [rhs] + * + * @param lhs the left hand side of the comparison + * @param rhs the right hand side of the comparison + * @return a '<=' comparison + */ + fun lessOrEqual( + lhs: ComparableExpression, + rhs: ComparableExpression, + ): Comparison = Comparison(Op.LESS_EQ, lhs, rhs) + } + } + + /** + * A filter expression checking for the existence of any elements satisfying the query (or, + * generally, the node list expression). + * + * @param query the node list expression, most likely a [QueryExpression] + * @see [QueryExpression] + */ + data class Test( + val query: NodeListExpression, + ) : FilterExpression() { + /** + * Returns the JSON path representation of this Test expression, i.e. the serialized query + */ + override fun toString(): String = "$query" + } + + /** + * A filter expression that matches some string [subject] against some regex [pattern]. It may + * either require the entire subject or a substring of the subject to match the pattern. + * + * @param subject the subject, which must be an expression referring to a string + * (e.g. a [ComparableExpression.Literal] or a [QueryExpression] pointing to a string value) + * @param pattern the regex pattern, which must be an expression referring to a string + * (e.g. a [ComparableExpression.Literal] or a [QueryExpression] pointing to a string value) + * @param matchEntire whether the entire subject string should be matched. If false, the function + * looks for a matching substring. + */ + data class Match( + val subject: ComparableExpression, + val pattern: ComparableExpression, + val matchEntire: Boolean, + ) : FilterExpression() { + /** + * Returns the JSON path representation of this function expression. + */ + override fun toString(): String { + val name = if (matchEntire) "match" else "search" + + return "$name($subject, $pattern)" + } + } + + /** + * Contains static functions to construct filter expressions + */ + companion object { + /** + * Compiles a filter expression string. It will return an instance of [Either.Right] containing + * the compiled expression if the compilation was successful. Otherwise, an error wrapped in an + * instance of [Either.Left] is returned. + * + * Filter expression strings must not have a leading `?`. + * + * @param filterExpression the filter expression string without leading `?` + * @return the compiled filter expression, or an error + * @see JsonPathError + */ + @JvmStatic + fun compile(filterExpression: String): Either = + JsonPathCompiler.compileJsonPathFilter(filterExpression) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/FunctionExpression.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/FunctionExpression.kt new file mode 100644 index 0000000..7e77885 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/FunctionExpression.kt @@ -0,0 +1,56 @@ +package com.kobil.vertx.jsonpath + +/** + * An expression representing a JSON Path Function extension. It may appear as an operand in a + * [FilterExpression.Comparison]. + */ +sealed interface FunctionExpression : ComparableExpression { + /** + * The `length` function extension, returning the length of a string argument, the number of + * elements in a JSON array, or the number of entries in a JSON object. + * + * @param arg the argument to the function, e.g. a [ComparableExpression.Literal] + * or a [QueryExpression] + */ + data class Length( + val arg: ComparableExpression, + ) : FunctionExpression { + /** + * Returns the JSON path representation of this function expression. + */ + override fun toString(): String = "length($arg)" + } + + /** + * The `count` function extension, returning the length of the node list returned by the query. + * + * @param arg the argument to the function, a [NodeListExpression] + * @see NodeListExpression + * @see QueryExpression + */ + data class Count( + val arg: NodeListExpression, + ) : FunctionExpression { + /** + * Returns the JSON path representation of this function expression. + */ + override fun toString(): String = "count($arg)" + } + + /** + * The `value` function extension, returning the single item of the node list resulting from the + * query. If the query doesn't return exactly one node, the function will result in an error. + * + * @param arg the argument to the function, a [NodeListExpression] + * @see NodeListExpression + * @see QueryExpression + */ + data class Value( + val arg: NodeListExpression, + ) : FunctionExpression { + /** + * Returns the JSON path representation of this function expression. + */ + override fun toString(): String = "value($arg)" + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/JsonNode.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/JsonNode.kt new file mode 100644 index 0000000..ed07d47 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/JsonNode.kt @@ -0,0 +1,36 @@ +package com.kobil.vertx.jsonpath + +/** + * Any JSON value together with its position, expressed by a normalized [JsonPath]. + * + * @param value the JSON value + * @param path the position of the value, relative to the root document + * @see JsonPath + */ +data class JsonNode( + val value: Any?, + val path: JsonPath, +) { + /** + * Contains helpers to obtain certain JSON nodes + */ + companion object { + /** + * Wraps the given value into a JSON node at the root. + * + * @param value the JSON value + * @return a JSON node with the given [value] in root position + */ + @JvmStatic + fun root(value: Any?): JsonNode = JsonNode(value, JsonPath.ROOT) + + /** + * Wraps the given value into a JSON node at the root. + * + * @receiver the JSON value + * @return a JSON node with the given [value] in root position + */ + val Any?.rootNode: JsonNode + get() = root(this) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/JsonPath.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/JsonPath.kt new file mode 100644 index 0000000..411e7f2 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/JsonPath.kt @@ -0,0 +1,247 @@ +package com.kobil.vertx.jsonpath + +import arrow.core.Either +import arrow.core.None +import arrow.core.Option +import arrow.core.flatMap +import arrow.core.left +import arrow.core.right +import arrow.core.some +import com.kobil.vertx.jsonpath.JsonNode.Companion.rootNode +import com.kobil.vertx.jsonpath.compiler.JsonPathCompiler.compileJsonPathQuery +import com.kobil.vertx.jsonpath.error.JsonPathError +import com.kobil.vertx.jsonpath.error.MultipleResults +import com.kobil.vertx.jsonpath.error.RequiredJsonValueError +import com.kobil.vertx.jsonpath.interpreter.evaluate +import io.vertx.core.json.impl.JsonUtil + +/** + * A compiled representation of a JSON Path. + * + * @see Segment + * @see Selector + */ +data class JsonPath internal constructor( + override val segments: List = emptyList(), +) : JsonPathQuery { + /** + * Evaluates this JSON path query on the given [subject]. It returns a list of all nodes matching + * the JSON Path query. + * + * Results are returned as [JsonNode] instances, i.e. JSON values together with their position + * relative to [subject]. + * + * @param subject the subject to apply the query to + * @return the list of matching JSON nodes + * + * @see JsonNode + */ + fun evaluate(subject: Any?): List = + segments.evaluate(JsonUtil.wrapJsonValue(subject).rootNode) + + /** + * Evaluates this JSON path query on the given [subject], requiring that there is at most one + * result + * + * If there is exactly one result, an instance of [Either.Right] containing a [arrow.core.Some] + * wrapping the node. If there is no result, the [Either.Right] instance contains + * [arrow.core.None]. If there is more than one result, an [Either.Left] wrapping a + * [MultipleResults] error is returned. + * + * Results are returned as [JsonNode] instances, i.e. JSON values together with their position + * relative to [subject]. + * + * @param subject the subject to apply the query to + * @return the single matching JSON node, if any, or an error + * + * @see JsonNode + * @see MultipleResults + */ + fun evaluateOne(subject: Any?): Either> = + evaluate(subject).one() + + /** + * Evaluates this JSON path query on the given [subject]. It returns a list of all values of nodes + * matching the JSON Path query. + * + * @param subject the subject to apply the query to + * @return the list of matching JSON values + */ + @Suppress("UNCHECKED_CAST") + fun getAll(subject: Any?): List = evaluate(subject).onlyValues().map { it as T } + + /** + * Evaluates this JSON path query on the given [subject], requiring that there is at most one + * result. The result value is returned, if there is any. + * + * If there is exactly one result, an instance of [Either.Right] containing a [arrow.core.Some] + * wrapping the value. If there is no result, the [Either.Right] instance contains + * [arrow.core.None]. If there is more than one result, an [Either.Left] wrapping a + * [MultipleResults] error is returned. + * + * @param subject the subject to apply the query to + * @return the single matching JSON value, if any, or an error + * + * @see MultipleResults + */ + @Suppress("UNCHECKED_CAST") + fun getOne(subject: Any?): Either> = + evaluateOne(subject).map { maybeValue -> + maybeValue.map { it.value as T } + } + + /** + * Evaluates this JSON path query on the given [subject], requiring that there is at most one + * result. The result value is returned, if there is any. + * + * If there is exactly one result, an instance of [Either.Right] containing a [arrow.core.Some] + * wrapping the value. If there is no result, an [Either.Left] instance containing the + * [RequiredJsonValueError.NoResult] error is returned. If there is more than one result, an + * [Either.Left] wrapping a [MultipleResults] error is returned. + * + * @param subject the subject to apply the query to + * @return the single matching JSON value, if any, or an error + * + * @see MultipleResults + * @see RequiredJsonValueError + */ + @Suppress("UNCHECKED_CAST") + fun requireOne(subject: Any?): Either = + evaluateOne(subject).flatMap { maybeValue -> + maybeValue.fold( + { RequiredJsonValueError.NoResult.left() }, + { (it.value as T).right() }, + ) + } + + /** + * Evaluates this JSON path query on the given [subject], returning the positions of all matching + * nodes inside the JSON. The positions are expressed as normalized [JsonPath]s, i.e. JSON Paths + * only including simple name and index selectors. + * + * @param subject the subject to apply the query to + * @return the list of normalized [JsonPath] positions of matching nodes + */ + fun traceAll(subject: Any?): List = evaluate(subject).onlyPaths() + + /** + * Evaluates this JSON path query on the given [subject], requiring that there is at most one + * result. The position of the result is returned, if any. The position is expressed as a + * normalized [JsonPath], i.e. a JSON Paths only including simple name and index selectors. + * + * If there is exactly one result, an instance of [Either.Right] containing a [arrow.core.Some] + * wrapping the position. If there is no result, the [Either.Right] instance contains + * [arrow.core.None]. If there is more than one result, an [Either.Left] wrapping a + * [MultipleResults] error is returned. + * + * @param subject the subject to apply the query to + * @return the position of the single matching JSON node, if any, or an error + * + * @see MultipleResults + */ + fun traceOne(subject: Any?): Either> = + evaluateOne(subject).map { maybeValue -> maybeValue.map { it.path } } + + override fun plus(segment: Segment): JsonPath = JsonPath(segments + segment) + + override operator fun plus(additionalSegments: Iterable): JsonPath = + copy(segments = this.segments + additionalSegments) + + /** + * Serializes this JSON path to the corresponding string representation. + */ + override fun toString(): String = segments.joinToString("", prefix = "$") + + /** + * Contains various utilities to work with JSON Paths + */ + companion object { + /** + * The [JsonPath] referring to the root document, i.e. '$' + */ + @JvmField + val ROOT = JsonPath() + + /** + * Compiles a filter expression string. It will return an instance of [Either.Right] containing + * the compiled [JsonPath] if the compilation was successful. Otherwise, an error wrapped in an + * instance of [Either.Left] is returned. + * + * @param jsonPath the JSON Path string + * @return the compiled [JsonPath], or an error + * @see JsonPathError + */ + @JvmStatic + fun compile(jsonPath: String): Either = compileJsonPathQuery(jsonPath) + + private fun List.one(): Either> = + when (size) { + 0 -> None.right() + 1 -> first().some().right() + else -> MultipleResults(this).left() + } + + /** + * Only keeps the values from the list of results + * + * @receiver a list of [JsonNode] + * @return the list of values of the JSON nodes + * @see [JsonNode] + */ + fun List.onlyValues(): List = map(JsonNode::value) + + /** + * Only keeps the positions from the list of results + * + * @receiver a list of [JsonNode] + * @return the list of positions of the JSON nodes + * @see [JsonNode] + */ + fun List.onlyPaths(): List = map(JsonNode::path) + + /** + * Returns a JSON path with one child segment using the given selectors. + * + * @param selector the first selector + * @param more additional selectors to include, if any + * @return A [JsonPath], equivalent to $[selector, ...more] + * + * @see Segment.ChildSegment + * @See Selector + */ + operator fun get( + selector: Selector, + vararg more: Selector, + ): JsonPath = ROOT.get(selector, *more) + + /** + * Returns a JSON path with one child segment selecting the given field names. + * + * @param field the first field + * @param more additional fields to include, if any + * @return A [JsonPath], equivalent to $['field', ...'more'] + * + * @see Segment.ChildSegment + * @See Selector.Name + */ + operator fun get( + field: String, + vararg more: String, + ): JsonPath = ROOT.get(field, *more) + + /** + * Returns a JSON path with one child segment selecting the given indices. + * + * @param index the first index + * @param more additional indices to include, if any + * @return A [JsonPath], equivalent to $[index, ...more] + * + * @see Segment.ChildSegment + * @See Selector.Index + */ + operator fun get( + index: Int, + vararg more: Int, + ): JsonPath = ROOT.get(index, *more) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/JsonPathQuery.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/JsonPathQuery.kt new file mode 100644 index 0000000..f4b21d8 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/JsonPathQuery.kt @@ -0,0 +1,168 @@ +package com.kobil.vertx.jsonpath + +/** + * A base interface for query-like objects which consist of a sequence of [Segment]s. + * + * @param T the query type + * @see Segment + * @see Selector + */ +interface JsonPathQuery> { + /** + * The ordered segments of this query + */ + val segments: List + + /** + * Appends a child segment using the given selectors to the query. + * + * @param selector the first selector + * @param more additional selectors to include, if any + * @return a query with the [segments] of this query plus a new child segment + * + * @see Segment.ChildSegment + * @see Selector + */ + fun selectChildren( + selector: Selector, + vararg more: Selector, + ): T = this + Segment.ChildSegment(selector, *more) + + /** + * Appends a descendant segment using the given selectors to the query. + * + * @param selector the first selector + * @param more additional selectors to include, if any + * @return a query with the [segments] of this query plus a new descendant segment + * + * @see Segment.DescendantSegment + * @see Selector + */ + fun selectDescendants( + selector: Selector, + vararg more: Selector, + ): T = this + Segment.DescendantSegment(selector, *more) + + /** + * Appends a new wildcard child segment to the query. This selects all direct children of all + * currently selected nodes + * + * @return a query with the [segments] of this query plus a new wildcard child segment + * + * @see Segment.ChildSegment + * @see Selector.Wildcard + */ + fun selectAllChildren(): T = selectChildren(Selector.WILDCARD) + + /** + * Appends a new wildcard descendant segment to the query. This will select all currently selected + * nodes and all their descendants (direct and indirect child nodes) + * + * @return a query with the [segments] of this query plus a new wildcard descendant segment + * + * @see Segment.DescendantSegment + * @see Selector.Wildcard + */ + fun selectAllDescendants(): T = selectDescendants(Selector.WILDCARD) + + /** + * Selects one or multiple fields from the currently selected nodes. + * + * @param field the first field + * @param more additional fields to include, if any + * @return a query with the [segments] of this query plus a new child segment using name selectors + * + * @see Segment.ChildSegment + * @See Selector.Name + */ + fun field( + field: String, + vararg more: String, + ): T = this + Segment.ChildSegment(field, *more) + + /** + * Selects one or multiple indices from the currently selected nodes. + * + * @param index the first index + * @param more additional indices to include, if any + * @return a query with the [segments] of this query plus a new child segment + * using index selectors + * + * @see Segment.ChildSegment + * @See Selector.Index + */ + fun index( + index: Int, + vararg more: Int, + ): T = this + Segment.ChildSegment(index, *more) + + /** + * Appends the given segment to the query. + * + * @param segment the segment to append + * @return a query with the [segments] of this query plus [segment] + * + * @see Segment + */ + operator fun plus(segment: Segment): T + + /** + * Appends the given segments to the query. + * + * @param additionalSegments the segments to append + * @return a query with the [segments] of this query plus [additionalSegments] + * + * @see Segment + */ + operator fun plus(additionalSegments: Iterable): T +} + +/** + * Appends a child segment using the given selectors to the query. + * + * @receiver the query to append to + * @param selector the first selector + * @param more additional selectors to include, if any + * @return a query with the [JsonPathQuery.segments] of this query plus a new child segment + * + * @see Segment.ChildSegment + * @see Selector + */ +operator fun > T.get( + selector: Selector, + vararg more: Selector, +): T = selectChildren(selector, *more) + +/** + * Selects one or multiple fields from the currently selected nodes. + * + * @receiver the query to append to + * @param field the first field + * @param more additional fields to include, if any + * @return a query with the [JsonPathQuery.segments] of this query plus a new child segment + * using name selectors + * + * @see Segment.ChildSegment + * @See Selector.Name + */ +operator fun > T.get( + field: String, + vararg more: String, +): T = field(field, *more) + +/** + * Selects one or multiple indices from the currently selected nodes. + * + * @receiver the query to append to + * @param index the first index + * @param more additional indices to include, if any + * @return a query with the [JsonPathQuery.segments] of this query plus a new child segment + * using index selectors + * + * @see Segment.ChildSegment + * @See Selector.Index + */ +operator fun > T.get( + index: Int, + vararg more: Int, +): T = index(index, *more) diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/NodeListExpression.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/NodeListExpression.kt new file mode 100644 index 0000000..5577fea --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/NodeListExpression.kt @@ -0,0 +1,35 @@ +package com.kobil.vertx.jsonpath + +/** + * An expression that results in a node list. This may be a query expression or a function + * expression that returns a node list. + */ +sealed interface NodeListExpression : ComparableExpression { + /** + * Returns a test expression, testing for existence of any nodes matching + * this [NodeListExpression]. + * + * @return a test expression checking that the returned node list is non-empty + * + * @see FilterExpression.Test + */ + fun exists(): FilterExpression = FilterExpression.Test(this) + + /** + * Returns a `count` function expression using this [NodeListExpression] as the argument. + * + * @return the `count` function expression + * + * @see FunctionExpression.Count + */ + fun count(): ComparableExpression = FunctionExpression.Count(this) + + /** + * Returns a `value` function expression using this [NodeListExpression] as the argument. + * + * @return the `value` function expression + * + * @see FunctionExpression.Count + */ + fun value(): ComparableExpression = FunctionExpression.Value(this) +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/QueryExpression.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/QueryExpression.kt new file mode 100644 index 0000000..2565e88 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/QueryExpression.kt @@ -0,0 +1,152 @@ +package com.kobil.vertx.jsonpath + +/** + * A query expression, that is, a JSON Path query or a relative query which occurs as part of a + * [FilterExpression]. It may be used in test expressions (checking for existence), as an argument + * to function expressions, or as an operand in comparisons. + * + * @see NodeListExpression + * @see FilterExpression.Comparison + * @see FilterExpression.Match + * @see FunctionExpression + * + * @param T the concrete query type + */ +sealed interface QueryExpression> : + NodeListExpression, + JsonPathQuery { + /** + * Indicates whether the query is a singular query, that is, it contains only child segments with + * only one [Selector.Name] or [Selector.Index] selector each. + * + * @see Segment.ChildSegment + */ + val isSingular: Boolean + get() = segments.all { it.isSingular } + + /** + * A relative query, i.e. a JSON path expression starting with '@'. + * + * @param segments the segments of the query + * @see Segment + */ + data class Relative + @JvmOverloads + constructor( + override val segments: List = listOf(), + ) : QueryExpression { + /** + * An alternative varargs constructor + * + * @param firstSegment the first segment of the query + * @param more additional segments, if any + * @see Segment + */ + constructor(firstSegment: Segment, vararg more: Segment) : this(listOf(firstSegment, *more)) + + override operator fun plus(segment: Segment): Relative = copy(segments = segments + segment) + + override operator fun plus(additionalSegments: Iterable): Relative = + copy(segments = this.segments + additionalSegments) + + /** + * Serializes this query to the corresponding string representation + */ + override fun toString(): String = segments.joinToString("", prefix = "@") + } + + /** + * An absolute query, equivalent to a JSON Path. In the context of a [FilterExpression], it refers + * to the root document + * + * @param segments the segments of the query + * @see Segment + */ + data class Absolute + @JvmOverloads + constructor( + override val segments: List = listOf(), + ) : QueryExpression { + /** + * An alternative varargs constructor + * + * @param firstSegment the first segment of the query + * @param more additional segments, if any + * @see Segment + */ + constructor(firstSegment: Segment, vararg more: Segment) : this(listOf(firstSegment, *more)) + + override operator fun plus(segment: Segment): Absolute = copy(segments = segments + segment) + + override operator fun plus(additionalSegments: Iterable): Absolute = + copy(segments = this.segments + additionalSegments) + + /** + * Serializes this query to the corresponding string representation + */ + override fun toString(): String = segments.joinToString("", prefix = "$") + } + + /** + * Contains convenience factory functions + */ + companion object { + /** + * Returns a relative query with the given segments. + * + * @param segments the segments to use + * @return the relative query + * + * @see Segment + * @see Relative + */ + @JvmStatic + @JvmOverloads + fun relative(segments: List = listOf()): Relative = Relative(segments) + + /** + * Returns a relative query with the given segments. + * + * @param firstSegment the first segment of the query + * @param more additional segments, if any + * @return the relative query + * + * @see Segment + * @see Relative + */ + @JvmStatic + fun relative( + firstSegment: Segment, + vararg more: Segment, + ): Relative = Relative(firstSegment, *more) + + /** + * Returns an absolute query with the given segments. + * + * @param segments the segments to use + * @return the relative query + * + * @see Segment + * @see Absolute + */ + @JvmStatic + @JvmOverloads + fun absolute(segments: List = listOf()): Absolute = Absolute(segments) + + /** + * Returns an absolute query with the given segments. + * + * @param firstSegment the first segment of the query + * @param more additional segments, if any + * @return the absolute query + * + * @see Segment + * @see Absolute + */ + @JvmStatic + fun absolute( + firstSegment: Segment, + vararg more: Segment, + ): Absolute = Absolute(firstSegment, *more) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/Segment.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/Segment.kt new file mode 100644 index 0000000..29a3771 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/Segment.kt @@ -0,0 +1,202 @@ +package com.kobil.vertx.jsonpath + +/** + * A segment of a JSON path query. It includes [Selector]s, which are applied to the input JSON + * separately, concatenating the results. Segments may either be [ChildSegment] or + * [DescendantSegment], with the former only selecting direct descendants of the currently selected + * nodes and the latter selecting the current nodes and all direct or indirect descendants. + * + * @see Selector + */ +sealed interface Segment { + /** + * The selectors used by the segment + */ + val selectors: List + + /** + * Whether this segment selects at most one result + */ + val isSingular: Boolean + + /** + * A child segment selecting direct children of the currently selected nodes. + * + * @param selectors the selectors used by the segment + * + * @see Selector + */ + data class ChildSegment( + override val selectors: List, + ) : Segment { + init { + require(selectors.isNotEmpty()) { "A child segment without selectors is not allowed" } + } + + /** + * An alternative vararg constructor + * + * @param selector the first selector + * @param more additional selectors, if any + * + * @see Selector + */ + constructor(selector: Selector, vararg more: Selector) : this(listOf(selector, *more)) + + /** + * An alternative vararg constructor, allowing to specify only field names + * + * @param field the first field name to select + * @param more additional field names, if any + * + * @see Selector.Name + */ + constructor(field: String, vararg more: String) : this( + Selector.Name(field), + *more.map(Selector::Name).toTypedArray(), + ) + + /** + * An alternative vararg constructor, allowing to specify only indices + * + * @param index the first index to select + * @param more additional indices, if any + * + * @see Selector.Index + */ + constructor(index: Int, vararg more: Int) : this( + Selector.Index(index), + *more.map(Selector::Index).toTypedArray(), + ) + + override val isSingular: Boolean + get() = + selectors.size == 1 && + (selectors.first() is Selector.Name || selectors.first() is Selector.Index) + + /** + * Serializes this segment to the corresponding JSON path representation + */ + override fun toString(): String = selectors.joinToString(",", prefix = "[", postfix = "]") + } + + /** + * A descendant segment selecting direct and indirect children of the currently selected nodes. + * + * @param selectors the selectors used by the segment + * + * @see Selector + */ + data class DescendantSegment( + override val selectors: List, + ) : Segment { + init { + require(selectors.isNotEmpty()) { "A descendant segment without selectors is not allowed" } + } + + /** + * An alternative vararg constructor + * + * @param selector the first selector + * @param more additional selectors, if any + * + * @see Selector + */ + constructor(selector: Selector, vararg more: Selector) : this(listOf(selector, *more)) + + /** + * An alternative vararg constructor, allowing to specify only field names + * + * @param field the first field name to select + * @param more additional field names, if any + * + * @see Selector.Name + */ + constructor(field: String, vararg more: String) : this( + Selector.Name(field), + *more.map(Selector::Name).toTypedArray(), + ) + + /** + * An alternative vararg constructor, allowing to specify only indices + * + * @param index the first index to select + * @param more additional indices, if any + * + * @see Selector.Index + */ + constructor(index: Int, vararg more: Int) : this( + Selector.Index(index), + *more.map(Selector::Index).toTypedArray(), + ) + + override val isSingular: Boolean + get() = false + + /** + * Serializes this segment to the corresponding JSON path representation + */ + override fun toString(): String = selectors.joinToString(",", prefix = "..[", postfix = "]") + } + + /** + * Contains useful factory functions + */ + companion object { + /** + * Creates a new [ChildSegment] with the given selectors. + * + * @param selectors the selectors to use + * @return the child segment + * + * @see ChildSegment + * @see Selector + */ + @JvmStatic + fun child(selectors: List): Segment = ChildSegment(selectors) + + /** + * Creates a new [ChildSegment] with the given selectors. + * + * @param selector the first selector + * @param more additional selectors, if any + * @return the child segment + * + * @see ChildSegment + * @see Selector + */ + @JvmStatic + fun child( + selector: Selector, + vararg more: Selector, + ): Segment = ChildSegment(selector, *more) + + /** + * Creates a new [DescendantSegment] with the given selectors. + * + * @param selectors the selectors to use + * @return the descendant segment + * + * @see DescendantSegment + * @see Selector + */ + @JvmStatic + fun descendant(selectors: List): Segment = DescendantSegment(selectors) + + /** + * Creates a new [DescendantSegment] with the given selectors. + * + * @param selector the first selector + * @param more additional selectors, if any + * @return the descendant segment + * + * @see DescendantSegment + * @see Selector + */ + @JvmStatic + fun descendant( + selector: Selector, + vararg more: Selector, + ): Segment = DescendantSegment(selector, *more) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/Selector.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/Selector.kt new file mode 100644 index 0000000..9bce6ae --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/Selector.kt @@ -0,0 +1,234 @@ +package com.kobil.vertx.jsonpath + +/** + * A base interface for JSON Path selectors. + */ +sealed interface Selector { + /** + * A selector matching fields with a specific name. + * + * @param name the field name to select + */ + data class Name( + val name: String, + ) : Selector { + /** + * Serializes this selector to the corresponding JSON path representation + */ + override fun toString(): String = "'$name'" + } + + /** + * A selector matching everything. + */ + data object Wildcard : Selector { + /** + * Serializes this selector to the corresponding JSON path representation + */ + override fun toString(): String = "*" + } + + /** + * A selector matching items with a specific index. + * + * @param index the index to select + */ + data class Index( + val index: Int, + ) : Selector { + /** + * Serializes this selector to the corresponding JSON path representation + */ + override fun toString(): String = "$index" + } + + /** + * A selector matching a range of indices between [first] (inclusive) and [last] (exclusive) with + * a step size of [step]. For example, if `0 < first < last` and `step > 0`, then this selector + * will select `first + k * step < last` for all values of `k >= 0` satisfying the inequality. + * + * The [first] and [last] indices may be negative, which refers to the "`k`th-last" element of an + * array. For example, `-1` refers to the last element, `-2` refers to the second last element, + * and so on. The [step] may be negative to return elements in reverse order, if the [first] + * element is at a higher index than [last]. + * + * Each component may be `null`, which makes it use a default value: + * - [first]: the first element of the array in iteration order (if [step] is negative, this is + * the _last_ element of the array) + * - [last]: the index _after the last_ element of the array in iteration order (if [step] is + * negative, this is the _first_ element of the array) + * - [step]: Default 1 + * + * @param first the first index (inclusive) of the slice, may be null + * @param last the last index (exclusive) of the slice, may be null + * @param step the step size of the slice, may be null + */ + data class Slice( + val first: Int?, + val last: Int?, + val step: Int?, + ) : Selector { + /** + * Serializes this selector to the corresponding JSON path representation + */ + override fun toString(): String = + (first?.toString() ?: "") + ":" + (last?.toString() ?: "") + (step?.let { ":$it" } ?: "") + } + + /** + * A selector matching nodes for which the [filter] evaluates to `true`. + * + * @param filter the filter to apply to the candidates + */ + data class Filter( + val filter: FilterExpression, + ) : Selector { + /** + * Serializes this selector to the corresponding JSON path representation + */ + override fun toString(): String = "?$filter" + } + + /** + * Contains convenience factory methods + */ + companion object { + /** + * A selector matching everything. This is for Java users, in Kotlin it is equivalent to + * using [Wildcard]. + */ + @JvmField + val WILDCARD: Selector = Wildcard + + /** + * Constructor taking a field name and returning a [Name] selector. + * + * @param name field name to select + * @return an equivalent [Name] selector + * + * @see Name + */ + operator fun invoke(name: String): Selector = Name(name) + + /** + * Factory taking a field name and returning a [Name] selector. + * + * @param name field name to select + * @return an equivalent [Name] selector + * + * @see Name + */ + @JvmStatic + fun name(name: String): Selector = Selector(name) + + /** + * Constructor taking an index and returning an [Index] selector. + * + * @param index index to select + * @return an equivalent [Index] selector + * + * @see Index + */ + operator fun invoke(index: Int): Selector = Index(index) + + /** + * Factory taking an index and returning an [Index] selector. + * + * @param index index to select + * @return an equivalent [Index] selector + * + * @see Index + */ + @JvmStatic + fun index(index: Int): Selector = Selector(index) + + /** + * Constructor taking an [IntProgression] and returning a [Slice] selector selecting the indices + * contained in the progression. + * + * @param slice indices to select + * @return an equivalent [Slice] selector + * + * @see Slice + */ + operator fun invoke(slice: IntProgression): Selector = + if (slice.step >= 0) { + Slice(slice.first, slice.last + 1, slice.step) + } else { + Slice( + slice.first, + if (slice.last != 0) slice.last - 1 else null, + slice.step, + ) + } + + /** + * Factory taking an [IntProgression] and returning a [Slice] selector selecting the indices + * contained in the progression. + * + * @param slice indices to select + * @return an equivalent [Slice] selector + * + * @see Slice + */ + @JvmStatic + fun slice(slice: IntProgression): Selector = Selector(slice) + + /** + * Constructor taking the [first], [last] and [step] parameters and returning a [Slice] selector + * with the same parameters. + * + * @param firstInclusive the first index to include + * @param lastExclusive the first index to exclude + * @param step the step size + * @return an equivalent [Slice] selector + * + * @see Slice + */ + operator fun invoke( + firstInclusive: Int?, + lastExclusive: Int?, + step: Int? = null, + ): Selector = Slice(firstInclusive, lastExclusive, step) + + /** + * Factory taking the [first], [last] and [step] parameters and returning a [Slice] selector + * with the same parameters. + * + * @param firstInclusive the first index to include + * @param lastExclusive the first index to exclude + * @param step the step size + * @return an equivalent [Slice] selector + * + * @see Slice + */ + @JvmStatic + @JvmOverloads + fun slice( + firstInclusive: Int?, + lastExclusive: Int?, + step: Int? = null, + ): Selector = Selector(firstInclusive, lastExclusive, step) + + /** + * Constructor taking a filter expression and returning a [Filter] selector. + * + * @param filter the filter expression to apply + * @return an equivalent [Filter] selector + * + * @see Filter + */ + operator fun invoke(filter: FilterExpression): Selector = Filter(filter) + + /** + * Factory taking a filter expression and returning a [Filter] selector. + * + * @param filter the filter expression to apply + * @return an equivalent [Filter] selector + * + * @see Filter + */ + @JvmStatic + fun filter(filter: FilterExpression): Selector = Selector(filter) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/Vertx.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/Vertx.kt new file mode 100644 index 0000000..be830e9 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/Vertx.kt @@ -0,0 +1,125 @@ +package com.kobil.vertx.jsonpath + +import arrow.core.Either +import arrow.core.Option +import com.kobil.vertx.jsonpath.JsonPath.Companion.onlyValues +import com.kobil.vertx.jsonpath.error.MultipleResults +import com.kobil.vertx.jsonpath.error.RequiredJsonValueError +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject + +/** + * Queries the JSON object using the JSON path [path] and returns the single result, if any. If + * there are multiple results, an error is returned. + * + * @param path the JSON path query to use + * @return the result, if there is exactly one. None if there is no result. An error otherwise. + * + * @see JsonPath.getOne + */ +inline operator fun JsonObject.get(path: JsonPath): Either> = + path.getOne(this) + +/** + * Queries the JSON array using the JSON path [path] and returns the single result, if any. If + * there are multiple results, an error is returned. + * + * @param path the JSON path query to use + * @return the result, if there is exactly one. None if there is no result. An error otherwise. + * + * @see JsonPath.getOne + */ +inline operator fun JsonArray.get(path: JsonPath): Either> = + path.getOne(this) + +/** + * Queries the JSON object using the JSON path [path] and returns the single result. If + * there are multiple results, an error is returned. If there is no result, an error is returned. + * + * @param path the JSON path query to use + * @return the result, if there is exactly one. An error otherwise. + * + * @see JsonPath.requireOne + */ +inline fun JsonObject.required(path: JsonPath): Either = + path.requireOne(this) + +/** + * Queries the JSON array using the JSON path [path] and returns the single result. If + * there are multiple results, an error is returned. If there is no result, an error is returned. + * + * @param path the JSON path query to use + * @return the result, if there is exactly one. An error otherwise. + * + * @see JsonPath.requireOne + */ +inline fun JsonArray.required(path: JsonPath): Either = + path.requireOne(this) + +/** + * Queries the JSON object using the JSON path [path] and returns all results. + * + * @param path the JSON path query to use + * @return the results + * + * @see JsonPath.getAll + */ +inline fun JsonObject.getAll(path: JsonPath): List = + path.evaluate(this).onlyValues().map { it as T } + +/** + * Queries the JSON array using the JSON path [path] and returns all results. + * + * @param path the JSON path query to use + * @return the results + * + * @see JsonPath.getAll + */ +inline fun JsonArray.getAll(path: JsonPath): List = + path.evaluate(this).onlyValues().map { it as T } + +/** + * Queries the JSON object using the JSON path [path] and returns the position of the single result, + * if any. If there are multiple results, an error is returned. + * + * @param path the JSON path query to use + * @return the position of the result, if there is exactly one. None if there is no result. + * An error otherwise. + * + * @see JsonPath.traceOne + */ +fun JsonObject.traceOne(path: JsonPath): Either> = + path.traceOne(this) + +/** + * Queries the JSON array using the JSON path [path] and returns the position of the single result, + * if any. If there are multiple results, an error is returned. + * + * @param path the JSON path query to use + * @return the position of the result, if there is exactly one. None if there is no result. + * An error otherwise. + * + * @see JsonPath.traceOne + */ +fun JsonArray.traceOne(path: JsonPath): Either> = + path.traceOne(this) + +/** + * Queries the JSON object using the JSON path [path] and returns the positions of all results. + * + * @param path the JSON path query to use + * @return the positions of the results + * + * @see JsonPath.traceAll + */ +fun JsonObject.traceAll(path: JsonPath): List = path.traceAll(this) + +/** + * Queries the JSON object using the JSON path [path] and returns the positions of all results. + * + * @param path the JSON path query to use + * @return the positions of the results + * + * @see JsonPath.traceAll + */ +fun JsonArray.traceAll(path: JsonPath): List = path.traceAll(this) diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathCompiler.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathCompiler.kt new file mode 100644 index 0000000..499c54d --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathCompiler.kt @@ -0,0 +1,62 @@ +package com.kobil.vertx.jsonpath.compiler + +import arrow.core.Either +import com.github.benmanes.caffeine.cache.Caffeine +import com.github.benmanes.caffeine.cache.LoadingCache +import com.kobil.vertx.jsonpath.FilterExpression +import com.kobil.vertx.jsonpath.JsonPath +import com.kobil.vertx.jsonpath.error.JsonPathError + +/** + * An interface to the JSON Path compiler, caching results of compilation request. It backs the + * implementation of [JsonPath.compile] and [FilterExpression.compile]. + */ +object JsonPathCompiler { + private val queryCache: LoadingCache> = + Caffeine + .newBuilder() + .maximumSize(1_000) + .build { jsonPath -> jsonPath.scanTokens().parseJsonPathQuery() } + + private val filterCache: LoadingCache> = + Caffeine + .newBuilder() + .maximumSize(1_000) + .build { filterExpression -> filterExpression.scanTokens().parseJsonPathFilter() } + + /** + * Compiles a filter expression string. It will return an instance of [Either.Right] containing + * the compiled [JsonPath] if the compilation was successful. Otherwise, an error wrapped in an + * instance of [Either.Left] is returned. + * + * The result of up to 1000 compilations is cached for performance reasons. + * + * @param jsonPath the JSON Path string + * @return the compiled [JsonPath], or an error + * + * @see JsonPath.compile + * @see JsonPathError + */ + @JvmStatic + fun compileJsonPathQuery(jsonPath: String): Either = + queryCache.get(jsonPath) + + /** + * Compiles a filter expression string. It will return an instance of [Either.Right] containing + * the compiled expression if the compilation was successful. Otherwise, an error wrapped in an + * instance of [Either.Left] is returned. + * + * Filter expression strings must not have a leading `?`. + * + * The result of up to 1000 compilations is cached for performance reasons. + * + * @param filterExpression the filter expression string without leading `?` + * @return the compiled filter expression, or an error + * + * @see FilterExpression.compile + * @see JsonPathError + */ + @JvmStatic + fun compileJsonPathFilter(filterExpression: String): Either = + filterCache.get(filterExpression) +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathParser.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathParser.kt new file mode 100644 index 0000000..3455259 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathParser.kt @@ -0,0 +1,435 @@ +package com.kobil.vertx.jsonpath.compiler + +import arrow.core.Either +import arrow.core.nonEmptyListOf +import arrow.core.raise.Raise +import arrow.core.raise.either +import arrow.core.raise.ensure +import com.kobil.vertx.jsonpath.ComparableExpression +import com.kobil.vertx.jsonpath.FilterExpression +import com.kobil.vertx.jsonpath.FunctionExpression +import com.kobil.vertx.jsonpath.JsonPath +import com.kobil.vertx.jsonpath.NodeListExpression +import com.kobil.vertx.jsonpath.QueryExpression +import com.kobil.vertx.jsonpath.Segment +import com.kobil.vertx.jsonpath.Selector +import com.kobil.vertx.jsonpath.error.JsonPathError + +internal fun Sequence.parseJsonPathQuery(): Either = + either { + ParserState(iterator(), this).run { + require("JSON path query") + JsonPath(segments()) + } + } + +internal fun Sequence.parseJsonPathFilter() = + either { + ParserState(iterator(), this).filterExpr() + } + +private fun ParserState.filterExpr() = or() + +private fun ParserState.segments(): List = + buildList { + while (!isAtEnd()) { + skipWhiteSpace() + + val dot = takeIf() + + if (dot != null || advanceIf()) { + add(childSegment(dot != null)) + } else if (advanceIf()) { + add(descendantSegment()) + } else { + break + } + } + }.toList() + +private fun ParserState.childSegment(dottedSegment: Boolean): Segment = + Segment.ChildSegment(selectors(dottedSegment, "child")) + +private fun ParserState.descendantSegment(): Segment { + val dottedSegment = !advanceIf() + return Segment.DescendantSegment(selectors(dottedSegment, "descendant")) +} + +private fun ParserState.selectors( + dottedSegment: Boolean, + segmentType: String, +): List { + val selectors = mutableListOf() + + do { + if (!dottedSegment) skipWhiteSpace() + selectors.add(selector(dottedSegment)) + if (!dottedSegment) skipWhiteSpace() + } while (!dottedSegment && !isAtEnd() && advanceIf()) + + if (!dottedSegment) require("$segmentType segment") + + return selectors.toList() +} + +private fun ParserState.selector(dottedSegment: Boolean): Selector = + when (val t = advance()) { + is Token.Star -> Selector.Wildcard + + is Token.Str -> { + if (dottedSegment) { + illegalSelector( + t, + "Quoted name selectors are only allowed in bracketed segments", + ) + } + Selector.Name(unescape(t)) + } + + is Token.Identifier -> { + if (!dottedSegment) { + illegalSelector( + t, + "Unquoted name selectors are only allowed in dotted segments", + ) + } + Selector.Name(t.value) + } + + is Token.Integer -> { + if (dottedSegment) { + illegalSelector( + t, + "Index and slice selectors are only allowed in bracketed segments", + ) + } + + val start = checkInt(t) + val whitespace = takeIf() + + if (advanceIf()) { + skipWhiteSpace() + + // Slice Selector + val end = takeIf()?.let { checkInt(it) } + skipWhiteSpace() + + val step = + if (advanceIf()) { + skipWhiteSpace() + takeIf()?.let { checkInt(it) } + } else { + null + } + + Selector.Slice(start, end, step) + } else { + if (whitespace != null) raise(JsonPathError.UnexpectedToken(whitespace, "index selector")) + Selector.Index(start) + } + } + + is Token.Colon -> { + if (dottedSegment) { + illegalSelector( + t, + "Slice selectors are only allowed in bracketed segments", + ) + } + + skipWhiteSpace() + + // Slice Selector without explicit start + val end = takeIf()?.let { checkInt(it) } + + skipWhiteSpace() + + val step = + if (advanceIf()) takeIf()?.let { checkInt(it) } else null + + skipWhiteSpace() + + Selector.Slice(null, end, step) + } + + is Token.QuestionMark -> { + if (dottedSegment) { + illegalSelector( + t, + "Filter selectors are only allowed in bracketed segments", + ) + } + + skipWhiteSpace() + + // Filter Selector + Selector.Filter(filterExpr()) + } + + else -> unexpectedToken(t, "selector") + } + +private fun ParserState.checkInt(number: Token.Integer): Int { + ensure(!number.negative || number.value != 0) { + JsonPathError.IllegalCharacter( + '-', + number.line, + number.column, + "An index of -0 is not allowed", + ) + } + return number.value +} + +private fun ParserState.queryExpr(): Pair, Token> = + when (val t = advance()) { + is Token.At -> QueryExpression.Relative(segments()) to t + is Token.Dollar -> QueryExpression.Absolute(segments()) to t + else -> unexpectedToken(t, "query expression") + } + +private inline fun ParserState.functionExpr( + identifier: Token.Identifier, + parse: ParserState.() -> Pair, + constructor: (C) -> ComparableExpression, + requireSingular: Boolean = true, +): ComparableExpression { + require("${identifier.value} function expression") + skipWhiteSpace() + val expr = + constructor(parse().let { if (requireSingular) checkSingular(it) else it.first }) + skipWhiteSpace() + require("${identifier.value} function expression") + + return expr +} + +private fun ParserState.functionExpr(identifier: Token.Identifier): ComparableExpression = + when (val name = identifier.value) { + "length" -> functionExpr(identifier, { comparable() }, FunctionExpression::Length) + "count" -> + functionExpr(identifier, { + queryExpr() + }, FunctionExpression::Count, requireSingular = false) + + "value" -> + functionExpr(identifier, { + queryExpr() + }, FunctionExpression::Value, requireSingular = false) + + else -> raise(JsonPathError.UnknownFunction(name, identifier.line, identifier.column)) + } + +private fun ParserState.comparable(): Pair = + when (val t = advance()) { + is Token.Integer -> ComparableExpression.Literal(t.value) to t + is Token.Decimal -> ComparableExpression.Literal(t.value) to t + is Token.Str -> ComparableExpression.Literal(unescape(t)) to t + is Token.Identifier -> + when (t.value) { + "true" -> ComparableExpression.Literal(true) + "false" -> ComparableExpression.Literal(false) + "null" -> ComparableExpression.Literal(null) + else -> functionExpr(t) + } to t + + is Token.At -> QueryExpression.Relative(segments()) to t + is Token.Dollar -> QueryExpression.Absolute(segments()) to t + else -> unexpectedToken(t, "comparable expression") + } + +private fun ParserState.groupExpr(): FilterExpression { + require("parenthesized expression") + skipWhiteSpace() + val expr = filterExpr() + skipWhiteSpace() + require("parenthesized expression") + + return expr +} + +private fun ParserState.notExpr(): FilterExpression { + require("not expression") + skipWhiteSpace() + return FilterExpression.Not(basicLogicalExpr()) +} + +private fun ParserState.matchOrSearchFunction(): FilterExpression { + val identifier = require("basic logical expression") + val name = identifier.value + + require("$name function expression") + skipWhiteSpace() + val firstArg = checkSingular(comparable()) + + skipWhiteSpace() + require("$name function expression") + skipWhiteSpace() + + val secondArg = checkSingular(comparable()) + skipWhiteSpace() + require("$name function expression") + + return FilterExpression.Match(firstArg, secondArg, name == "match") +} + +private fun ParserState.basicLogicalExpr(): FilterExpression { + if (check()) { + return notExpr() + } else if (check()) { + return groupExpr() + } + + val matchOrSearch = (current as? Token.Identifier)?.takeIf { it.value in matchOrSearch } + + if (matchOrSearch != null) return matchOrSearchFunction() + + val (lhs, lhsToken) = comparable() + skipWhiteSpace() + val op = takeIf() + + if (op != null) { + skipWhiteSpace() + val (rhs, rhsToken) = comparable() + + return FilterExpression.Comparison( + op.operator, + checkSingular(lhs, lhsToken), + checkSingular(rhs, rhsToken), + ) + } + + return when (lhs) { + is NodeListExpression -> FilterExpression.Test(lhs) + is ComparableExpression.Literal -> + raise( + JsonPathError.UnexpectedToken(current!!, "basic logical expression"), + ) + + is FunctionExpression -> + raise( + JsonPathError.UnexpectedToken(current!!, "basic logical expression"), + ) + } +} + +private fun Raise.checkSingular( + expr: Pair, +): C = checkSingular(expr.first, expr.second) + +private fun Raise.checkSingular( + expr: C, + token: Token, +): C = + expr.apply { + if (this is QueryExpression<*> && + !isSingular + ) { + raise(JsonPathError.MustBeSingularQuery(token.line, token.column)) + } + } + +private fun ParserState.and(): FilterExpression { + var expr = basicLogicalExpr() + skipWhiteSpace() + + while (!isAtEnd() && advanceIf()) { + skipWhiteSpace() + val right = basicLogicalExpr() + + expr = + when (expr) { + is FilterExpression.And -> FilterExpression.And(expr.operands + right) + else -> FilterExpression.And(nonEmptyListOf(expr, right)) + } + skipWhiteSpace() + } + + return expr +} + +private fun ParserState.or(): FilterExpression { + var expr = and() + skipWhiteSpace() + + while (!isAtEnd() && advanceIf()) { + skipWhiteSpace() + + val right = and() + + expr = + when (expr) { + is FilterExpression.Or -> FilterExpression.Or(expr.operands + right) + else -> FilterExpression.Or(nonEmptyListOf(expr, right)) + } + + skipWhiteSpace() + } + + return expr +} + +private fun ParserState.skipWhiteSpace() { + while (advanceIf()) { + // Drop all whitespace tokens + } +} + +private fun ParserState.peek(): Token = + current ?: run { + val first = receiveToken() + current = first + first + } + +private fun ParserState.advance(): Token = + peek().also { + if (!isAtEnd()) current = receiveToken() + } + +private inline fun ParserState.advanceIf(): Boolean { + if (check()) { + advance() + return true + } + + return false +} + +private inline fun ParserState.takeIf(): T? { + if (check()) { + return advance() as T + } + + return null +} + +private inline fun ParserState.require(parsing: String): T = + takeIf() ?: unexpectedToken(peek(), parsing) + +private inline fun ParserState.check(): Boolean = peek() is T + +private fun ParserState.isAtEnd(): Boolean = check() + +private class ParserState( + tokens: Iterator>, + raise: Raise, + var current: Token? = null, +) : Raise by raise, + Iterator> by tokens { + fun receiveToken(): Token = next().bind() +} + +private fun ParserState.unexpectedToken( + token: Token, + parsing: String, +): Nothing { + raise(JsonPathError.UnexpectedToken(token, parsing)) +} + +private fun ParserState.illegalSelector( + token: Token, + reason: String, +): Nothing = raise(JsonPathError.IllegalSelector(token.line, token.column, reason)) + +private val matchOrSearch = setOf("match", "search") diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathScanner.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathScanner.kt new file mode 100644 index 0000000..90fc800 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathScanner.kt @@ -0,0 +1,322 @@ +package com.kobil.vertx.jsonpath.compiler + +import arrow.core.Either +import arrow.core.left +import arrow.core.raise.Raise +import arrow.core.raise.recover +import arrow.core.right +import com.kobil.vertx.jsonpath.error.JsonPathError + +internal typealias TokenEvent = Either + +internal fun String.scanTokens(): Sequence = + sequence { + recover( + block = { + val scannerState = ScannerState(this@scanTokens, this) + + if (firstOrNull() in whitespaceChar) { + this.raise( + JsonPathError.IllegalCharacter( + this@scanTokens[0], + 1U, + 1U, + "Leading whitespace is disallowed", + ), + ) + } + + while (scannerState.current < uLength) { + scannerState.start = scannerState.current + scannerState.startLine = scannerState.line + scannerState.startColumn = scannerState.column + yield(scannerState.scanToken().right()) + } + + if (lastOrNull() in whitespaceChar) { + this.raise( + JsonPathError.IllegalCharacter( + last(), + scannerState.line, + scannerState.column - 1U, + "Trailing whitespace is disallowed", + ), + ) + } + + scannerState.start = scannerState.current + + yield(Token.Eof(scannerState.line, scannerState.column).right()) + }, + recover = { + yield(it.left()) + }, + ) + } + +private fun ScannerState.scanToken(): Token = + when (val ch = advance()) { + // Simple one-character tokens + '$' -> Token.Dollar(line, column) + '@' -> Token.At(line, column) + ',' -> Token.Comma(line, column) + '*' -> Token.Star(line, column) + ':' -> Token.Colon(line, column) + '?' -> Token.QuestionMark(line, column) + '[' -> Token.LeftBracket(line, column) + ']' -> Token.RightBracket(line, column) + '(' -> Token.LeftParen(line, column) + ')' -> Token.RightParen(line, column) + + // Potential two-character tokens + '.' -> match('.', { Token.DotDot(line, column) }, { Token.Dot(line, column) }) + '!' -> match('=', { Token.BangEq(line, column) }, { Token.Bang(line, column) }) + '<' -> match('=', { Token.LessEq(line, column) }, { Token.Less(line, column) }) + '>' -> match('=', { Token.GreaterEq(line, column) }, { Token.Greater(line, column) }) + + // Two-character tokens + '=' -> expect('=') { Token.EqEq(line, column) } + '&' -> expect('&') { Token.AndAnd(line, column) } + '|' -> expect('|') { Token.PipePipe(line, column) } + + // Numbers + in '0'..'9', '-' -> scanNumber(ch) + + // Strings + '\'', '\"' -> scanQuotedString(ch) + + // Potential name shorthand + in 'A'..'Z', in 'a'..'z', '_', in '\u0080'..'\ud7ff', in '\ue000'..'\uffff' -> + scanIdentifier() + + ' ', '\t', '\r' -> scanWhitespace(line, column) + '\n' -> { + val l = line + val c = column + + newLine() + scanWhitespace(l, c) + } + + else -> + raise( + JsonPathError.IllegalCharacter( + ch, + line, + column - 1U, + "Character not allowed in JSON Path", + ), + ) + } + +private fun ScannerState.scanNumber(first: Char): Token { + val negative = first == '-' + + when { + negative && !expr[current].isDigit() -> + raise( + JsonPathError.IllegalCharacter( + expr[current], + line, + column, + "Expecting an integer part after '-'", + ), + ) + + first == '0' && !isAtEnd() && expr[current].isDigit() -> + raise( + JsonPathError.IllegalCharacter( + expr[current], + line, + column - 1U, + "Leading zeroes in numbers are not allowed", + ), + ) + + first == '-' && !isAtEnd(1U) && expr[current] == '0' && expr[current + 1U].isDigit() -> + raise( + JsonPathError.IllegalCharacter( + expr[current], + line, + column, + "Leading zeroes in numbers are not allowed", + ), + ) + } + + while (!isAtEnd() && expr[current].isDigit()) advance() + + if (!isAtEnd(1U) && expr[current] == '.' && expr[current + 1U].isDigit()) { + return scanDecimalPart() + } + + if (!isAtEnd(2U) && hasExponent) { + return scanScientificNotation() + } + + val strValue = expr.substring(start..= expr.uLength + +private fun ScannerState.advance(): Char = expr[current++] + +private fun ScannerState.advanceIf(next: Char): Boolean = + if (!isAtEnd() && expr[current] == next) { + true.also { current++ } + } else { + false + } + +private fun ScannerState.match( + next: Char, + ifMatch: () -> Token, + ifNoMatch: () -> Token, +): Token = if (advanceIf(next)) ifMatch() else ifNoMatch() + +private fun ScannerState.expect( + next: Char, + ifMatch: () -> Token, +): Token = + if (advanceIf(next)) { + ifMatch() + } else if (isAtEnd()) { + raise(JsonPathError.UnexpectedEof("'$next'", line, column)) + } else { + raise(JsonPathError.IllegalCharacter(expr[current], line, column, "Expected '$next'")) + } + +private fun ScannerState.newLine() { + line++ + currentLineStart = current +} + +private val ScannerState.column: UInt + get() = start - currentLineStart + 1U + +private operator fun String.get(idx: UInt): Char = this[idx.toInt()] + +private fun String.substring(range: UIntRange): String = + substring(range.first.toInt()..range.last.toInt()) + +private val String.uLength: UInt + get() = length.toUInt() + +private class ScannerState( + var expr: String, + raise: Raise, + var start: UInt = 0U, + var current: UInt = 0U, + var line: UInt = 1U, + var currentLineStart: UInt = 0U, + var startLine: UInt = 1U, + var startColumn: UInt = 1U, +) : Raise by raise + +private val identifierChar = + ('A'..'Z').toSet() + ('a'..'z') + '_' + ('\u0080'..'\ud7ff') + ('\ue000'..'\uffff') + + ('0'..'9') +private val whitespaceChar = setOf(' ', '\t', '\n', '\r') +private val plusMinus = setOf('+', '-') +private val exponent = setOf('e', 'E') diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/Strings.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/Strings.kt new file mode 100644 index 0000000..55a52ac --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/Strings.kt @@ -0,0 +1,80 @@ +package com.kobil.vertx.jsonpath.compiler + +import arrow.core.raise.Raise +import com.kobil.vertx.jsonpath.error.JsonPathError +import java.nio.charset.StandardCharsets + +private val INVALID_ESCAPE = """(?u[a-fA-F0-9]{4}|[btnfr'"/\\]))""".toRegex() +private val CONTROL_CHARACTER = """[\u0000-\u001F]""".toRegex() +private val INVALID_SURROGATE_PAIR = + """(?>\\u[Dd][89aAbB][0-9a-fA-F]{2}(?!\\u[Dd][CcDdEeFf][0-9a-fA-F]{2}))""".toRegex() +private val LONE_LOW_SURROGATE = + """(?>(?.unescape(rawName: Token.Str): String { + check(rawName, INVALID_ESCAPE) { "Invalid escape sequence" } + check(rawName, INVALID_SURROGATE_PAIR) { + "A unicode high surrogate must be followed by a low surrogate" + } + check(rawName, LONE_LOW_SURROGATE) { + "A unicode low surrogate must be preceded by a high surrogate" + } + check(rawName, CONTROL_CHARACTER) { "Control characters (U+0000 to U+001F) are disallowed" } + + return rawName + .value + .replace("\\b", "\b") + .replace("\\t", "\t") + .replace("\\n", "\n") + .replace("\\f", "\u000c") + .replace("\\r", "\r") + .replace("\\\"", "\"") + .replace("\\'", "'") + .replace("\\/", "/") + .unescapeUnicode() + .replace("\\\\", "\\") +} + +@OptIn(ExperimentalStdlibApi::class) +private fun String.unescapeUnicode(): String { + var result = this + var match = UNICODE_SEQUENCE.find(result) + + while (match != null) { + val sequence = match.value + + val decoded = + sequence + .replace("\\u", "") + .lowercase() + .hexToByteArray() + .toString(StandardCharsets.UTF_16) + + result = + result.substring(0...check( + rawName: Token.Str, + regex: Regex, + reason: () -> String, +) { + regex.find(rawName.value)?.let { + raise( + JsonPathError.InvalidEscapeSequence( + rawName.value, + rawName.line, + rawName.column, + it.range.first.toUInt(), + reason(), + ), + ) + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/Token.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/Token.kt new file mode 100644 index 0000000..20858f4 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/compiler/Token.kt @@ -0,0 +1,181 @@ +package com.kobil.vertx.jsonpath.compiler + +import com.kobil.vertx.jsonpath.FilterExpression + +internal sealed interface Token { + val line: UInt + val column: UInt + val name: String + get() = this::class.simpleName!! + + sealed interface ComparisonOperator { + val operator: FilterExpression.Comparison.Op + } + + sealed interface Value { + val value: T + } + + data class Whitespace( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Eof( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Dollar( + override val line: UInt, + override val column: UInt, + ) : Token + + data class At( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Comma( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Star( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Colon( + override val line: UInt, + override val column: UInt, + ) : Token + + data class QuestionMark( + override val line: UInt, + override val column: UInt, + ) : Token + + data class LeftBracket( + override val line: UInt, + override val column: UInt, + ) : Token + + data class RightBracket( + override val line: UInt, + override val column: UInt, + ) : Token + + data class LeftParen( + override val line: UInt, + override val column: UInt, + ) : Token + + data class RightParen( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Dot( + override val line: UInt, + override val column: UInt, + ) : Token + + data class DotDot( + override val line: UInt, + override val column: UInt, + ) : Token + + data class EqEq( + override val line: UInt, + override val column: UInt, + ) : Token, + ComparisonOperator { + override val operator: FilterExpression.Comparison.Op = FilterExpression.Comparison.Op.EQ + } + + data class Bang( + override val line: UInt, + override val column: UInt, + ) : Token + + data class BangEq( + override val line: UInt, + override val column: UInt, + ) : Token, + ComparisonOperator { + override val operator: FilterExpression.Comparison.Op = FilterExpression.Comparison.Op.NOT_EQ + } + + data class Less( + override val line: UInt, + override val column: UInt, + ) : Token, + ComparisonOperator { + override val operator: FilterExpression.Comparison.Op = FilterExpression.Comparison.Op.LESS + } + + data class LessEq( + override val line: UInt, + override val column: UInt, + ) : Token, + ComparisonOperator { + override val operator: FilterExpression.Comparison.Op = FilterExpression.Comparison.Op.LESS_EQ + } + + data class Greater( + override val line: UInt, + override val column: UInt, + ) : Token, + ComparisonOperator { + override val operator: FilterExpression.Comparison.Op = FilterExpression.Comparison.Op.GREATER + } + + data class GreaterEq( + override val line: UInt, + override val column: UInt, + ) : Token, + ComparisonOperator { + override val operator: FilterExpression.Comparison.Op = + FilterExpression.Comparison.Op.GREATER_EQ + } + + data class AndAnd( + override val line: UInt, + override val column: UInt, + ) : Token + + data class PipePipe( + override val line: UInt, + override val column: UInt, + ) : Token + + data class Str( + override val line: UInt, + override val column: UInt, + override val value: String, + ) : Token, + Value + + data class Integer( + override val line: UInt, + override val column: UInt, + val negative: Boolean, + override val value: Int, + ) : Token, + Value + + data class Decimal( + override val line: UInt, + override val column: UInt, + override val value: Double, + ) : Token, + Value + + data class Identifier( + override val line: UInt, + override val column: UInt, + override val value: String, + ) : Token, + Value +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/error/JsonPathError.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/error/JsonPathError.kt new file mode 100644 index 0000000..9e8575d --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/error/JsonPathError.kt @@ -0,0 +1,237 @@ +package com.kobil.vertx.jsonpath.error + +import com.kobil.vertx.jsonpath.compiler.Token +import kotlinx.coroutines.CancellationException + +/** + * The base type for JSON Path compiler errors. + */ +sealed interface JsonPathError { + /** + * The input (JSON Path string) ended unexpectedly. + * + * @param expected the expected element when the EOF occurred + * @param line the line number at which the string ended + * @param column the column number within the line at which the string ended + */ + data class UnexpectedEof( + val expected: String, + val line: UInt, + val column: UInt, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${messagePrefix(line, column)}: Premature end of input, expected $expected" + } + + /** + * The compiler encountered a character in the input string that was invalid in the current + * context. + * + * @param char the illegal character + * @param line the line of the invalid character + * @param column the column of the invalid character + * @param reason information why the character was invalid + */ + data class IllegalCharacter( + val char: Char, + val line: UInt, + val column: UInt, + val reason: String, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${messagePrefix(line, column)}: Illegal character '$char' ($reason)" + } + + /** + * Some quoted string was missing the closing quote. + * + * @param line the line where the error was detected + * @param column the column where the error was detected + * @param startLine the line where the opening quote was located + * @param startColumn the column where the opening quote was located + */ + data class UnterminatedString( + val line: UInt, + val column: UInt, + val startLine: UInt, + val startColumn: UInt, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${ + messagePrefix( + line, + column, + ) + }: Unterminated string literal starting at [$startLine:$startColumn]" + } + + /** + * An integer value outside the supported interval of -2^31..2^31 - 1 was encountered. While the + * JSON Path specification allows indices to be 48 bit integers, this isn't possible in Java. + * + * @param string the string representation of the integer + * @param line the line where the integer is located + * @param column the column where the integer is located + */ + data class IntOutOfBounds( + val string: String, + val line: UInt, + val column: UInt, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${ + messagePrefix( + line, + column, + ) + }: Invalid integer value (Out of bounds)" + } + + /** + * An unexpected token was encountered in the current context. + * + * @param token a readable name of the token + * @param line the starting line of the token + * @param column the starting column of the token + * @param context the current parsing context when the error occurred + */ + data class UnexpectedToken( + val token: String, + val line: UInt, + val column: UInt, + val context: String, + ) : JsonPathError { + internal constructor(token: Token, parsing: String) : this( + token.name, + token.line, + token.column, + parsing, + ) + + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${ + messagePrefix( + line, + column, + ) + }: Unexpected token '$token' while parsing $context" + } + + /** + * An illegal selector was encountered. This could be an index or slice selector in a dotted + * segment or a non-quoted string in a bracketed segment. + * + * @param line the line at which the error was detected + * @param column the column at which the error was detected + * @param reason a more detailed description of the error + */ + data class IllegalSelector( + val line: UInt, + val column: UInt, + val reason: String, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = "${messagePrefix(line, column)}: Illegal selector ($reason)" + } + + /** + * The compiler encountered a function extension that was unknown. + * + * @param name the name of the unknown function + * @param line the line at which the unknown function occurred + * @param column the column at which the unknown function occurred + */ + data class UnknownFunction( + val name: String, + val line: UInt, + val column: UInt, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${messagePrefix(line, column)}: Unknown function extension '$name'" + } + + /** + * A non-singular query appeared in a context where a singular query was expected (e.g. an operand + * of a comparison) + * + * @param line the line at which the offending query occurred + * @param column the column at which the offending query occurred + */ + data class MustBeSingularQuery( + val line: UInt, + val column: UInt, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = "${messagePrefix(line, column)}: A singular query is expected" + } + + /** + * An invalid escape sequence occurred in a string literal. + * + * @param string the string literal + * @param line the line at which the string literal is located + * @param column the column at which the string literal is located + * @param position the position of the invalid escape sequence within the string + * @param reason a more detailed description of the issue + */ + data class InvalidEscapeSequence( + val string: String, + val line: UInt, + val column: UInt, + val position: UInt, + val reason: String, + ) : JsonPathError { + /** + * Serializes this error to a readable string message + */ + override fun toString(): String = + "${messagePrefix(line, column)}: " + + "Invalid escape sequence at position $position in string literal '$string' ($reason)" + } + + /** + * Contains helpers and a constructor-like factory function + */ + companion object { + /** + * Creates a [JsonPathError] from the given [Throwable]. If it is a [JsonPathException], the + * contained error is unwrapped. + * + * @param throwable the throwable to convert + * @return a corresponding JSON Path Error + */ + operator fun invoke(throwable: Throwable): JsonPathError = + when (throwable) { + is JsonPathException -> throwable.err + is CancellationException, is Error -> throw throwable + else -> throw IllegalStateException(throwable) + } + + private fun messagePrefix( + line: UInt, + column: UInt, + ): String = "Error at [$line:$column]" + } +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/error/JsonPathException.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/error/JsonPathException.kt new file mode 100644 index 0000000..9ff837e --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/error/JsonPathException.kt @@ -0,0 +1,10 @@ +package com.kobil.vertx.jsonpath.error + +/** + * A simple stacktrace-less exception carrying a [JsonPathError]. + * + * @param err the [JsonPathError] + */ +class JsonPathException( + val err: JsonPathError, +) : Exception(err.toString(), null, false, false) diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/error/MultipleResults.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/error/MultipleResults.kt new file mode 100644 index 0000000..61e5787 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/error/MultipleResults.kt @@ -0,0 +1,20 @@ +package com.kobil.vertx.jsonpath.error + +import com.kobil.vertx.jsonpath.JsonNode + +/** + * A query that was required to yield at most one result returned multiple results. + * + * @param results all results that were returned + * + * @see JsonNode + * @see com.kobil.vertx.jsonpath.JsonPath.getOne + * @see com.kobil.vertx.jsonpath.JsonPath.requireOne + * @see com.kobil.vertx.jsonpath.JsonPath.traceOne + * @see com.kobil.vertx.jsonpath.get + * @see com.kobil.vertx.jsonpath.required + * @see com.kobil.vertx.jsonpath.traceOne + */ +data class MultipleResults( + val results: List, +) : RequiredJsonValueError diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/error/RequiredJsonValueError.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/error/RequiredJsonValueError.kt new file mode 100644 index 0000000..0bfce31 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/error/RequiredJsonValueError.kt @@ -0,0 +1,15 @@ +package com.kobil.vertx.jsonpath.error + +/** + * A base interface for errors that can occur when executing a query that should yield exactly one + * result. + * + * @see NoResult + * @see MultipleResults + */ +sealed interface RequiredJsonValueError { + /** + * The query returned no result + */ + data object NoResult : RequiredJsonValueError +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/ComparableExpressions.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/ComparableExpressions.kt new file mode 100644 index 0000000..7b19a05 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/ComparableExpressions.kt @@ -0,0 +1,79 @@ +package com.kobil.vertx.jsonpath.interpreter + +import arrow.core.None +import arrow.core.Option +import arrow.core.some +import com.kobil.vertx.jsonpath.ComparableExpression +import com.kobil.vertx.jsonpath.FunctionExpression +import com.kobil.vertx.jsonpath.JsonNode +import com.kobil.vertx.jsonpath.JsonPath.Companion.onlyValues +import com.kobil.vertx.jsonpath.NodeListExpression +import com.kobil.vertx.jsonpath.QueryExpression +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject + +internal fun ComparableExpression.evaluate( + input: JsonNode, + root: JsonNode, +): Option = + when (this) { + is ComparableExpression.Literal -> value.some() + is FunctionExpression.Length -> evaluate(input, root) + is FunctionExpression.Count -> evaluate(input, root) + is FunctionExpression.Value -> evaluate(input, root) + is QueryExpression<*> -> evaluate(input, root).takeIfSingular() + } + +internal fun FunctionExpression.Length.evaluate( + input: JsonNode, + root: JsonNode, +): Option = + when (arg) { + is ComparableExpression.Literal -> arg.value.some() + is NodeListExpression -> arg.evaluate(input, root).takeIfSingular() + is FunctionExpression -> arg.evaluate(input, root) + }.flatMap { + when (it) { + is String -> it.length.some() + is JsonArray -> it.size().some() + is JsonObject -> it.size().some() + else -> None + } + } + +internal fun FunctionExpression.Count.evaluate( + input: JsonNode, + root: JsonNode, +): Option = arg.evaluate(input, root).size.some() + +internal fun FunctionExpression.Value.evaluate( + input: JsonNode, + root: JsonNode, +): Option = arg.evaluate(input, root).takeIfSingular() + +internal fun NodeListExpression.evaluate( + input: JsonNode, + root: JsonNode, +): List = + when (this) { + is QueryExpression<*> -> evaluate(input, root) + } + +internal fun QueryExpression<*>.evaluate( + input: JsonNode, + root: JsonNode, +): List = + when (this) { + is QueryExpression.Relative -> + segments.evaluate(input, root).onlyValues() + + is QueryExpression.Absolute -> + segments.evaluate(root).onlyValues() + } + +internal fun List.takeIfSingular(): Option = + if (size == 1) { + first().some() + } else { + None + } diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/FilterExpressions.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/FilterExpressions.kt new file mode 100644 index 0000000..4743e93 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/FilterExpressions.kt @@ -0,0 +1,202 @@ +package com.kobil.vertx.jsonpath.interpreter + +import arrow.core.None +import arrow.core.Option +import arrow.core.Some +import com.kobil.vertx.jsonpath.ComparableExpression +import com.kobil.vertx.jsonpath.FilterExpression +import com.kobil.vertx.jsonpath.FunctionExpression +import com.kobil.vertx.jsonpath.JsonNode +import com.kobil.vertx.jsonpath.NodeListExpression +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject +import io.vertx.kotlin.core.json.get +import java.util.regex.PatternSyntaxException + +/** + * Evaluates the filter expression on the given [input] node in the context of the [root] node. If + * the filter expression contains nested absolute queries, they are evaluated on [root]. + * + * @receiver the filter expression + * @param input the input node + * @param root the root node. When omitted, `input == root` is assumed. + * @return true if the filter expression matches, false otherwise + * + * @see JsonNode + * @see FilterExpression + */ +@JvmOverloads +fun FilterExpression.test( + input: JsonNode, + root: JsonNode = input, +): Boolean = + when (this) { + is FilterExpression.And -> this@test.test(input, root) + is FilterExpression.Or -> this@test.test(input, root) + is FilterExpression.Not -> !operand.test(input, root) + is FilterExpression.Comparison -> this@test.test(input, root) + is FilterExpression.Test -> this@test.test(input, root) + is FilterExpression.Match -> this@test.test(input, root) + } + +internal fun FilterExpression.And.test( + input: JsonNode, + root: JsonNode, +): Boolean = + operands.fold(true) { acc, operand -> + acc && operand.test(input, root) + } + +internal fun FilterExpression.Or.test( + input: JsonNode, + root: JsonNode, +): Boolean = + operands.fold(false) { acc, operand -> + acc || operand.test(input, root) + } + +internal fun FilterExpression.Comparison.test( + input: JsonNode, + root: JsonNode, +): Boolean { + val lhsVal = lhs.evaluate(input, root) + val rhsVal = rhs.evaluate(input, root) + + return when (op) { + FilterExpression.Comparison.Op.EQ -> equals(lhsVal, rhsVal) + FilterExpression.Comparison.Op.NOT_EQ -> !equals(lhsVal, rhsVal) + FilterExpression.Comparison.Op.LESS -> less(lhsVal, rhsVal) + FilterExpression.Comparison.Op.LESS_EQ -> less(lhsVal, rhsVal) || equals(lhsVal, rhsVal) + FilterExpression.Comparison.Op.GREATER -> greater(lhsVal, rhsVal) + FilterExpression.Comparison.Op.GREATER_EQ -> greater(lhsVal, rhsVal) || equals(lhsVal, rhsVal) + } +} + +internal fun FilterExpression.Test.test( + input: JsonNode, + root: JsonNode, +): Boolean = query.evaluate(input, root).isNotEmpty() + +private val unescapedDot = """(?(\\\\)*)\.(?![^]\n\r]*])""".toRegex() + +internal fun FilterExpression.Match.test( + input: JsonNode, + root: JsonNode, +): Boolean { + val subjectStr = + when (subject) { + is ComparableExpression.Literal -> subject.value + is NodeListExpression -> subject.evaluate(input, root).takeIfSingular().getOrNull() + is FunctionExpression -> pattern.evaluate(input, root) + } as? String ?: return false + + val patternStr = + when (pattern) { + is ComparableExpression.Literal -> pattern.value + is NodeListExpression -> pattern.evaluate(input, root).takeIfSingular().getOrNull() + is FunctionExpression -> pattern.evaluate(input, root).getOrNull() + } as? String ?: return false + + val patternRegex = + try { + patternStr.replace(unescapedDot, """${"$"}{backslashes}[^\\n\\r]""").toRegex() + } catch (pse: PatternSyntaxException) { + return false + } + + return if (matchEntire) { + patternRegex.matches(subjectStr) + } else { + patternRegex.containsMatchIn(subjectStr) + } +} + +internal fun equals( + lhs: Option, + rhs: Option, +): Boolean = + when (lhs) { + is None -> rhs is None + is Some -> rhs is Some && valuesEqual(lhs.value, rhs.value) + } + +internal fun less( + lhs: Option, + rhs: Option, +): Boolean = + when (lhs) { + is None -> false + is Some -> rhs is Some && valueLess(lhs.value, rhs.value) + } + +internal fun greater( + lhs: Option, + rhs: Option, +): Boolean = + when (lhs) { + is None -> false + is Some -> rhs is Some && valueGreater(lhs.value, rhs.value) + } + +internal fun valuesEqual( + lhs: Any?, + rhs: Any?, +): Boolean { + val lhsVal = replaceNodeListWithNode(lhs) + val rhsVal = replaceNodeListWithNode(rhs) + + return when (lhsVal) { + null -> rhs == null + is Number -> rhsVal is Number && lhsVal.toDouble() == rhsVal.toDouble() + is String -> rhsVal is String && lhsVal == rhsVal + is Boolean -> rhsVal is Boolean && lhsVal == rhsVal + is JsonArray -> + rhsVal is JsonArray && + lhsVal.size() == rhsVal.size() && + lhsVal.asSequence().zip(rhsVal.asSequence(), ::valuesEqual).all { it } + + is JsonObject -> + rhsVal is JsonObject && + lhsVal.map.keys == rhsVal.map.keys && + lhsVal.map.keys.all { valuesEqual(lhsVal[it], rhsVal[it]) } + + is List<*> -> + if (lhsVal.isEmpty()) { + rhsVal is List<*> && rhsVal.isEmpty() + } else { + false + } + + else -> false + } +} + +internal fun valueLess( + lhs: Any?, + rhs: Any?, +): Boolean = + when (lhs) { + is Number -> rhs is Number && lhs.toDouble() < rhs.toDouble() + is String -> rhs is String && lhs < rhs + else -> false + } + +internal fun valueGreater( + lhs: Any?, + rhs: Any?, +): Boolean = + when (lhs) { + is Number -> rhs is Number && lhs.toDouble() > rhs.toDouble() + is String -> rhs is String && lhs > rhs + else -> false + } + +internal fun replaceNodeListWithNode(maybeList: Any?): Any? { + val maybeNode = + (maybeList as? List<*>) + ?.takeIf { it.size == 1 } + ?.first() + as? JsonNode + + return maybeNode ?: maybeList +} diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/Segments.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/Segments.kt new file mode 100644 index 0000000..1a22816 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/Segments.kt @@ -0,0 +1,81 @@ +package com.kobil.vertx.jsonpath.interpreter + +import com.kobil.vertx.jsonpath.JsonNode +import com.kobil.vertx.jsonpath.Segment +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject + +/** + * Evaluates the segments on the given [input] node in the context of the [root] node. If + * any selector within the segments contains nested absolute queries, they are evaluated on [root]. + * + * @receiver an ordered list of segments to evaluate + * @param input the input node + * @param root the root node. When omitted, `input == root` is assumed. + * @return the resulting node list after all segments have been evaluated + * + * @see JsonNode + * @see Segment + */ +@JvmOverloads +fun List.evaluate( + input: JsonNode, + root: JsonNode = input, +): List = + fold(listOf(input)) { selected, segment -> + segment.evaluate(selected, root) + } + +/** + * Evaluates the segment on the given [input] node list in the context of the [root] node. If + * any selector within the segments contains nested absolute queries, they are evaluated on [root]. + * + * @receiver the segment to evaluate + * @param input the input node list + * @param root the root node + * @return the resulting node list after the segment has been evaluated + * + * @see JsonNode + * @see Segment + */ +fun Segment.evaluate( + input: List, + root: JsonNode, +): List = + when (this) { + is Segment.ChildSegment -> evaluate(input, root) + is Segment.DescendantSegment -> evaluate(input, root) + }.ifEmpty(::emptyList) + +internal fun Segment.ChildSegment.evaluate( + input: List, + root: JsonNode, +): List = + input.flatMap { selected -> + selectors.flatMap { it.select(selected, root) } + } + +internal fun Segment.DescendantSegment.evaluate( + input: List, + root: JsonNode, +): List = + input.flatMap { selected -> + selected.enumerateDescendants().flatMap { descendant -> + selectors.flatMap { it.select(descendant, root) } + } + } + +internal fun JsonNode.enumerateDescendants(): Sequence = + sequence { + yield(this@enumerateDescendants) + + when (value) { + is JsonObject -> + value.forEach { yieldAll(child(it.key, it.value).enumerateDescendants()) } + + is JsonArray -> + value.forEachIndexed { idx, item -> + yieldAll(child(idx, item).enumerateDescendants()) + } + } + } diff --git a/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/Selectors.kt b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/Selectors.kt new file mode 100644 index 0000000..3164081 --- /dev/null +++ b/src/main/kotlin/com/kobil/vertx/jsonpath/interpreter/Selectors.kt @@ -0,0 +1,129 @@ +package com.kobil.vertx.jsonpath.interpreter + +import com.kobil.vertx.jsonpath.JsonNode +import com.kobil.vertx.jsonpath.Selector +import com.kobil.vertx.jsonpath.get +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject + +/** + * Applies the selector to the given [input] node in the context of the [root] node. If + * any selector within the segments contains nested absolute queries, they are evaluated on [root]. + * + * @receiver the selector to apply + * @param input the input node + * @param root the root node. When omitted, `input == root` is assumed. + * @return the resulting node list after the selector has been applied + * + * @see JsonNode + * @see Selector + */ +@JvmOverloads +fun Selector.select( + input: JsonNode, + root: JsonNode = input, +): List = + when (this) { + is Selector.Name -> select(input) + is Selector.Index -> select(input) + is Selector.Wildcard -> selectAll(input) + is Selector.Slice -> select(input) + is Selector.Filter -> select(input, root) + } + +internal fun Selector.Name.select(input: JsonNode): List = + (input.value as? JsonObject)?.let { + if (it.containsKey(name)) { + listOf(input.child(name, it.getValue(name))) + } else { + emptyList() + } + } ?: emptyList() + +internal fun selectAll(input: JsonNode): List = + when (val node = input.value) { + is JsonObject -> node.map { input.child(it.key, it.value) } + is JsonArray -> node.mapIndexed { idx, item -> input.child(idx, item) } + else -> emptyList() + } + +internal fun Selector.Index.select(input: JsonNode): List = + (input.value as? JsonArray)?.let { arr -> + val idx = index.normalizeIndex(arr.size()) + + if (idx in 0.. = + (input.value as? JsonArray)?.let { arr -> + val len = arr.size() + val step = step ?: 1 + + if (step == 0) return emptyList() + + val lower = + if (step > 0) { + minOf(maxOf(first?.normalizeIndex(len) ?: 0, 0), len) + } else { + minOf(maxOf(last?.normalizeIndex(len) ?: -1, -1), len - 1) + } + + val upper = + if (step > 0) { + minOf(maxOf(last?.normalizeIndex(len) ?: len, 0), len) + } else { + minOf(maxOf(first?.normalizeIndex(len) ?: (len - 1), -1), len - 1) + } + + val range = + if (step > 0) { + lower.. input.child(i, arr.getValue(i)) } + } ?: emptyList() + +internal fun Selector.Filter.select( + input: JsonNode, + root: JsonNode, +): List = + when (val value = input.value) { + is JsonObject -> + value + .asSequence() + .map { (key, field) -> input.child(key, field) } + .filter { node -> filter.test(node, root) } + .toList() + + is JsonArray -> + value + .asSequence() + .mapIndexed { idx, item -> input.child(idx, item) } + .filter { node -> filter.test(node, root) } + .toList() + + else -> emptyList() + } + +internal fun Int.normalizeIndex(size: Int): Int = + if (this >= 0) { + toInt() + } else { + toInt() + size + } + +internal fun JsonNode.child( + name: String, + node: Any?, +): JsonNode = JsonNode(node, path[name]) + +internal fun JsonNode.child( + index: Int, + node: Any?, +): JsonNode = JsonNode(node, path[index]) diff --git a/src/test/java/com/kobil/vertx/jsonpath/JavaFilterExpressionTest.java b/src/test/java/com/kobil/vertx/jsonpath/JavaFilterExpressionTest.java new file mode 100644 index 0000000..4fbe42c --- /dev/null +++ b/src/test/java/com/kobil/vertx/jsonpath/JavaFilterExpressionTest.java @@ -0,0 +1,38 @@ +package com.kobil.vertx.jsonpath; + +import arrow.core.Either; +import com.kobil.vertx.jsonpath.error.JsonPathError; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +public class JavaFilterExpressionTest { + @Test + @DisplayName("A call to the compile static method with a valid filter expression should return a Right containing the compiled filter") + public void success() { + var filterA = assertInstanceOf(Either.Right.class, FilterExpression.compile("@.a")).getValue(); + assertEquals(new FilterExpression.Test(QueryExpression.relative().field("a")), filterA); + + var filterB = assertInstanceOf(Either.Right.class, FilterExpression.compile("$['b']")).getValue(); + assertEquals(new FilterExpression.Test(QueryExpression.absolute().field("b")), filterB); + } + + @Test + @DisplayName("A call to the compile static method with an invalid filter string should return a Left") + public void failure() { + assertEquals( + "QuestionMark", + assertInstanceOf( + JsonPathError.UnexpectedToken.class, + assertInstanceOf(Either.Left.class, FilterExpression.compile("?@.abc")).getValue() + ).getToken() + ); + + assertInstanceOf( + JsonPathError.MustBeSingularQuery.class, + assertInstanceOf(Either.Left.class, FilterExpression.compile("@..a == 2")).getValue() + ); + } +} diff --git a/src/test/java/com/kobil/vertx/jsonpath/JavaJsonNodeTest.java b/src/test/java/com/kobil/vertx/jsonpath/JavaJsonNodeTest.java new file mode 100644 index 0000000..f25d923 --- /dev/null +++ b/src/test/java/com/kobil/vertx/jsonpath/JavaJsonNodeTest.java @@ -0,0 +1,32 @@ +package com.kobil.vertx.jsonpath; + +import io.vertx.core.json.JsonObject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +public class JavaJsonNodeTest { + @Test + @DisplayName("The root static function should create a JsoNode with the given value and the root path") + public void root() { + Assertions.assertEquals( + new JsonNode("a", JsonPath.ROOT), + JsonNode.root("a") + ); + + Assertions.assertEquals( + new JsonNode(1, JsonPath.ROOT), + JsonNode.root(1) + ); + + Assertions.assertEquals( + new JsonNode(null, JsonPath.ROOT), + JsonNode.root(null) + ); + + Assertions.assertEquals( + new JsonNode(new JsonObject(), JsonPath.ROOT), + JsonNode.root(new JsonObject()) + ); + } +} diff --git a/src/test/java/com/kobil/vertx/jsonpath/JavaJsonPathTest.java b/src/test/java/com/kobil/vertx/jsonpath/JavaJsonPathTest.java new file mode 100644 index 0000000..19607bb --- /dev/null +++ b/src/test/java/com/kobil/vertx/jsonpath/JavaJsonPathTest.java @@ -0,0 +1,45 @@ +package com.kobil.vertx.jsonpath; + +import arrow.core.Either; +import com.kobil.vertx.jsonpath.error.JsonPathError; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +public class JavaJsonPathTest { + @Test + @DisplayName("A call to the compile static method with a valid JSON path should return a Right containing the compiled filter") + public void success() { + var jpA = assertInstanceOf(Either.Right.class, JsonPath.compile("$.a")).getValue(); + assertEquals(JsonPath.ROOT.field("a"), jpA); + + var jpB = assertInstanceOf(Either.Right.class, JsonPath.compile("$['b', 1::2, ?@.a][*]")).getValue(); + assertEquals( + JsonPath.ROOT.selectChildren( + Selector.name("b"), + Selector.slice(1, null, 2), + Selector.filter(QueryExpression.relative().field("a").exists()) + ).selectAllChildren(), + jpB + ); + } + + @Test + @DisplayName("A call to the compile static method with an invalid JSON Path string should return a Left") + public void failure() { + assertEquals( + "QuestionMark", + assertInstanceOf( + JsonPathError.UnexpectedToken.class, + assertInstanceOf(Either.Left.class, JsonPath.compile("?.abc")).getValue() + ).getToken() + ); + + assertInstanceOf( + JsonPathError.MustBeSingularQuery.class, + assertInstanceOf(Either.Left.class, FilterExpression.compile("$[?@..a == 2]")).getValue() + ); + } +} diff --git a/src/test/java/com/kobil/vertx/jsonpath/JavaQueryExpressionTest.java b/src/test/java/com/kobil/vertx/jsonpath/JavaQueryExpressionTest.java new file mode 100644 index 0000000..cfb71c7 --- /dev/null +++ b/src/test/java/com/kobil/vertx/jsonpath/JavaQueryExpressionTest.java @@ -0,0 +1,161 @@ +package com.kobil.vertx.jsonpath; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class JavaQueryExpressionTest { + @Nested + @DisplayName("The absolute static function") + public class Absolute { + @Test + @DisplayName("called without arguments should return an empty absolute query") + public void noArgs() { + assertEquals( + new QueryExpression.Absolute(Collections.emptyList()), + QueryExpression.absolute() + ); + } + + @Test + @DisplayName("called with a list of segments should return an absolute query using the same segments") + public void list() { + var n = Selector.name("a"); + var i = Selector.index(1); + var s = Selector.slice(1, -1, 2); + var w = Selector.WILDCARD; + var f = Selector.filter(QueryExpression.absolute().exists()); + + var segments1 = List.of(new Segment.ChildSegment(n)); + var segments2 = Arrays.asList(new Segment.ChildSegment(n, i), new Segment.DescendantSegment(f)); + var segments3 = Arrays.asList(new Segment.ChildSegment(w), new Segment.DescendantSegment(s), + new Segment.ChildSegment(i)); + + assertEquals( + new QueryExpression.Absolute(segments1), + QueryExpression.absolute(segments1) + ); + + assertEquals( + new QueryExpression.Absolute(segments2), + QueryExpression.absolute(segments2) + ); + + assertEquals( + new QueryExpression.Absolute(segments3), + QueryExpression.absolute(segments3) + ); + } + + @Test + @DisplayName("called with vararg segments should return an absolute query using the same segments") + public void varargs() { + var n = Selector.name("a"); + var i = Selector.index(1); + var s = Selector.slice(1, -1, 2); + var w = Selector.WILDCARD; + var f = Selector.filter(QueryExpression.absolute().exists()); + + var segments1 = List.of(new Segment.ChildSegment(n)); + var segments2 = Arrays.asList(new Segment.ChildSegment(n, i), new Segment.DescendantSegment(f)); + var segments3 = Arrays.asList(new Segment.ChildSegment(w), new Segment.DescendantSegment(s), + new Segment.ChildSegment(i)); + + assertEquals( + new QueryExpression.Absolute(segments1), + QueryExpression.absolute(new Segment.ChildSegment(n)) + ); + + assertEquals( + new QueryExpression.Absolute(segments2), + QueryExpression.absolute(new Segment.ChildSegment(n, i), new Segment.DescendantSegment(f)) + ); + + assertEquals( + new QueryExpression.Absolute(segments3), + QueryExpression.absolute(new Segment.ChildSegment(w), new Segment.DescendantSegment(s), + new Segment.ChildSegment(i)) + ); + } + } + + @Nested + @DisplayName("The relative static function") + public class Relative { + @Test + @DisplayName("called without arguments should return an empty relative query") + public void noArgs() { + assertEquals( + new QueryExpression.Relative(Collections.emptyList()), + QueryExpression.relative() + ); + } + + @Test + @DisplayName("called with a list of segments should return a relative query using the same segments") + public void list() { + var n = Selector.name("a"); + var i = Selector.index(1); + var s = Selector.slice(1, -1, 2); + var w = Selector.WILDCARD; + var f = Selector.filter(QueryExpression.relative().exists()); + + var segments1 = List.of(new Segment.ChildSegment(n)); + var segments2 = Arrays.asList(new Segment.ChildSegment(n, i), new Segment.DescendantSegment(f)); + var segments3 = Arrays.asList(new Segment.ChildSegment(w), new Segment.DescendantSegment(s), + new Segment.ChildSegment(i)); + + assertEquals( + new QueryExpression.Relative(segments1), + QueryExpression.relative(segments1) + ); + + assertEquals( + new QueryExpression.Relative(segments2), + QueryExpression.relative(segments2) + ); + + assertEquals( + new QueryExpression.Relative(segments3), + QueryExpression.relative(segments3) + ); + } + + @Test + @DisplayName("called with vararg segments should return a relative query using the same segments") + public void varargs() { + var n = Selector.name("a"); + var i = Selector.index(1); + var s = Selector.slice(1, -1, 2); + var w = Selector.WILDCARD; + var f = Selector.filter(QueryExpression.relative().exists()); + + var segments1 = List.of(new Segment.ChildSegment(n)); + var segments2 = Arrays.asList(new Segment.ChildSegment(n, i), new Segment.DescendantSegment(f)); + var segments3 = Arrays.asList(new Segment.ChildSegment(w), new Segment.DescendantSegment(s), + new Segment.ChildSegment(i)); + + assertEquals( + new QueryExpression.Relative(segments1), + QueryExpression.relative(new Segment.ChildSegment(n)) + ); + + assertEquals( + new QueryExpression.Relative(segments2), + QueryExpression.relative(new Segment.ChildSegment(n, i), new Segment.DescendantSegment(f)) + ); + + assertEquals( + new QueryExpression.Relative(segments3), + QueryExpression.relative(new Segment.ChildSegment(w), new Segment.DescendantSegment(s), + new Segment.ChildSegment(i)) + ); + } + } +} diff --git a/src/test/java/com/kobil/vertx/jsonpath/JavaSegmentTest.java b/src/test/java/com/kobil/vertx/jsonpath/JavaSegmentTest.java new file mode 100644 index 0000000..52d780f --- /dev/null +++ b/src/test/java/com/kobil/vertx/jsonpath/JavaSegmentTest.java @@ -0,0 +1,101 @@ +package com.kobil.vertx.jsonpath; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class JavaSegmentTest { + @Nested + @DisplayName("The child static method on Segment") + public class Child { + @Test + @DisplayName("should throw when called with an empty list") + public void emptyList() { + assertThrows( + IllegalArgumentException.class, + () -> Segment.child(new ArrayList<>()) + ); + } + + @Test + @DisplayName("should return a child segment with the same selectors when called with a non-empty list") + public void nonEmptyList() { + var sel = new ArrayList(); + sel.add(Selector.name("a")); + sel.add(Selector.index(1)); + sel.add(Selector.slice(1, -1, 2)); + sel.add(Selector.WILDCARD); + sel.add(Selector.filter(QueryExpression.absolute().exists())); + + assertEquals( + new Segment.ChildSegment(sel), + Segment.child(sel) + ); + } + + @Test + @DisplayName("should return a child segment with the same selectors when called with varargs") + public void varargs() { + var n = Selector.name("a"); + var i = Selector.index(1); + var s = Selector.slice(1, -1, 2); + var w = Selector.WILDCARD; + var f = Selector.filter(QueryExpression.absolute().exists()); + + assertEquals( + new Segment.ChildSegment(Arrays.asList(n, i, s, w, f)), + Segment.child(n, i, s, w, f) + ); + } + } + + @Nested + @DisplayName("The descendant static method on Segment") + public class Descendant { + @Test + @DisplayName("should throw when called with an empty list") + public void emptyList() { + assertThrows( + IllegalArgumentException.class, + () -> Segment.descendant(new ArrayList<>()) + ); + } + + @Test + @DisplayName("should return a descendant segment with the same selectors when called with a non-empty list") + public void nonEmptyList() { + var sel = new ArrayList(); + sel.add(Selector.name("a")); + sel.add(Selector.index(1)); + sel.add(Selector.slice(1, -1, 2)); + sel.add(Selector.WILDCARD); + sel.add(Selector.filter(QueryExpression.absolute().exists())); + + assertEquals( + new Segment.DescendantSegment(sel), + Segment.descendant(sel) + ); + } + + @Test + @DisplayName("should return a descendant segment with the same selectors when called with varargs") + public void varargs() { + var n = Selector.name("a"); + var i = Selector.index(1); + var s = Selector.slice(1, -1, 2); + var w = Selector.WILDCARD; + var f = Selector.filter(QueryExpression.absolute().exists()); + + assertEquals( + new Segment.DescendantSegment(Arrays.asList(n, i, s, w, f)), + Segment.descendant(n, i, s, w, f) + ); + } + } +} diff --git a/src/test/java/com/kobil/vertx/jsonpath/JavaSelectorTest.java b/src/test/java/com/kobil/vertx/jsonpath/JavaSelectorTest.java new file mode 100644 index 0000000..14b7691 --- /dev/null +++ b/src/test/java/com/kobil/vertx/jsonpath/JavaSelectorTest.java @@ -0,0 +1,84 @@ +package com.kobil.vertx.jsonpath; + +import com.kobil.vertx.jsonpath.FilterExpression.Comparison; +import com.kobil.vertx.jsonpath.FilterExpression.Not; +import com.kobil.vertx.jsonpath.QueryExpression.Relative; +import com.kobil.vertx.jsonpath.Segment.ChildSegment; +import kotlin.ranges.IntProgression; +import kotlin.ranges.IntRange; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static arrow.core.NonEmptyListKt.nonEmptyListOf; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class JavaSelectorTest { + @Test + @DisplayName("The name static function should return a Name selector with the given field name") + public void name() { + assertEquals(new Selector.Name("a"), Selector.name("a")); + assertEquals(new Selector.Name("hello world"), Selector.name("hello world")); + } + + @Test + @DisplayName("The index static function should return an Index selector with the given index") + public void index() { + assertEquals(new Selector.Index(1), Selector.index(1)); + assertEquals(new Selector.Index(-10), Selector.index(-10)); + } + + @Nested + @DisplayName("The slice static function") + public class Slice { + @Test + @DisplayName("applied to an IntProgression instance should return an equivalent slice selector") + public void progression() { + assertEquals(new Selector.Slice(1, 3, 1), Selector.slice(new IntRange(1, 2))); + assertEquals(new Selector.Slice(1, 5, 1), Selector.slice(new IntRange(1, 4))); + assertEquals(new Selector.Slice(1, 10, 2), Selector.slice(new IntProgression(1, 10, 2))); + assertEquals(new Selector.Slice(10, 0, -1), Selector.slice(new IntProgression(10, 1, -1))); + assertEquals(new Selector.Slice(10, 1, -4), Selector.slice(new IntProgression(10, 1, -4))); + } + + @Test + @DisplayName("applied to two nullable integers should return an equivalent slice selector with unset step") + public void twoInts() { + assertEquals(new Selector.Slice(1, 2, null), Selector.slice(1, 2)); + assertEquals(new Selector.Slice(1, -1, null), Selector.slice(1, -1)); + assertEquals(new Selector.Slice(1, null, null), Selector.slice(1, null)); + assertEquals(new Selector.Slice(null, 2, null), Selector.slice(null, 2)); + assertEquals(new Selector.Slice(null, null, null), Selector.slice(null, null)); + } + + @Test + @DisplayName("applied to three nullable integers should return an equivalent slice selector") + public void threeInts() { + assertEquals(new Selector.Slice(1, 2, 2), Selector.slice(1, 2, 2)); + assertEquals(new Selector.Slice(1, -1, 3), Selector.slice(1, -1, 3)); + assertEquals(new Selector.Slice(1, null, -1), Selector.slice(1, null, -1)); + assertEquals(new Selector.Slice(null, 2, 3), Selector.slice(null, 2, 3)); + assertEquals(new Selector.Slice(null, null, 3), Selector.slice(null, null, 3)); + assertEquals(new Selector.Slice(null, null, null), Selector.slice(null, null, null)); + } + } + + @Test + @DisplayName("The filter static function should return a Filter selector with the given filter expression") + public void filter() { + var expr1 = new FilterExpression.Test(new Relative(new ChildSegment("a"))); + var expr2 = new FilterExpression.Or( + nonEmptyListOf( + new Comparison( + Comparison.Op.GREATER_EQ, + new Relative(new ChildSegment("a")), + new ComparableExpression.Literal(1) + ), + new Not(new FilterExpression.Test(new Relative(new ChildSegment("a")))) + ) + ); + + assertEquals(new Selector.Filter(expr1), Selector.filter(expr1)); + assertEquals(new Selector.Filter(expr2), Selector.filter(expr2)); + } +} diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/ComparableExpressionTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/ComparableExpressionTest.kt new file mode 100644 index 0000000..ce04bba --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/ComparableExpressionTest.kt @@ -0,0 +1,110 @@ +package com.kobil.vertx.jsonpath + +import com.kobil.vertx.jsonpath.FilterExpression.Comparison +import com.kobil.vertx.jsonpath.testing.comparable +import com.kobil.vertx.jsonpath.testing.matchOperand +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.arbitrary.boolean +import io.kotest.property.arbitrary.choice +import io.kotest.property.arbitrary.constant +import io.kotest.property.arbitrary.double +import io.kotest.property.arbitrary.int +import io.kotest.property.arbitrary.string +import io.kotest.property.checkAll + +class ComparableExpressionTest : + ShouldSpec({ + context("The eq operator") { + should("return a Comparison of both operands using the EQ operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + lhs eq rhs shouldBe Comparison(Comparison.Op.EQ, lhs, rhs) + } + } + } + + context("The neq operator") { + should("return a Comparison of both operands using the NOT_EQ operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + lhs neq rhs shouldBe Comparison(Comparison.Op.NOT_EQ, lhs, rhs) + } + } + } + + context("The gt operator") { + should("return a Comparison of both operands using the GREATER operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + lhs gt rhs shouldBe Comparison(Comparison.Op.GREATER, lhs, rhs) + } + } + } + + context("The ge operator") { + should("return a Comparison of both operands using the GREATER_EQ operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + lhs ge rhs shouldBe Comparison(Comparison.Op.GREATER_EQ, lhs, rhs) + } + } + } + + context("The lt operator") { + should("return a Comparison of both operands using the LESS operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + lhs lt rhs shouldBe Comparison(Comparison.Op.LESS, lhs, rhs) + } + } + } + + context("The le operator") { + should("return a Comparison of both operands using the LESS_EQ operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + lhs le rhs shouldBe Comparison(Comparison.Op.LESS_EQ, lhs, rhs) + } + } + } + + context("The length function") { + should("return a Length instance with the given operand") { + checkAll(Arb.comparable()) { lhs -> + lhs.length() shouldBe FunctionExpression.Length(lhs) + } + } + } + + context("The match function") { + should("return a Match instance with the given subject and pattern and matchEntire = true") { + checkAll(Arb.matchOperand(), Arb.matchOperand()) { subject, pattern -> + subject.match(pattern) shouldBe + FilterExpression.Match(subject, pattern, matchEntire = true) + } + } + } + + context("The search function") { + should("return a Match instance with the given subject and pattern and matchEntire = false") { + checkAll(Arb.matchOperand(), Arb.matchOperand()) { subject, pattern -> + subject.search(pattern) shouldBe + FilterExpression.Match(subject, pattern, matchEntire = false) + } + } + } + + context("The toString method") { + context("of a Literal instance") { + should("wrap a string value in double quotes") { + checkAll(Arb.string()) { + ComparableExpression.Literal(it).toString() shouldBe "\"$it\"" + } + } + + should("simply serialize any other value to string") { + checkAll( + Arb.choice(Arb.int(), Arb.double(), Arb.boolean(), Arb.constant(null)), + ) { + ComparableExpression.Literal(it).toString() shouldBe "$it" + } + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/ComplianceTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/ComplianceTest.kt new file mode 100644 index 0000000..24413d5 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/ComplianceTest.kt @@ -0,0 +1,141 @@ +package com.kobil.vertx.jsonpath + +import com.kobil.vertx.jsonpath.JsonPath.Companion.onlyValues +import com.kobil.vertx.jsonpath.testing.ShouldSpecContext +import com.kobil.vertx.jsonpath.testing.VertxExtension +import com.kobil.vertx.jsonpath.testing.VertxExtension.Companion.vertx +import io.kotest.assertions.arrow.core.shouldBeLeft +import io.kotest.assertions.arrow.core.shouldBeRight +import io.kotest.assertions.fail +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldBeIn +import io.kotest.matchers.shouldBe +import io.vertx.core.json.JsonArray +import io.vertx.core.json.JsonObject +import io.vertx.kotlin.core.json.get +import io.vertx.kotlin.coroutines.coAwait + +class ComplianceTest : + ShouldSpec({ + println("Instantiating test suite") + + register(VertxExtension()) + + context("The JSON Path implementation should pass the standard compliance test suite") { + val testSuite = + vertx + .fileSystem() + .readFile("compliance-test-suite/cts.json") + .coAwait() + .toJsonObject() + + val tests = + testSuite + .getJsonArray("tests") + .filterIsInstance() + + for (test in tests) { + val ctx: ShouldSpecContext = + if (test.name in skippedTests) { + { name, block -> xcontext(name, block) } + } else { + { name, block -> context(name, block) } + } + + if (test.isInvalid) { + ctx(test.name) { + should("yield an error when compiled") { + JsonPath.compile(test.selector).shouldBeLeft() + } + } + } else { + val result = test.result?.toList() + val results = test.results?.map { (it as JsonArray).toList() } + + if (result != null) { + ctx(test.name) { + should("compile to a valid JSON path") { + JsonPath.compile(test.selector).shouldBeRight() + } + + should("yield the expected results") { + val jsonPath = JsonPath.compile(test.selector).shouldBeRight() + + val actual = + when (val d = test.document) { + is JsonObject -> jsonPath.evaluate(d).onlyValues() + is JsonArray -> jsonPath.evaluate(d).onlyValues() + else -> fail("Unsupported document $d") + } + + actual shouldBe result + } + } + } else if (results != null) { + ctx(test.name) { + should("compile to a valid JSON path") { + JsonPath.compile(test.selector).shouldBeRight() + } + + should("yield the expected results") { + val jsonPath = JsonPath.compile(test.selector).shouldBeRight() + + val actual = + when (val d = test.document) { + is JsonObject -> jsonPath.evaluate(d).onlyValues() + is JsonArray -> jsonPath.evaluate(d).onlyValues() + else -> fail("Unsupported document $d") + } + + actual shouldBeIn results + } + } + } else { + fail( + "Unsupported test case: invalid_selector=false, but neither result nor results is present", + ) + } + } + } + } + }) { + companion object { + val skippedTests = + setOf( + // Tests using values greater than Java's int, which makes no sense in Java as + // indices can never go beyond int's max value + "index selector, min exact index", + "index selector, max exact index", + "slice selector, excessively large to value", + "slice selector, excessively small from value", + "slice selector, excessively large from value with negative step", + "slice selector, excessively small to value with negative step", + "slice selector, excessively large step", + "slice selector, excessively small step", + "slice selector, start, min exact", + "slice selector, start, max exact", + "slice selector, end, min exact", + "slice selector, end, max exact", + "slice selector, step, min exact", + "slice selector, step, max exact", + ) + + private val JsonObject.name: String + get() = this["name"] + + private val JsonObject.selector: String + get() = this["selector"] + + private val JsonObject.document: Any? + get() = this["document"] + + private val JsonObject.result: JsonArray? + get() = this["result"] + + private val JsonObject.results: JsonArray? + get() = this["results"] + + private val JsonObject.isInvalid: Boolean + get() = getBoolean("invalid_selector", false) + } +} diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/FilterExpressionTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/FilterExpressionTest.kt new file mode 100644 index 0000000..4d10b2b --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/FilterExpressionTest.kt @@ -0,0 +1,792 @@ +package com.kobil.vertx.jsonpath + +import arrow.core.nonEmptyListOf +import com.kobil.vertx.jsonpath.ComparableExpression.Literal +import com.kobil.vertx.jsonpath.FilterExpression.And +import com.kobil.vertx.jsonpath.FilterExpression.Comparison +import com.kobil.vertx.jsonpath.FilterExpression.Comparison.Op +import com.kobil.vertx.jsonpath.FilterExpression.Match +import com.kobil.vertx.jsonpath.FilterExpression.Not +import com.kobil.vertx.jsonpath.FilterExpression.Or +import com.kobil.vertx.jsonpath.FilterExpression.Test +import com.kobil.vertx.jsonpath.QueryExpression.Absolute +import com.kobil.vertx.jsonpath.QueryExpression.Relative +import com.kobil.vertx.jsonpath.compiler.Token +import com.kobil.vertx.jsonpath.error.JsonPathError +import com.kobil.vertx.jsonpath.testing.comparable +import com.kobil.vertx.jsonpath.testing.matchOperand +import com.kobil.vertx.jsonpath.testing.queryExpression +import io.kotest.assertions.arrow.core.shouldBeLeft +import io.kotest.assertions.arrow.core.shouldBeRight +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.booleans.shouldBeFalse +import io.kotest.matchers.booleans.shouldBeTrue +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.checkAll +import io.vertx.kotlin.core.json.jsonArrayOf +import io.vertx.kotlin.core.json.jsonObjectOf +import arrow.core.nonEmptyListOf as nel + +class FilterExpressionTest : + ShouldSpec({ + context("Invalid filter expressions") { + context("with a leading question mark") { + should("result in an error when compiled") { + val unexpectedQuestion = + JsonPathError.UnexpectedToken( + Token.QuestionMark(1U, 1U), + "comparable expression", + ) + + // Leading ? must be omitted + FilterExpression.compile("?@") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?@.abc") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?!@") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?!@.abc") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?@ == 'x'") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?@.abc < 1U") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?@['xyz'] >= 'a'") shouldBeLeft unexpectedQuestion + FilterExpression.compile("?@.abc != 2U") shouldBeLeft unexpectedQuestion + } + } + + context("with a non-singular query as the operand of a comparison expression") { + should("result in an error when compiled") { + FilterExpression.compile("@..a == 2") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 1U, + ) + + FilterExpression.compile("2 == @..a") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 6U, + ) + + FilterExpression.compile("@.a[1, 2] == 2") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 1U, + ) + + FilterExpression.compile("2 == @.a[1, 2]") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 6U, + ) + + FilterExpression.compile("@.a['b', 'c'] == 2") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 1U, + ) + + FilterExpression.compile("2 == @.a['b', 'c']") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 6U, + ) + + FilterExpression.compile("@.a[1:] == 2") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 1U, + ) + + FilterExpression.compile("2 == @.a[1:]") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 6U, + ) + + FilterExpression.compile("@.a[?@.b == 1] == 2") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 1U, + ) + + FilterExpression.compile("2 == @.a[?@.b == 1]") shouldBeLeft + JsonPathError.MustBeSingularQuery( + 1U, + 6U, + ) + } + } + } + + context("Valid filter expressions") { + context("using a simple existence check") { + val hasA = "@.a" + val hasB = "@['b']" + val has1 = "@[1]" + val hasNestedA = "@..a" + val hasNestedB = "@..['b']" + val hasNested1 = "@..[1]" + + should("compile successfully") { + FilterExpression.compile(hasA) shouldBeRight + Test( + Relative(listOf(Segment.ChildSegment("a"))), + ) + + FilterExpression.compile(hasB) shouldBeRight + Test( + Relative(listOf(Segment.ChildSegment("b"))), + ) + + FilterExpression.compile(has1) shouldBeRight + Test( + Relative(listOf(Segment.ChildSegment(1))), + ) + FilterExpression.compile(hasNestedA) shouldBeRight + Test( + Relative(listOf(Segment.DescendantSegment("a"))), + ) + + FilterExpression.compile(hasNestedB) shouldBeRight + Test( + Relative(listOf(Segment.DescendantSegment("b"))), + ) + + FilterExpression.compile(hasNested1) shouldBeRight + Test( + Relative(listOf(Segment.DescendantSegment(1))), + ) + } + + context("of a child segment") { + should("return true for inputs if, and only if, they contain the required element") { + val obj1 = jsonObjectOf("a" to 1) + val obj2 = jsonObjectOf("b" to 2) + val obj3 = jsonObjectOf("a" to 1, "b" to 2) + val objANull = jsonObjectOf("a" to null) + val objName1 = jsonObjectOf("1" to true) + + val arr1 = jsonArrayOf("a") + val arr2 = jsonArrayOf("a", "b") + val arr3 = jsonArrayOf("a", "b", "c", "d") + val arr4 = jsonArrayOf(1) + + FilterExpression.compile(hasA).shouldBeRight().also { + it.test(obj1).shouldBeTrue() + it.test(obj2).shouldBeFalse() + it.test(obj3).shouldBeTrue() + it.test(objANull).shouldBeTrue() + it.test(arr1).shouldBeFalse() + it.test(arr2).shouldBeFalse() + it.test(arr3).shouldBeFalse() + it.test(arr4).shouldBeFalse() + } + + FilterExpression.compile(hasB).shouldBeRight().also { + it.test(obj1).shouldBeFalse() + it.test(obj2).shouldBeTrue() + it.test(obj3).shouldBeTrue() + it.test(objANull).shouldBeFalse() + it.test(arr1).shouldBeFalse() + it.test(arr2).shouldBeFalse() + it.test(arr3).shouldBeFalse() + it.test(arr4).shouldBeFalse() + } + + FilterExpression.compile(has1).shouldBeRight().also { + it.test(obj1).shouldBeFalse() + it.test(obj2).shouldBeFalse() + it.test(obj3).shouldBeFalse() + it.test(objANull).shouldBeFalse() + it.test(objName1).shouldBeFalse() + it.test(arr1).shouldBeFalse() + it.test(arr2).shouldBeTrue() + it.test(arr3).shouldBeTrue() + it.test(arr4).shouldBeFalse() + } + } + } + + context("of a descendant segment") { + should("return true for inputs if, and only if, they contain the required element") { + val obj1 = jsonObjectOf("a" to 1) + val obj2 = jsonObjectOf("b" to jsonObjectOf("a" to 1)) + val obj3 = jsonObjectOf("a" to 1, "b" to jsonArrayOf(1)) + val obj4 = jsonObjectOf("a" to jsonArrayOf(1, 2, 3)) + val obj5 = + jsonObjectOf( + "c" to + jsonArrayOf( + jsonObjectOf("a" to true), + jsonObjectOf("b" to false), + ), + ) + val obj6 = jsonObjectOf("b" to jsonArrayOf(1, 2), "c" to jsonObjectOf("b" to 1)) + + val arr1 = jsonArrayOf("a") + val arr2 = jsonArrayOf("a", "b", jsonObjectOf("a" to 1)) + val arr3 = jsonArrayOf("a", "b", "c", "d") + val arr4 = jsonArrayOf(jsonArrayOf("a", "b")) + + FilterExpression.compile(hasNestedA).shouldBeRight().also { + it.test(obj1).shouldBeTrue() + it.test(obj2).shouldBeTrue() + it.test(obj3).shouldBeTrue() + it.test(obj4).shouldBeTrue() + it.test(obj5).shouldBeTrue() + it.test(obj6).shouldBeFalse() + it.test(arr1).shouldBeFalse() + it.test(arr2).shouldBeTrue() + it.test(arr3).shouldBeFalse() + it.test(arr4).shouldBeFalse() + } + + FilterExpression.compile(hasNestedB).shouldBeRight().also { + it.test(obj1).shouldBeFalse() + it.test(obj2).shouldBeTrue() + it.test(obj3).shouldBeTrue() + it.test(obj4).shouldBeFalse() + it.test(obj5).shouldBeTrue() + it.test(obj6).shouldBeTrue() + it.test(arr1).shouldBeFalse() + it.test(arr2).shouldBeFalse() + it.test(arr3).shouldBeFalse() + it.test(arr4).shouldBeFalse() + } + + FilterExpression.compile(hasNested1).shouldBeRight().also { + it.test(obj1).shouldBeFalse() + it.test(obj2).shouldBeFalse() + it.test(obj3).shouldBeFalse() + it.test(obj4).shouldBeTrue() + it.test(obj5).shouldBeTrue() + it.test(obj6).shouldBeTrue() + it.test(arr1).shouldBeFalse() + it.test(arr2).shouldBeTrue() + it.test(arr3).shouldBeTrue() + it.test(arr4).shouldBeTrue() + } + } + } + } + } + + context("The and operator") { + context("when applied to two instances of And") { + should("return a single And instance concatenating the operands of both") { + val f1 = + Or( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + And(nel(f1, f2)) and And(nel(f3, f4)) shouldBe And(nel(f1, f2, f3, f4)) + And(nel(f1, f3)) and And(nel(f2, f5, f4)) shouldBe And(nel(f1, f3, f2, f5, f4)) + And(nel(f1, f3)) and And(nel(f2, f3, f5)) shouldBe And(nel(f1, f3, f2, f3, f5)) + } + } + + context("when only the left hand operand is an instance of And") { + should( + "return a single And instance appending the right hand operand to the operands of the left hand And", + ) { + val f1 = + Or( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + And(nel(f1, f2)) and f3 shouldBe And(nel(f1, f2, f3)) + And(nel(f1, f3, f5)) and f4 shouldBe And(nel(f1, f3, f5, f4)) + And(nel(f1, f3, f5, f2)) and f2 and f4 shouldBe And(nel(f1, f3, f5, f2, f2, f4)) + } + } + + context("when only the right hand operand is an instance of And") { + should( + "return a single And instance prepending the left hand operand to the operands of the right hand And", + ) { + val f1 = + Or( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + f3 and And(nel(f1, f2)) shouldBe And(nel(f3, f1, f2)) + f4 and And(nel(f1, f3, f5)) shouldBe And(nel(f4, f1, f3, f5)) + f2 and And(nel(f1, f3, f5, f2)) and f4 shouldBe And(nel(f2, f1, f3, f5, f2, f4)) + } + } + + context("when none of the operands is an instance of And") { + should("return an And instance containing both operands") { + val f1 = + Or( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + f1 and f2 shouldBe And(nonEmptyListOf(f1, f2)) + f1 and f3 shouldBe And(nonEmptyListOf(f1, f3)) + f2 and f3 shouldBe And(nonEmptyListOf(f2, f3)) + f3 and f1 shouldBe And(nonEmptyListOf(f3, f1)) + f3 and f2 and f1 shouldBe And(nonEmptyListOf(f3, f2, f1)) + } + } + } + + context("The or operator") { + context("when applied to two instances of Or") { + should("return a single Or instance concatenating the operands of both") { + val f1 = + And( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + Or(nel(f1, f2)) or Or(nel(f3, f4)) shouldBe Or(nel(f1, f2, f3, f4)) + Or(nel(f1, f3)) or Or(nel(f2, f5, f4)) shouldBe Or(nel(f1, f3, f2, f5, f4)) + Or(nel(f1, f3)) or Or(nel(f2, f3, f5)) shouldBe Or(nel(f1, f3, f2, f3, f5)) + } + } + + context("when only the left hor operand is an instance of Or") { + should( + "return a single Or instance appending the right hor operand to the operands of the left hor Or", + ) { + val f1 = + And( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + Or(nel(f1, f2)) or f3 shouldBe Or(nel(f1, f2, f3)) + Or(nel(f1, f3, f5)) or f4 shouldBe Or(nel(f1, f3, f5, f4)) + Or(nel(f1, f3, f5, f2)) or f2 or f4 shouldBe Or(nel(f1, f3, f5, f2, f2, f4)) + } + } + + context("when only the right hor operand is an instance of Or") { + should( + "return a single Or instance prepending the left hor operand to the operands of the right hor Or", + ) { + val f1 = + And( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + f3 or Or(nel(f1, f2)) shouldBe Or(nel(f3, f1, f2)) + f4 or Or(nel(f1, f3, f5)) shouldBe Or(nel(f4, f1, f3, f5)) + f2 or Or(nel(f1, f3, f5, f2)) or f4 shouldBe Or(nel(f2, f1, f3, f5, f2, f4)) + } + } + + context("when none of the operands is an instance of Or") { + should("return an Or instance containing both operands") { + val f1 = + And( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + f1 or f2 shouldBe Or(nonEmptyListOf(f1, f2)) + f1 or f3 shouldBe Or(nonEmptyListOf(f1, f3)) + f2 or f3 shouldBe Or(nonEmptyListOf(f2, f3)) + f3 or f1 shouldBe Or(nonEmptyListOf(f3, f1)) + f3 or f2 or f1 shouldBe Or(nonEmptyListOf(f3, f2, f1)) + } + } + } + + context("The not operator") { + context("when applied to an instance of Not") { + should("return the operand of Not") { + val f1 = + And( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + !Not(f1) shouldBe f1 + !Not(f2) shouldBe f2 + !Not(f3) shouldBe f3 + } + } + + context("when applied to an instance of Comparison") { + should("invert the comparison operator") { + checkAll(Arb.comparable(), Arb.comparable()) { lhs, rhs -> + !Comparison(Op.EQ, lhs, rhs) shouldBe Comparison(Op.NOT_EQ, lhs, rhs) + !Comparison(Op.NOT_EQ, lhs, rhs) shouldBe Comparison(Op.EQ, lhs, rhs) + !Comparison(Op.LESS, lhs, rhs) shouldBe Comparison(Op.GREATER_EQ, lhs, rhs) + !Comparison(Op.LESS_EQ, lhs, rhs) shouldBe Comparison(Op.GREATER, lhs, rhs) + !Comparison(Op.GREATER, lhs, rhs) shouldBe Comparison(Op.LESS_EQ, lhs, rhs) + !Comparison(Op.GREATER_EQ, lhs, rhs) shouldBe Comparison(Op.LESS, lhs, rhs) + } + } + } + + context("when the operand is not an instance of Not") { + should("return a Not instance of the operand") { + val f1 = + And( + nel( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + !f1 shouldBe Not(f1) + !f2 shouldBe Not(f2) + !f3 shouldBe Not(f3) + } + } + } + + context("The toString method") { + context("of an And expression") { + should("concatenate the serialized operands with &&, parenthesizing Or instances") { + val f1 = + Or( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + And(f1, f2, f3, f4).toString() shouldBe "($f1) && $f2 && $f3 && $f4" + And(f5, f1, f2).toString() shouldBe "$f5 && ($f1) && $f2" + And(f3, f1).toString() shouldBe "$f3 && ($f1)" + } + } + + context("of an Or expression") { + should("concatenate the serialized operands with ||") { + val f1 = + And( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ) + + val f2 = Test(Relative()["b"]) + + val f3 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f4 = Not(Test(Absolute()["d"])) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + Or(f1, f2, f3, f4).toString() shouldBe "$f1 || $f2 || $f3 || $f4" + Or(f5, f1, f2).toString() shouldBe "$f5 || $f1 || $f2" + Or(f3, f1).toString() shouldBe "$f3 || $f1" + } + } + + context("of a Not expression") { + should( + "prepend an exclamation mark to the serialized operand, parenthesizing Or, Comparision and And", + ) { + val f1 = + And( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ) + + val f2 = + Or( + Test(Relative()["a"]), + Comparison( + Op.LESS, + Literal(1), + Literal(2), + ), + ) + + val f3 = Test(Relative()["b"]) + + val f4 = + Match( + Relative()["c"], + Literal("a.*"), + true, + ) + + val f5 = + Comparison( + Op.GREATER, + Absolute()["e"], + Literal(2), + ) + + Not(f1).toString() shouldBe "!($f1)" + Not(f2).toString() shouldBe "!($f2)" + Not(f3).toString() shouldBe "!$f3" + Not(f4).toString() shouldBe "!$f4" + Not(f5).toString() shouldBe "!($f5)" + } + } + + context("of an Existence expression") { + should("return the serialized query") { + checkAll(Arb.queryExpression()) { + Test(it).toString() shouldBe it.toString() + } + } + } + + context("of a Match expression") { + should("serialize to a match function expression if matchEntire = true") { + checkAll(Arb.matchOperand(), Arb.matchOperand()) { subject, pattern -> + Match(subject, pattern, matchEntire = true).toString() shouldBe + "match($subject, $pattern)" + } + } + + should("serialize to a search function expression if matchEntire = false") { + checkAll(Arb.matchOperand(), Arb.matchOperand()) { subject, pattern -> + Match(subject, pattern, matchEntire = false).toString() shouldBe + "search($subject, $pattern)" + } + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/FunctionExpressionTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/FunctionExpressionTest.kt new file mode 100644 index 0000000..9cdb675 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/FunctionExpressionTest.kt @@ -0,0 +1,37 @@ +package com.kobil.vertx.jsonpath + +import com.kobil.vertx.jsonpath.testing.comparable +import com.kobil.vertx.jsonpath.testing.queryExpression +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.checkAll + +class FunctionExpressionTest : + ShouldSpec({ + context("the toString method") { + context("of the Length function") { + should("serialize to 'length' followed by the parenthesized serialized argument") { + checkAll(Arb.comparable()) { + FunctionExpression.Length(it).toString() shouldBe "length($it)" + } + } + } + + context("of the Count function") { + should("serialize to 'count' followed by the parenthesized serialized argument") { + checkAll(Arb.queryExpression()) { + FunctionExpression.Count(it).toString() shouldBe "count($it)" + } + } + } + + context("of the Value function") { + should("serialize to 'value' followed by the parenthesized serialized argument") { + checkAll(Arb.queryExpression()) { + FunctionExpression.Value(it).toString() shouldBe "value($it)" + } + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/JsonPathQueryTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/JsonPathQueryTest.kt new file mode 100644 index 0000000..6bc482c --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/JsonPathQueryTest.kt @@ -0,0 +1,351 @@ +package com.kobil.vertx.jsonpath + +import com.kobil.vertx.jsonpath.FilterExpression.Test +import com.kobil.vertx.jsonpath.QueryExpression.Relative +import com.kobil.vertx.jsonpath.Segment.ChildSegment +import com.kobil.vertx.jsonpath.Segment.DescendantSegment +import com.kobil.vertx.jsonpath.Selector.Index +import com.kobil.vertx.jsonpath.Selector.Name +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.arbitrary.int +import io.kotest.property.arbitrary.orNull +import io.kotest.property.arbitrary.string +import io.kotest.property.arbitrary.triple +import io.kotest.property.checkAll + +class JsonPathQueryTest : + ShouldSpec({ + context("The get operator") { + context("applied to one or more strings") { + should("append a child segment selecting the specified field names") { + checkAll(Arb.string(), Arb.string(), Arb.string()) { a, b, c -> + QueryExpression.absolute()[a].segments shouldBe + listOf( + ChildSegment(Name(a)), + ) + + QueryExpression.absolute()[a, b].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(b))), + ) + + QueryExpression.absolute()[a, c].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(c))), + ) + + QueryExpression.absolute()[a, b, c].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(b), Name(c))), + ) + + QueryExpression.absolute()[a, c][b].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(c))), + ChildSegment(listOf(Name(b))), + ) + } + } + } + + context("applied to one or more integers") { + should("append a child segment selecting the specified indices") { + checkAll(Arb.int(), Arb.int(), Arb.int()) { a, b, c -> + QueryExpression.absolute()[a].segments shouldBe + listOf( + ChildSegment(Index(a)), + ) + + QueryExpression.absolute()[a, b].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(b))), + ) + + QueryExpression.absolute()[a, c].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(c))), + ) + + QueryExpression.absolute()[a, b, c].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(b), Index(c))), + ) + + QueryExpression.absolute()[a, c][b].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(c))), + ChildSegment(listOf(Index(b))), + ) + } + } + } + + context("applied to one or more selectors") { + should("append a child segment using the specified selectors") { + checkAll( + Arb.string(), + Arb.int(), + Arb.triple(Arb.int().orNull(), Arb.int().orNull(), Arb.int().orNull()), + ) { name, idx, (first, last, step) -> + val n = Selector.name(name) + val i = Selector.index(idx) + val w = Selector.Wildcard + val s = Selector.slice(first, last, step) + val f = Selector.filter(Test(Relative()["a"])) + + QueryExpression.absolute()[n].segments shouldBe + listOf( + ChildSegment(n), + ) + + QueryExpression.absolute()[n, i].segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + ) + + QueryExpression.absolute()[n, i, s].segments shouldBe + listOf( + ChildSegment(listOf(n, i, s)), + ) + + QueryExpression.absolute()[n, i][s, w].segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + ChildSegment(listOf(s, w)), + ) + + QueryExpression.absolute()[n, i, f][w][i, f, s].segments shouldBe + listOf( + ChildSegment(listOf(n, i, f)), + ChildSegment(listOf(w)), + ChildSegment(listOf(i, f, s)), + ) + } + } + } + } + + context("The selectChildren function") { + should("append a child segment using the specified selectors") { + checkAll( + Arb.string(), + Arb.int(), + Arb.triple(Arb.int().orNull(), Arb.int().orNull(), Arb.int().orNull()), + ) { name, idx, (first, last, step) -> + val n = Selector.name(name) + val i = Selector.index(idx) + val w = Selector.Wildcard + val s = Selector.slice(first, last, step) + val f = Selector.filter(Test(Relative()["a"])) + + QueryExpression.absolute().selectChildren(n).segments shouldBe + listOf( + ChildSegment(n), + ) + + QueryExpression.absolute().selectChildren(n, i).segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + ) + + QueryExpression.absolute().selectChildren(n, i, s).segments shouldBe + listOf( + ChildSegment(listOf(n, i, s)), + ) + + QueryExpression + .absolute() + .selectChildren(n, i) + .selectChildren(s, w) + .segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + ChildSegment(listOf(s, w)), + ) + + QueryExpression + .absolute() + .selectChildren( + n, + i, + f, + ).selectChildren(w) + .selectChildren(i, f, s) + .segments shouldBe + listOf( + ChildSegment(listOf(n, i, f)), + ChildSegment(listOf(w)), + ChildSegment(listOf(i, f, s)), + ) + } + } + } + + context("The selectDescendants function") { + should("append a descendant segment using the specified selectors") { + checkAll( + Arb.string(), + Arb.int(), + Arb.triple(Arb.int().orNull(), Arb.int().orNull(), Arb.int().orNull()), + ) { name, idx, (first, last, step) -> + val n = Selector.name(name) + val i = Selector.index(idx) + val w = Selector.Wildcard + val s = Selector.slice(first, last, step) + val f = Selector.filter(Test(Relative()["a"])) + + QueryExpression.absolute().selectDescendants(n).segments shouldBe + listOf( + DescendantSegment(n), + ) + + QueryExpression.absolute().selectDescendants(n, i).segments shouldBe + listOf( + DescendantSegment(listOf(n, i)), + ) + + QueryExpression.absolute().selectDescendants(n, i, s).segments shouldBe + listOf( + DescendantSegment(listOf(n, i, s)), + ) + + QueryExpression + .absolute() + .selectChildren(n, i) + .selectDescendants(s, w) + .segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + DescendantSegment(listOf(s, w)), + ) + + QueryExpression + .absolute() + .selectDescendants( + n, + i, + f, + ).selectChildren(w) + .selectDescendants(i, f, s) + .segments shouldBe + listOf( + DescendantSegment(listOf(n, i, f)), + ChildSegment(listOf(w)), + DescendantSegment(listOf(i, f, s)), + ) + } + } + } + + context("The selectAllChildren function") { + should("append a wildcard selector child segment") { + QueryExpression.absolute().selectAllChildren().segments shouldBe + listOf( + ChildSegment(Selector.WILDCARD), + ) + + QueryExpression + .absolute() + .field("a") + .selectAllChildren() + .segments shouldBe + listOf( + ChildSegment(Name("a")), + ChildSegment(Selector.Wildcard), + ) + } + } + + context("The selectAllDescendants function") { + should("append a wildcard selector descendant segment") { + QueryExpression.absolute().selectAllDescendants().segments shouldBe + listOf( + DescendantSegment(Selector.WILDCARD), + ) + + QueryExpression + .absolute() + .field("a") + .selectAllDescendants() + .segments shouldBe + listOf( + ChildSegment(Name("a")), + DescendantSegment(Selector.Wildcard), + ) + } + } + + context("The field function") { + should("append a child segment selecting the specified field names") { + checkAll(Arb.string(), Arb.string(), Arb.string()) { a, b, c -> + QueryExpression.absolute().field(a).segments shouldBe + listOf( + ChildSegment(Name(a)), + ) + + QueryExpression.absolute().field(a, b).segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(b))), + ) + + QueryExpression.absolute().field(a, c).segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(c))), + ) + + QueryExpression.absolute().field(a, b, c).segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(b), Name(c))), + ) + + QueryExpression + .absolute() + .field(a, c) + .field(b) + .segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(c))), + ChildSegment(listOf(Name(b))), + ) + } + } + } + + context("The index function") { + should("append a child segment selecting the specified indices") { + checkAll(Arb.int(), Arb.int(), Arb.int()) { a, b, c -> + QueryExpression.absolute().index(a).segments shouldBe + listOf( + ChildSegment(Index(a)), + ) + + QueryExpression.absolute().index(a, b).segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(b))), + ) + + QueryExpression.absolute().index(a, c).segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(c))), + ) + + QueryExpression.absolute().index(a, b, c).segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(b), Index(c))), + ) + + QueryExpression + .absolute() + .index(a, c) + .index(b) + .segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(c))), + ChildSegment(listOf(Index(b))), + ) + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/JsonPathTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/JsonPathTest.kt new file mode 100644 index 0000000..29903ec --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/JsonPathTest.kt @@ -0,0 +1,826 @@ +package com.kobil.vertx.jsonpath + +import com.kobil.vertx.jsonpath.FilterExpression.Test +import com.kobil.vertx.jsonpath.JsonPath.Companion.onlyPaths +import com.kobil.vertx.jsonpath.QueryExpression.Relative +import com.kobil.vertx.jsonpath.Segment.ChildSegment +import com.kobil.vertx.jsonpath.Segment.DescendantSegment +import com.kobil.vertx.jsonpath.Selector.Index +import com.kobil.vertx.jsonpath.Selector.Name +import com.kobil.vertx.jsonpath.error.MultipleResults +import com.kobil.vertx.jsonpath.error.RequiredJsonValueError.NoResult +import com.kobil.vertx.jsonpath.testing.normalizedJsonPath +import io.kotest.assertions.arrow.core.shouldBeLeft +import io.kotest.assertions.arrow.core.shouldBeNone +import io.kotest.assertions.arrow.core.shouldBeRight +import io.kotest.assertions.arrow.core.shouldBeSome +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldBeEmpty +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder +import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeInstanceOf +import io.kotest.property.Arb +import io.kotest.property.arbitrary.int +import io.kotest.property.arbitrary.list +import io.kotest.property.arbitrary.orNull +import io.kotest.property.arbitrary.string +import io.kotest.property.arbitrary.triple +import io.kotest.property.checkAll +import io.vertx.core.json.JsonObject +import io.vertx.kotlin.core.json.jsonArrayOf +import io.vertx.kotlin.core.json.jsonObjectOf + +class JsonPathTest : + ShouldSpec({ + context("The evaluateOne function") { + context("called on a JSON object") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1 + .evaluateOne(jsonObjectOf("a" to 1, "b" to 2)) + .shouldBeRight() shouldBeSome JsonNode(1, JsonPath["a"]) + jsonObjectOf("a" to 1, "b" to 2) + .get(jsonPath1) + .shouldBeRight() shouldBeSome 1 + + jsonPath1 + .evaluateOne(jsonObjectOf("a" to "string")) + .shouldBeRight() shouldBeSome JsonNode("string", JsonPath["a"]) + jsonObjectOf("a" to "string") + .get(jsonPath1) + .shouldBeRight() shouldBeSome "string" + + jsonPath2 + .evaluateOne(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldBeRight() shouldBeSome JsonNode(true, JsonPath["a"][1]["b"]) + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .get(jsonPath2) + .shouldBeRight() shouldBeSome true + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonPath1 + .evaluateOne(jsonObjectOf("b" to jsonObjectOf("a" to 1))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .evaluateOne(jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .evaluateOne(jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true)))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .evaluateOne(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true)))) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .evaluateOne( + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(1, JsonPath["a"]), + JsonNode(2, JsonPath["b"]["a"]), + JsonNode(3, JsonPath["c"][1]["a"]), + ) + + jsonPath1 + .evaluateOne(jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null))) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode("string", JsonPath["a"]), + JsonNode(null, JsonPath["b"]["a"]), + ) + + jsonPath2 + .evaluateOne( + jsonObjectOf( + "a" to jsonObjectOf("a" to 1), + "b" to jsonObjectOf("a" to 2), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath["a"]), + JsonNode(jsonObjectOf("a" to 2), JsonPath["b"]), + ) + } + } + + context("called on a JSON array") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1 + .evaluateOne(jsonArrayOf(1, 2, 3)) + .shouldBeRight() shouldBeSome JsonNode(1, JsonPath[0]) + + jsonPath1 + .evaluateOne(jsonArrayOf("string", null, true)) + .shouldBeRight() shouldBeSome JsonNode("string", JsonPath[0]) + + jsonPath2 + .evaluateOne(jsonArrayOf(null, jsonObjectOf("b" to true))) + .shouldBeRight() shouldBeSome JsonNode(true, JsonPath[1]["b"]) + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonArrayOf()).shouldBeRight().shouldBeNone() + + jsonPath2 + .evaluateOne(jsonArrayOf(null, jsonObjectOf("a" to true))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .evaluateOne(jsonArrayOf(jsonObjectOf("b" to true))) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .evaluateOne( + jsonArrayOf( + jsonObjectOf("a" to 2), + jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(2, JsonPath[0]["a"]), + JsonNode(3, JsonPath[1][1]["a"]), + ) + + jsonPath2 + .evaluateOne( + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath[0]), + JsonNode(jsonObjectOf("a" to 2), JsonPath[3]), + ) + } + } + } + + context("The getAll function") { + context("called on a JSON object") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1 + .getAll(jsonObjectOf("a" to 1, "b" to 2)) + .shouldContainExactly(1) + + jsonPath1 + .getAll(jsonObjectOf("a" to "string")) + .shouldContainExactly("string") + + jsonPath2 + .getAll(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldContainExactly(true) + } + + should("return an empty list if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonPath1 + .getAll(jsonObjectOf("b" to jsonObjectOf("a" to 1))) + .shouldBeEmpty() + + jsonPath2 + .getAll(jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldBeEmpty() + + jsonPath2 + .getAll(jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true)))) + .shouldBeEmpty() + + jsonPath2 + .getAll(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true)))) + .shouldBeEmpty() + } + + should("return all results if there are multiple") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .getAll( + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldContainExactlyInAnyOrder(1, 2, 3) + + jsonPath1 + .getAll(jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null))) + .shouldContainExactlyInAnyOrder("string", null) + + jsonPath2 + .getAll( + jsonObjectOf( + "a" to jsonObjectOf("a" to 1), + "b" to jsonObjectOf("a" to 2), + ), + ).shouldContainExactlyInAnyOrder( + jsonObjectOf("a" to 1), + jsonObjectOf("a" to 2), + ) + } + } + + context("called on a JSON array") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1 + .getAll(jsonArrayOf(1, 2, 3)) + .shouldContainExactly(1) + + jsonPath1 + .getAll(jsonArrayOf("string", null, true)) + .shouldContainExactly("string") + + jsonPath2 + .getAll(jsonArrayOf(null, jsonObjectOf("b" to true))) + .shouldContainExactly(true) + } + + should("return an empty list if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonArrayOf()).shouldBeRight().shouldBeNone() + + jsonPath2 + .getAll(jsonArrayOf(null, jsonObjectOf("a" to true))) + .shouldBeEmpty() + + jsonPath2 + .getAll(jsonArrayOf(jsonObjectOf("b" to true))) + .shouldBeEmpty() + } + + should("return all results if there are multiple") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .getAll( + jsonArrayOf( + jsonObjectOf("a" to 2), + jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldContainExactly(2, 3) + + jsonPath2 + .getAll( + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ), + ).shouldContainExactly( + jsonObjectOf("a" to 1), + jsonObjectOf("a" to 2), + ) + } + } + } + + context("The getOne function") { + context("called on a JSON object") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1 + .getOne(jsonObjectOf("a" to 1, "b" to 2)) + .shouldBeRight() shouldBeSome 1 + + jsonPath1 + .getOne(jsonObjectOf("a" to "string")) + .shouldBeRight() shouldBeSome "string" + + jsonPath2 + .getOne(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldBeRight() shouldBeSome true + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.getOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonPath1 + .getOne(jsonObjectOf("b" to jsonObjectOf("a" to 1))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .getOne(jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .getOne(jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true)))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .getOne(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true)))) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .getOne( + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(1, JsonPath["a"]), + JsonNode(2, JsonPath["b"]["a"]), + JsonNode(3, JsonPath["c"][1]["a"]), + ) + + jsonPath1 + .getOne(jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null))) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode("string", JsonPath["a"]), + JsonNode(null, JsonPath["b"]["a"]), + ) + + jsonPath2 + .getOne( + jsonObjectOf( + "a" to jsonObjectOf("a" to 1), + "b" to jsonObjectOf("a" to 2), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath["a"]), + JsonNode(jsonObjectOf("a" to 2), JsonPath["b"]), + ) + } + } + + context("called on a JSON array") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1 + .getOne(jsonArrayOf(1, 2, 3)) + .shouldBeRight() shouldBeSome 1 + + jsonPath1 + .getOne(jsonArrayOf("string", null, true)) + .shouldBeRight() shouldBeSome "string" + + jsonPath2 + .getOne(jsonArrayOf(null, jsonObjectOf("b" to true))) + .shouldBeRight() shouldBeSome true + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1.getOne(jsonArrayOf()).shouldBeRight().shouldBeNone() + + jsonPath2 + .getOne(jsonArrayOf(null, jsonObjectOf("a" to true))) + .shouldBeRight() + .shouldBeNone() + + jsonPath2 + .getOne(jsonArrayOf(jsonObjectOf("b" to true))) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .getOne( + jsonArrayOf( + jsonObjectOf("a" to 2), + jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(2, JsonPath[0]["a"]), + JsonNode(3, JsonPath[1][1]["a"]), + ) + + jsonPath2 + .getOne( + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ), + ).shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath[0]), + JsonNode(jsonObjectOf("a" to 2), JsonPath[3]), + ) + } + } + } + + context("The requireOne function") { + context("called on a JSON object") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1 + .requireOne(jsonObjectOf("a" to 1, "b" to 2)) shouldBeRight 1 + + jsonPath1 + .requireOne(jsonObjectOf("a" to "string")) shouldBeRight "string" + + jsonPath2 + .requireOne(jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true)))) + .shouldBeRight(true) + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.requireOne(jsonObjectOf("b" to 2)) shouldBeLeft NoResult + + jsonPath1 + .requireOne(jsonObjectOf("b" to jsonObjectOf("a" to 1))) shouldBeLeft NoResult + + jsonPath2 + .requireOne( + jsonObjectOf( + "b" to + jsonArrayOf( + null, + jsonObjectOf("b" to true), + ), + ), + ) shouldBeLeft NoResult + + jsonPath2 + .requireOne( + jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true))), + ) shouldBeLeft + NoResult + + jsonPath2 + .requireOne( + jsonObjectOf( + "a" to + jsonArrayOf( + null, + jsonObjectOf("a" to true), + ), + ), + ) shouldBeLeft NoResult + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .requireOne( + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(1, JsonPath["a"]), + JsonNode(2, JsonPath["b"]["a"]), + JsonNode(3, JsonPath["c"][1]["a"]), + ) + + jsonPath1 + .requireOne(jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null))) + .shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode("string", JsonPath["a"]), + JsonNode(null, JsonPath["b"]["a"]), + ) + + jsonPath2 + .requireOne( + jsonObjectOf( + "a" to jsonObjectOf("a" to 1), + "b" to jsonObjectOf("a" to 2), + ), + ).shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath["a"]), + JsonNode(jsonObjectOf("a" to 2), JsonPath["b"]), + ) + } + } + + context("called on a JSON array") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1 + .requireOne(jsonArrayOf(1, 2, 3)) shouldBeRight 1 + + jsonPath1 + .requireOne(jsonArrayOf("string", null, true)) shouldBeRight "string" + + jsonPath2 + .requireOne(jsonArrayOf(null, jsonObjectOf("b" to true))) shouldBeRight true + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonPath1.requireOne(jsonArrayOf()) shouldBeLeft NoResult + + jsonPath2 + .requireOne(jsonArrayOf(null, jsonObjectOf("a" to true))) shouldBeLeft NoResult + + jsonPath2 + .requireOne(jsonArrayOf(jsonObjectOf("b" to true))) shouldBeLeft NoResult + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonPath1 + .requireOne( + jsonArrayOf( + jsonObjectOf("a" to 2), + jsonArrayOf(1, jsonObjectOf("a" to 3)), + ), + ).shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(2, JsonPath[0]["a"]), + JsonNode(3, JsonPath[1][1]["a"]), + ) + + jsonPath2 + .requireOne( + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ), + ).shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath[0]), + JsonNode(jsonObjectOf("a" to 2), JsonPath[3]), + ) + } + } + } + + context("The plus operator") { + context("specifying a single segment") { + should("append the segment") { + val n = Selector.name("a") + val i = Selector.index(1) + val s = Selector.slice(1, -1, 2) + val w = Selector.Wildcard + val f = Selector.filter(QueryExpression.absolute().exists()) + + (JsonPath.ROOT + ChildSegment(n)).segments shouldBe + listOf( + ChildSegment(n), + ) + + (JsonPath.ROOT + ChildSegment(i, f)).segments shouldBe + listOf( + ChildSegment(i, f), + ) + + ( + JsonPath.ROOT + DescendantSegment(n) + ChildSegment(w) + + DescendantSegment( + s, + f, + ) + ).segments shouldBe + listOf( + DescendantSegment(n), + ChildSegment(w), + DescendantSegment(s, f), + ) + } + } + + context("specifying iterable segments") { + should("append all segments") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + val n = Selector.name("a") + + (JsonPath.ROOT + segments).segments shouldBe segments + (JsonPath.ROOT + ChildSegment(n) + segments).segments shouldBe + listOf(ChildSegment(n)) + segments + } + } + } + } + + context("The onlyPaths function") { + should("return exactly the path fields of the list of JsonNodes") { + checkAll(Arb.list(Arb.normalizedJsonPath(), 0..32)) { paths -> + paths.map { JsonNode(null, it) }.onlyPaths() shouldContainExactly paths + } + } + } + + context("The static get operator") { + context("applied to one or more strings") { + should("append a child segment selecting the specified field names") { + checkAll(Arb.string(), Arb.string(), Arb.string()) { a, b, c -> + JsonPath[a].segments shouldBe + listOf( + ChildSegment(Name(a)), + ) + + JsonPath[a, b].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(b))), + ) + + JsonPath[a, c].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(c))), + ) + + JsonPath[a, b, c].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(b), Name(c))), + ) + + JsonPath[a, c][b].segments shouldBe + listOf( + ChildSegment(listOf(Name(a), Name(c))), + ChildSegment(listOf(Name(b))), + ) + } + } + } + + context("applied to one or more integers") { + should("append a child segment selecting the specified indices") { + checkAll(Arb.int(), Arb.int(), Arb.int()) { a, b, c -> + JsonPath[a].segments shouldBe + listOf( + ChildSegment(Index(a)), + ) + + JsonPath[a, b].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(b))), + ) + + JsonPath[a, c].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(c))), + ) + + JsonPath[a, b, c].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(b), Index(c))), + ) + + JsonPath[a, c][b].segments shouldBe + listOf( + ChildSegment(listOf(Index(a), Index(c))), + ChildSegment(listOf(Index(b))), + ) + } + } + } + + context("applied to one or more selectors") { + should("append a child segment using the specified selectors") { + checkAll( + Arb.string(), + Arb.int(), + Arb.triple(Arb.int().orNull(), Arb.int().orNull(), Arb.int().orNull()), + ) { name, idx, (first, last, step) -> + val n = Selector.name(name) + val i = Selector.index(idx) + val w = Selector.Wildcard + val s = Selector.slice(first, last, step) + val f = Selector.filter(Test(Relative()["a"])) + + JsonPath[n].segments shouldBe + listOf( + ChildSegment(n), + ) + + JsonPath[n, i].segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + ) + + JsonPath[n, i, s].segments shouldBe + listOf( + ChildSegment(listOf(n, i, s)), + ) + + JsonPath[n, i][s, w].segments shouldBe + listOf( + ChildSegment(listOf(n, i)), + ChildSegment(listOf(s, w)), + ) + + JsonPath[n, i, f][w][i, f, s].segments shouldBe + listOf( + ChildSegment(listOf(n, i, f)), + ChildSegment(listOf(w)), + ChildSegment(listOf(i, f, s)), + ) + } + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/QueryExpressionTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/QueryExpressionTest.kt new file mode 100644 index 0000000..d1e57c0 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/QueryExpressionTest.kt @@ -0,0 +1,219 @@ +package com.kobil.vertx.jsonpath + +import arrow.core.toNonEmptyListOrNull +import com.kobil.vertx.jsonpath.QueryExpression.Absolute +import com.kobil.vertx.jsonpath.QueryExpression.Relative +import com.kobil.vertx.jsonpath.Segment.ChildSegment +import com.kobil.vertx.jsonpath.Segment.DescendantSegment +import com.kobil.vertx.jsonpath.testing.normalizedJsonPath +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.arbitrary.filter +import io.kotest.property.arbitrary.map +import io.kotest.property.checkAll + +class QueryExpressionTest : + ShouldSpec({ + context("The count method") { + should("return a count function called on the query expression") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + val abs = Absolute(segments) + val rel = Relative(segments) + + abs.count() shouldBe FunctionExpression.Count(abs) + rel.count() shouldBe FunctionExpression.Count(rel) + } + } + } + + context("The value method") { + should("return a value function called on the query expression") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + val abs = Absolute(segments) + val rel = Relative(segments) + + abs.value() shouldBe FunctionExpression.Value(abs) + rel.value() shouldBe FunctionExpression.Value(rel) + } + } + } + + context("The plus operator") { + context("called on an absolute query") { + context("specifying a single segment") { + should("append the segment") { + val n = Selector.name("a") + val i = Selector.index(1) + val s = Selector.slice(1, -1, 2) + val w = Selector.Wildcard + val f = Selector.filter(QueryExpression.absolute().exists()) + + (Absolute() + ChildSegment(n)).segments shouldBe + listOf( + ChildSegment(n), + ) + + (Absolute() + ChildSegment(i, f)).segments shouldBe + listOf( + ChildSegment(i, f), + ) + + ( + Absolute() + DescendantSegment(n) + ChildSegment(w) + + DescendantSegment( + s, + f, + ) + ).segments shouldBe + listOf( + DescendantSegment(n), + ChildSegment(w), + DescendantSegment(s, f), + ) + } + } + + context("specifying iterable segments") { + should("append all segments") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + val n = Selector.name("a") + + (Absolute() + segments).segments shouldBe segments + (Absolute() + ChildSegment(n) + segments).segments shouldBe + listOf(ChildSegment(n)) + segments + } + } + } + } + + context("called on a relative query") { + context("specifying a single segment") { + should("append the segment") { + val n = Selector.name("a") + val i = Selector.index(1) + val s = Selector.slice(1, -1, 2) + val w = Selector.Wildcard + val f = Selector.filter(QueryExpression.relative().exists()) + + (Relative() + ChildSegment(n)).segments shouldBe + listOf( + ChildSegment(n), + ) + + (Relative() + ChildSegment(i, f)).segments shouldBe + listOf( + ChildSegment(i, f), + ) + + ( + Relative() + DescendantSegment(n) + ChildSegment(w) + + DescendantSegment( + s, + f, + ) + ).segments shouldBe + listOf( + DescendantSegment(n), + ChildSegment(w), + DescendantSegment(s, f), + ) + } + } + + context("specifying iterable segments") { + should("append all segments") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + val n = Selector.name("a") + + (Relative() + segments).segments shouldBe segments + (Relative() + ChildSegment(n) + segments).segments shouldBe + listOf(ChildSegment(n)) + segments + } + } + } + } + } + + context("The toString function") { + context("called on an absolute query") { + should("return the serialized segments, prefixed by $") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + Absolute(segments).toString() shouldBe "$" + segments.joinToString("") + } + } + } + + context("called on a relative query") { + should("return the serialized segments, prefixed by @") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + Relative(segments).toString() shouldBe "@" + segments.joinToString("") + } + } + } + } + + context("The static absolute method") { + context("called without an argument") { + should("return an empty absolute query") { + QueryExpression.absolute() shouldBe Absolute(listOf()) + } + } + + context("applied to a list of segments") { + should("return an absolute query with the same list of segments") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + QueryExpression.absolute(segments) shouldBe Absolute(segments) + } + } + } + + context("applied to vararg segments") { + should("return an absolute query with the same segments") { + checkAll( + Arb + .normalizedJsonPath() + .map { it.segments.toNonEmptyListOrNull() } + .filter { it != null }, + ) { segments -> + QueryExpression.absolute( + segments!!.head, + *segments.tail.toTypedArray(), + ) shouldBe Absolute(segments) + } + } + } + } + + context("The static relative method") { + context("called without an argument") { + should("return an empty relative query") { + QueryExpression.relative() shouldBe Relative(listOf()) + } + } + + context("applied to a list of segments") { + should("return a relative query with the same list of segments") { + checkAll(Arb.normalizedJsonPath()) { (segments) -> + QueryExpression.relative(segments) shouldBe Relative(segments) + } + } + } + + context("applied to vararg segments") { + should("return a relative query with the same segments") { + checkAll( + Arb + .normalizedJsonPath() + .map { it.segments.toNonEmptyListOrNull() } + .filter { it != null }, + ) { segments -> + QueryExpression.relative( + segments!!.head, + *segments.tail.toTypedArray(), + ) shouldBe Relative(segments) + } + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/SegmentTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/SegmentTest.kt new file mode 100644 index 0000000..e707661 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/SegmentTest.kt @@ -0,0 +1,130 @@ +package com.kobil.vertx.jsonpath + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe + +class SegmentTest : + ShouldSpec({ + context("The ChildSegment") { + context("primary constructor") { + should("throw when called with an empty list") { + shouldThrow { + Segment.ChildSegment(listOf()) + } + } + } + + context("toString method") { + should( + "return a string of all selectors, joined by commas, enclosed in square brackets", + ) { + Segment.ChildSegment("a", "b", "c").toString() shouldBe "['a','b','c']" + Segment.ChildSegment("a").toString() shouldBe "['a']" + Segment.ChildSegment(1).toString() shouldBe "[1]" + Segment.ChildSegment(Selector.Wildcard).toString() shouldBe "[*]" + Segment + .ChildSegment( + Selector.name("a"), + Selector.Wildcard, + Selector.index(1), + ).toString() shouldBe "['a',*,1]" + } + } + } + + context("The DescendantSegment") { + context("primary constructor") { + should("throw when called with an empty list") { + shouldThrow { + Segment.DescendantSegment(listOf()) + } + } + } + + context("toString method") { + should( + "return a string of all selectors, separated by commas, enclosed in square brackets, preceded by ..", + ) { + Segment.DescendantSegment("a", "b", "c").toString() shouldBe "..['a','b','c']" + Segment.DescendantSegment("a").toString() shouldBe "..['a']" + Segment.DescendantSegment(1).toString() shouldBe "..[1]" + Segment.DescendantSegment(Selector.Wildcard).toString() shouldBe "..[*]" + Segment + .DescendantSegment(Selector.name("a"), Selector.Wildcard, Selector.index(1)) + .toString() shouldBe "..['a',*,1]" + } + } + } + + context("The child static function") { + context("taking a list of selectors") { + should("throw on an empty list") { + shouldThrow { + Segment.child(listOf()) + } + } + + should("return a child segment with the specified list of selectors") { + val sel = + listOf( + Selector.name("a"), + Selector.index(1), + Selector.slice(1, -1, 2), + Selector.Wildcard, + Selector.Filter(QueryExpression.absolute().exists()), + ) + + Segment.child(sel) shouldBe Segment.ChildSegment(sel) + } + } + + context("taking varargs") { + should("return a child segment with the specified selectors") { + val n = Selector.name("a") + val i = Selector.index(1) + val s = Selector.slice(1, -1, 2) + val w = Selector.Wildcard + val f = Selector.Filter(QueryExpression.absolute().exists()) + + Segment.child(n, i, s, w, f) shouldBe Segment.ChildSegment(listOf(n, i, s, w, f)) + } + } + } + + context("The descendant static function") { + context("taking a list of selectors") { + should("throw on an empty list") { + shouldThrow { + Segment.descendant(listOf()) + } + } + + should("return a descendant segment with the specified list of selectors") { + val sel = + listOf( + Selector.name("a"), + Selector.index(1), + Selector.slice(1, -1, 2), + Selector.Wildcard, + Selector.filter(QueryExpression.absolute().exists()), + ) + + Segment.descendant(sel) shouldBe Segment.DescendantSegment(sel) + } + } + + context("taking varargs") { + should("return a descendant segment with the specified selectors") { + val n = Selector.name("a") + val i = Selector.index(1) + val s = Selector.slice(1, -1, 2) + val w = Selector.Wildcard + val f = Selector.filter(QueryExpression.absolute().exists()) + + Segment.descendant(n, i, s, w, f) shouldBe + Segment.DescendantSegment(listOf(n, i, s, w, f)) + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/SelectorTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/SelectorTest.kt new file mode 100644 index 0000000..06109ec --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/SelectorTest.kt @@ -0,0 +1,218 @@ +package com.kobil.vertx.jsonpath + +import arrow.core.nonEmptyListOf +import com.kobil.vertx.jsonpath.ComparableExpression.Literal +import com.kobil.vertx.jsonpath.FilterExpression.Comparison +import com.kobil.vertx.jsonpath.FilterExpression.Not +import com.kobil.vertx.jsonpath.FilterExpression.Or +import com.kobil.vertx.jsonpath.FilterExpression.Test +import com.kobil.vertx.jsonpath.QueryExpression.Relative +import com.kobil.vertx.jsonpath.Segment.ChildSegment +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.arbitrary.int +import io.kotest.property.arbitrary.string +import io.kotest.property.checkAll + +class SelectorTest : + ShouldSpec({ + context("the toString method") { + context("of a name selector") { + should("return the name enclosed in single quotes") { + checkAll(Arb.string()) { + Selector.Name(it).toString() shouldBe "'$it'" + } + } + } + + context("of an index selector") { + should("return the index") { + checkAll(Arb.int()) { + Selector.Index(it).toString() shouldBe "$it" + } + } + } + + context("of the wildcard selector") { + should("return a literal *") { + Selector.Wildcard.toString() shouldBe "*" + } + } + + context("of a slice selector") { + should("return the three components separated by colons") { + checkAll(Arb.int(), Arb.int(), Arb.int()) { first, last, step -> + Selector.Slice(first, last, step).toString() shouldBe "$first:$last:$step" + } + } + + should("omit the step component when it is null") { + checkAll(Arb.int(), Arb.int()) { first, last -> + Selector.Slice(first, last, null).toString() shouldBe "$first:$last" + } + } + + should("have an empty first component when it is null") { + checkAll(Arb.int(), Arb.int()) { last, step -> + Selector.Slice(null, last, step).toString() shouldBe ":$last:$step" + } + } + + should("have an empty last component when it is null") { + checkAll(Arb.int(), Arb.int()) { first, step -> + Selector.Slice(first, null, step).toString() shouldBe "$first::$step" + } + } + + should("have empty first and last components when they are both null") { + checkAll(Arb.int()) { step -> + Selector.Slice(null, null, step).toString() shouldBe "::$step" + } + } + + should("return a single colon if all components are null") { + Selector.Slice(null, null, null).toString() shouldBe ":" + } + } + + context("of a filter selector") { + should("return the serialized filter expression preceded by a question mark") { + Selector + .Filter( + Test( + Relative(ChildSegment(Selector.Name("a"))), + ), + ).toString() shouldBe "?@['a']" + } + } + } + + context("the invoke operator") { + context("called on a string") { + should("return a name selector with the given field name") { + checkAll(Arb.string()) { + Selector(it) shouldBe Selector.Name(it) + } + } + } + + context("called on an integer") { + should("return an index selector with the given index") { + checkAll(Arb.int()) { + Selector(it) shouldBe Selector.Index(it) + } + } + } + + context("called on an IntProgression") { + should("return an equivalent slice selector") { + Selector(1..2) shouldBe Selector.Slice(1, 3, 1) + Selector(1..<5) shouldBe Selector.Slice(1, 5, 1) + Selector(1..10 step 2) shouldBe Selector.Slice(1, 10, 2) + Selector(10 downTo 1) shouldBe Selector.Slice(10, 0, -1) + Selector(10 downTo 1 step 4) shouldBe Selector.Slice(10, 1, -4) + } + } + + context("called on three nullable integers") { + should("return a slice selector with the same parameters") { + checkAll(Arb.int(), Arb.int(), Arb.int()) { first, last, step -> + Selector(first, last, step) shouldBe Selector.Slice(first, last, step) + } + } + } + + context("called on two nullable integers") { + should("return a slice selector with the same parameters and a null step") { + checkAll(Arb.int(), Arb.int()) { first, last -> + Selector(first, last) shouldBe Selector.Slice(first, last, null) + } + } + } + + context("called on a filter expression") { + should("return a filter selector with the given filter expression") { + val expr1 = Test(Relative(ChildSegment("a"))) + val expr2 = + Or( + nonEmptyListOf( + Comparison( + Comparison.Op.GREATER_EQ, + Relative(ChildSegment("a")), + Literal(1), + ), + Not(Test(Relative(ChildSegment("a")))), + ), + ) + + Selector(expr1) shouldBe Selector.Filter(expr1) + Selector(expr2) shouldBe Selector.Filter(expr2) + } + } + } + + context("the name static function") { + should("return a name selector with the given field name") { + checkAll(Arb.string()) { + Selector.name(it) shouldBe Selector.Name(it) + } + } + } + + context("the index static function") { + should("return an index selector with the given index") { + checkAll(Arb.int()) { + Selector.index(it) shouldBe Selector.Index(it) + } + } + } + + context("the slice static function") { + context("called on an IntProgression") { + should("return an equivalent slice selector") { + Selector.slice(1..2) shouldBe Selector.Slice(1, 3, 1) + Selector.slice(1..<5) shouldBe Selector.Slice(1, 5, 1) + Selector.slice(1..10 step 2) shouldBe Selector.Slice(1, 10, 2) + Selector.slice(10 downTo 1) shouldBe Selector.Slice(10, 0, -1) + Selector.slice(10 downTo 1 step 4) shouldBe Selector.Slice(10, 1, -4) + } + } + + context("called on three nullable integers") { + should("return a slice selector with the same parameters") { + checkAll(Arb.int(), Arb.int(), Arb.int()) { first, last, step -> + Selector.slice(first, last, step) shouldBe Selector.Slice(first, last, step) + } + } + } + + context("called on two nullable integers") { + should("return a slice selector with the same parameters and a null step") { + checkAll(Arb.int(), Arb.int()) { first, last -> + Selector.slice(first, last) shouldBe Selector.Slice(first, last, null) + } + } + } + } + + context("the filter static function") { + should("return a filter selector with the given filter expression") { + val expr1 = Test(Relative(ChildSegment("a"))) + val expr2 = + Or( + nonEmptyListOf( + Comparison( + Comparison.Op.GREATER_EQ, + Relative(ChildSegment("a")), + Literal(1), + ), + Not(Test(Relative(ChildSegment("a")))), + ), + ) + + Selector.filter(expr1) shouldBe Selector.Filter(expr1) + Selector.filter(expr2) shouldBe Selector.Filter(expr2) + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/VertxExtensionsTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/VertxExtensionsTest.kt new file mode 100644 index 0000000..c7683e3 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/VertxExtensionsTest.kt @@ -0,0 +1,690 @@ +package com.kobil.vertx.jsonpath + +import com.kobil.vertx.jsonpath.error.MultipleResults +import com.kobil.vertx.jsonpath.error.RequiredJsonValueError +import io.kotest.assertions.arrow.core.shouldBeLeft +import io.kotest.assertions.arrow.core.shouldBeNone +import io.kotest.assertions.arrow.core.shouldBeRight +import io.kotest.assertions.arrow.core.shouldBeSome +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder +import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeInstanceOf +import io.vertx.core.json.JsonObject +import io.vertx.kotlin.core.json.jsonArrayOf +import io.vertx.kotlin.core.json.jsonObjectOf + +class VertxExtensionsTest : + ShouldSpec({ + context("The get operator") { + context("applied to a JsonObject") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonObjectOf("a" to 1, "b" to 2) + .get(jsonPath1) + .shouldBeRight() shouldBeSome 1 + + jsonObjectOf("a" to "string") + .get(jsonPath1) + .shouldBeRight() shouldBeSome "string" + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .get(jsonPath2) + .shouldBeRight() shouldBeSome true + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonObjectOf("b" to jsonObjectOf("a" to 1)) + .get(jsonPath1) + .shouldBeRight() + .shouldBeNone() + + jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .get(jsonPath2) + .shouldBeRight() + .shouldBeNone() + + jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true))) + .get(jsonPath2) + .shouldBeRight() + .shouldBeNone() + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true))) + .get(jsonPath2) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ).get(jsonPath1) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(1, JsonPath["a"]), + JsonNode(2, JsonPath["b"]["a"]), + JsonNode(3, JsonPath["c"][1]["a"]), + ) + + jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null)) + .get(jsonPath1) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode("string", JsonPath["a"]), + JsonNode(null, JsonPath["b"]["a"]), + ) + + jsonObjectOf("a" to jsonObjectOf("a" to 1), "b" to jsonObjectOf("a" to 2)) + .get(jsonPath2) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath["a"]), + JsonNode(jsonObjectOf("a" to 2), JsonPath["b"]), + ) + } + } + + context("applied to a JsonArray") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf(1, 2, 3) + .get(jsonPath1) + .shouldBeRight() shouldBeSome 1 + + jsonArrayOf("string", null, true) + .get(jsonPath1) + .shouldBeRight() shouldBeSome "string" + + jsonArrayOf(null, jsonObjectOf("b" to true)) + .get(jsonPath2) + .shouldBeRight() shouldBeSome true + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf() + .get(jsonPath1) + .shouldBeRight() + .shouldBeNone() + + jsonArrayOf(null, jsonObjectOf("a" to true)) + .get(jsonPath2) + .shouldBeRight() + .shouldBeNone() + + jsonArrayOf(jsonObjectOf("b" to true)) + .get(jsonPath2) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonArrayOf(jsonObjectOf("a" to 2), jsonArrayOf(1, jsonObjectOf("a" to 3))) + .get(jsonPath1) + .shouldBeLeft() + .results + .shouldContainExactly( + JsonNode(2, JsonPath[0]["a"]), + JsonNode(3, JsonPath[1][1]["a"]), + ) + + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ).get(jsonPath2) + .shouldBeLeft() + .results + .shouldContainExactly( + JsonNode(jsonObjectOf("a" to 1), JsonPath[0]), + JsonNode(jsonObjectOf("a" to 2), JsonPath[3]), + ) + } + } + } + + context("The required function") { + context("applied to a JsonObject") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonObjectOf("a" to 1, "b" to 2) + .required(jsonPath1) + .shouldBeRight(1) + + jsonObjectOf("a" to "string") + .required(jsonPath1) + .shouldBeRight("string") + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .required(jsonPath2) + .shouldBeRight(true) + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonObjectOf("b" to jsonObjectOf("a" to 1)) + .required(jsonPath1) + .shouldBeLeft(RequiredJsonValueError.NoResult) + + jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .required(jsonPath2) + .shouldBeLeft(RequiredJsonValueError.NoResult) + + jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true))) + .required(jsonPath2) + .shouldBeLeft(RequiredJsonValueError.NoResult) + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true))) + .required(jsonPath2) + .shouldBeLeft(RequiredJsonValueError.NoResult) + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ).required(jsonPath1) + .shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(1, JsonPath["a"]), + JsonNode(2, JsonPath["b"]["a"]), + JsonNode(3, JsonPath["c"][1]["a"]), + ) + + jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null)) + .required(jsonPath1) + .shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode("string", JsonPath["a"]), + JsonNode(null, JsonPath["b"]["a"]), + ) + + jsonObjectOf("a" to jsonObjectOf("a" to 1), "b" to jsonObjectOf("a" to 2)) + .required(jsonPath2) + .shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath["a"]), + JsonNode(jsonObjectOf("a" to 2), JsonPath["b"]), + ) + } + } + + context("applied to a JsonArray") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf(1, 2, 3) + .required(jsonPath1) + .shouldBeRight(1) + + jsonArrayOf("string", null, true) + .required(jsonPath1) + .shouldBeRight("string") + + jsonArrayOf(null, jsonObjectOf("b" to true)) + .required(jsonPath2) + .shouldBeRight(true) + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf() + .required(jsonPath1) + .shouldBeLeft(RequiredJsonValueError.NoResult) + + jsonArrayOf(null, jsonObjectOf("a" to true)) + .required(jsonPath2) + .shouldBeLeft(RequiredJsonValueError.NoResult) + + jsonArrayOf(jsonObjectOf("b" to true)) + .required(jsonPath2) + .shouldBeLeft(RequiredJsonValueError.NoResult) + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonArrayOf(jsonObjectOf("a" to 2), jsonArrayOf(1, jsonObjectOf("a" to 3))) + .required(jsonPath1) + .shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactly( + JsonNode(2, JsonPath[0]["a"]), + JsonNode(3, JsonPath[1][1]["a"]), + ) + + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ).required(jsonPath2) + .shouldBeLeft() + .shouldBeInstanceOf() + .results + .shouldContainExactly( + JsonNode(jsonObjectOf("a" to 1), JsonPath[0]), + JsonNode(jsonObjectOf("a" to 2), JsonPath[3]), + ) + } + } + } + + context("The getAll function") { + context("applied to a JsonObject") { + should("return a list containing the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonObjectOf("a" to 1, "b" to 2) + .getAll(jsonPath1) shouldBe listOf(1) + + jsonObjectOf("a" to "string") + .getAll(jsonPath1) shouldBe listOf("string") + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .getAll(jsonPath2) shouldBe listOf(true) + } + + should("return an empty list if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonObjectOf("b" to jsonObjectOf("a" to 1)) + .getAll(jsonPath1) shouldBe listOf() + + jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .getAll(jsonPath2) shouldBe listOf() + + jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true))) + .getAll(jsonPath2) shouldBe listOf() + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true))) + .getAll(jsonPath2) shouldBe listOf() + } + + should("return all results if there are multiple") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ).getAll(jsonPath1) shouldContainExactlyInAnyOrder listOf(1, 2, 3) + + jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null)) + .getAll(jsonPath1) shouldContainExactlyInAnyOrder listOf("string", null) + + jsonObjectOf("a" to jsonObjectOf("a" to 1), "b" to jsonObjectOf("a" to 2)) + .getAll(jsonPath2) shouldContainExactlyInAnyOrder + listOf( + jsonObjectOf("a" to 1), + jsonObjectOf("a" to 2), + ) + } + } + + context("applied to a JsonArray") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf(1, 2, 3) + .getAll(jsonPath1) shouldBe listOf(1) + + jsonArrayOf("string", null, true) + .getAll(jsonPath1) shouldBe listOf("string") + + jsonArrayOf(null, jsonObjectOf("b" to true)) + .getAll(jsonPath2) shouldBe listOf(true) + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf() + .getAll(jsonPath1) shouldBe listOf() + + jsonArrayOf(null, jsonObjectOf("a" to true)) + .getAll(jsonPath2) shouldBe listOf() + + jsonArrayOf(jsonObjectOf("b" to true)) + .getAll(jsonPath2) shouldBe listOf() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonArrayOf(jsonObjectOf("a" to 2), jsonArrayOf(1, jsonObjectOf("a" to 3))) + .getAll(jsonPath1) shouldContainExactly listOf(2, 3) + + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ).getAll(jsonPath2) shouldContainExactly + listOf( + jsonObjectOf("a" to 1), + jsonObjectOf("a" to 2), + ) + } + } + } + + context("The traceOne function") { + context("applied to a JsonObject") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonObjectOf("a" to 1, "b" to 2) + .traceOne(jsonPath1) + .shouldBeRight() shouldBeSome JsonPath["a"] + + jsonObjectOf("a" to "string") + .traceOne(jsonPath1) + .shouldBeRight() shouldBeSome JsonPath["a"] + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .traceOne(jsonPath2) + .shouldBeRight() shouldBeSome JsonPath["a"][1]["b"] + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonObjectOf("b" to jsonObjectOf("a" to 1)) + .traceOne(jsonPath1) + .shouldBeRight() + .shouldBeNone() + + jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .traceOne(jsonPath2) + .shouldBeRight() + .shouldBeNone() + + jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true))) + .traceOne(jsonPath2) + .shouldBeRight() + .shouldBeNone() + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true))) + .traceOne(jsonPath2) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ).traceOne(jsonPath1) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(1, JsonPath["a"]), + JsonNode(2, JsonPath["b"]["a"]), + JsonNode(3, JsonPath["c"][1]["a"]), + ) + + jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null)) + .traceOne(jsonPath1) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode("string", JsonPath["a"]), + JsonNode(null, JsonPath["b"]["a"]), + ) + + jsonObjectOf("a" to jsonObjectOf("a" to 1), "b" to jsonObjectOf("a" to 2)) + .traceOne(jsonPath2) + .shouldBeLeft() + .results + .shouldContainExactlyInAnyOrder( + JsonNode(jsonObjectOf("a" to 1), JsonPath["a"]), + JsonNode(jsonObjectOf("a" to 2), JsonPath["b"]), + ) + } + } + + context("applied to a JsonArray") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf(1, 2, 3) + .traceOne(jsonPath1) + .shouldBeRight() shouldBeSome JsonPath[0] + + jsonArrayOf("string", null, true) + .traceOne(jsonPath1) + .shouldBeRight() shouldBeSome JsonPath[0] + + jsonArrayOf(null, jsonObjectOf("b" to true)) + .traceOne(jsonPath2) + .shouldBeRight() shouldBeSome JsonPath[1]["b"] + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf() + .traceOne(jsonPath1) + .shouldBeRight() + .shouldBeNone() + + jsonArrayOf(null, jsonObjectOf("a" to true)) + .traceOne(jsonPath2) + .shouldBeRight() + .shouldBeNone() + + jsonArrayOf(jsonObjectOf("b" to true)) + .traceOne(jsonPath2) + .shouldBeRight() + .shouldBeNone() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonArrayOf(jsonObjectOf("a" to 2), jsonArrayOf(1, jsonObjectOf("a" to 3))) + .traceOne(jsonPath1) + .shouldBeLeft() + .results + .shouldContainExactly( + JsonNode(2, JsonPath[0]["a"]), + JsonNode(3, JsonPath[1][1]["a"]), + ) + + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ).traceOne(jsonPath2) + .shouldBeLeft() + .results + .shouldContainExactly( + JsonNode(jsonObjectOf("a" to 1), JsonPath[0]), + JsonNode(jsonObjectOf("a" to 2), JsonPath[3]), + ) + } + } + } + + context("The traceAll function") { + context("applied to a JsonObject") { + should("return a list containing the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonObjectOf("a" to 1, "b" to 2) + .traceAll(jsonPath1) shouldBe listOf(JsonPath["a"]) + + jsonObjectOf("a" to "string") + .traceAll(jsonPath1) shouldBe listOf(JsonPath["a"]) + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .traceAll(jsonPath2) shouldBe listOf(JsonPath["a"][1]["b"]) + } + + should("return an empty list if there is no result") { + val jsonPath1 = JsonPath.compile("$.a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$.a[1]['b']").shouldBeRight() + + jsonPath1.evaluateOne(jsonObjectOf("b" to 2)).shouldBeRight().shouldBeNone() + + jsonObjectOf("b" to jsonObjectOf("a" to 1)) + .traceAll(jsonPath1) shouldBe listOf() + + jsonObjectOf("b" to jsonArrayOf(null, jsonObjectOf("b" to true))) + .traceAll(jsonPath2) shouldBe listOf() + + jsonObjectOf("a" to jsonArrayOf(jsonObjectOf("b" to true))) + .traceAll(jsonPath2) shouldBe listOf() + + jsonObjectOf("a" to jsonArrayOf(null, jsonObjectOf("a" to true))) + .traceAll(jsonPath2) shouldBe listOf() + } + + should("return all results if there are multiple") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonObjectOf( + "a" to 1, + "b" to jsonObjectOf("a" to 2), + "c" to jsonArrayOf(1, jsonObjectOf("a" to 3)), + ).traceAll(jsonPath1) shouldContainExactlyInAnyOrder + listOf( + JsonPath["a"], + JsonPath["b"]["a"], + JsonPath["c"][1]["a"], + ) + + jsonObjectOf("a" to "string", "b" to jsonObjectOf("a" to null)) + .traceAll(jsonPath1) shouldContainExactlyInAnyOrder + listOf( + JsonPath["a"], + JsonPath["b"]["a"], + ) + + jsonObjectOf("a" to jsonObjectOf("a" to 1), "b" to jsonObjectOf("a" to 2)) + .traceAll(jsonPath2) shouldContainExactlyInAnyOrder + listOf( + JsonPath["a"], + JsonPath["b"], + ) + } + } + + context("applied to a JsonArray") { + should("return the single result if there is exactly one") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf(1, 2, 3) + .traceAll(jsonPath1) shouldBe listOf(JsonPath[0]) + + jsonArrayOf("string", null, true) + .traceAll(jsonPath1) shouldBe listOf(JsonPath[0]) + + jsonArrayOf(null, jsonObjectOf("b" to true)) + .traceAll(jsonPath2) shouldBe listOf(JsonPath[1]["b"]) + } + + should("return None if there is no result") { + val jsonPath1 = JsonPath.compile("$[0]").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[1]['b']").shouldBeRight() + + jsonArrayOf() + .traceAll(jsonPath1) shouldBe listOf() + + jsonArrayOf(null, jsonObjectOf("a" to true)) + .traceAll(jsonPath2) shouldBe listOf() + + jsonArrayOf(jsonObjectOf("b" to true)) + .traceAll(jsonPath2) shouldBe listOf() + } + + should("return an error if there are multiple results") { + val jsonPath1 = JsonPath.compile("$..a").shouldBeRight() + val jsonPath2 = JsonPath.compile("$[?@.a]").shouldBeRight() + + jsonArrayOf(jsonObjectOf("a" to 2), jsonArrayOf(1, jsonObjectOf("a" to 3))) + .traceAll(jsonPath1) shouldContainExactly listOf(JsonPath[0]["a"], JsonPath[1][1]["a"]) + + jsonArrayOf( + jsonObjectOf("a" to 1), + true, + jsonObjectOf("b" to 3), + jsonObjectOf("a" to 2), + ).traceAll(jsonPath2) shouldContainExactly + listOf( + JsonPath[0], + JsonPath[3], + ) + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathScannerTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathScannerTest.kt new file mode 100644 index 0000000..cd38bf7 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/compiler/JsonPathScannerTest.kt @@ -0,0 +1,104 @@ +package com.kobil.vertx.jsonpath.compiler + +import arrow.core.right +import com.kobil.vertx.jsonpath.testing.nameChar +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.property.Arb +import io.kotest.property.arbitrary.Codepoint +import io.kotest.property.arbitrary.az +import io.kotest.property.arbitrary.of +import io.kotest.property.arbitrary.string +import io.kotest.property.checkAll + +class JsonPathScannerTest : + ShouldSpec({ + context("When called on an empty string") { + should("only return an EOF token") { + "".scanTokens().toList() shouldBe listOf(Token.Eof(1U, 1U).right()) + } + } + + context("Dotted segments") { + should("be parsed to an Identifier token when they start with a lowercase latin letter") { + checkAll( + Arb.string(1, Codepoint.az()), + Arb.string(1..48, Codepoint.nameChar()), + ) { firstLetter, rest -> + val name = "$firstLetter$rest" + + "$.$name".scanTokens().toList() shouldBe + listOf( + Token.Dollar(1U, 1U).right(), + Token.Dot(1U, 2U).right(), + Token.Identifier(1U, 3U, name).right(), + Token.Eof(1U, name.length.toUInt() + 3U).right(), + ) + } + } + should("be parsed to an Identifier token when they start with a uppercase latin letter") { + checkAll( + Arb.string(1, Arb.of(('A'.code..'Z'.code).map(::Codepoint))), + Arb.string(1..48, Codepoint.nameChar()), + ) { firstLetter, rest -> + val name = "$firstLetter$rest" + + "$.$name".scanTokens().toList() shouldBe + listOf( + Token.Dollar(1U, 1U).right(), + Token.Dot(1U, 2U).right(), + Token.Identifier(1U, 3U, name).right(), + Token.Eof(1U, name.length.toUInt() + 3U).right(), + ) + } + } + + should("be parsed to an Identifier token when they start with an underscore") { + checkAll(Arb.string(1..48, Codepoint.nameChar())) { rest -> + val name = "_$rest" + + "$.$name".scanTokens().toList() shouldBe + listOf( + Token.Dollar(1U, 1U).right(), + Token.Dot(1U, 2U).right(), + Token.Identifier(1U, 3U, name).right(), + Token.Eof(1U, name.length.toUInt() + 3U).right(), + ) + } + } + + should("be parsed to an Identifier token when they start with a letter U+0080-U+D7FF") { + checkAll( + Arb.string(1, Arb.of((0x80..0xd7ff).map(::Codepoint))), + Arb.string(1..48, Codepoint.nameChar()), + ) { firstLetter, rest -> + val name = "$firstLetter$rest" + + "$.$name".scanTokens().toList() shouldBe + listOf( + Token.Dollar(1U, 1U).right(), + Token.Dot(1U, 2U).right(), + Token.Identifier(1U, 3U, name).right(), + Token.Eof(1U, name.length.toUInt() + 3U).right(), + ) + } + } + + should("be parsed to an Identifier token when they start with a letter U+E000-U+FFFF") { + checkAll( + Arb.string(1, Arb.of((0xe000..0xffff).map(::Codepoint))), + Arb.string(1..48, Codepoint.nameChar()), + ) { firstLetter, rest -> + val name = "$firstLetter$rest" + + "$.$name".scanTokens().toList() shouldBe + listOf( + Token.Dollar(1U, 1U).right(), + Token.Dot(1U, 2U).right(), + Token.Identifier(1U, 3U, name).right(), + Token.Eof(1U, name.length.toUInt() + 3U).right(), + ) + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/error/JsonPathErrorTest.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/error/JsonPathErrorTest.kt new file mode 100644 index 0000000..2779686 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/error/JsonPathErrorTest.kt @@ -0,0 +1,149 @@ +package com.kobil.vertx.jsonpath.error + +import com.kobil.vertx.jsonpath.compiler.Token +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.ShouldSpec +import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeSameInstanceAs +import io.kotest.property.checkAll +import java.io.IOException +import kotlin.coroutines.cancellation.CancellationException + +class JsonPathErrorTest : + ShouldSpec({ + context("The 'invoke' operator of JsonPathError") { + context("applied to a JsonPathException") { + should("return the error wrapped in the exception") { + val errors = + listOf( + JsonPathError.IllegalCharacter('a', 1U, 1U, "something"), + JsonPathError.UnterminatedString(1U, 1U, 1U, 1U), + JsonPathError.UnexpectedToken(Token.QuestionMark(1U, 1U), "something"), + JsonPathError.IllegalSelector(1U, 1U, "something"), + JsonPathError.UnknownFunction("something", 1U, 1U), + JsonPathError.MustBeSingularQuery(1U, 1U), + JsonPathError.InvalidEscapeSequence("abc", 1U, 1U, 1U, "something"), + ) + + for (err in errors) { + JsonPathError(JsonPathException(err)) shouldBeSameInstanceAs err + } + } + } + + context("applied to a CancellationException") { + should("rethrow the exception") { + shouldThrow { + JsonPathError(CancellationException("abc")) + } + } + } + + context("applied to an Error") { + should("rethrow the error") { + shouldThrow { + JsonPathError(OutOfMemoryError("abc")) + } + } + } + + context("applied to any other exception") { + should("return an UnexpectedError wrapping the exception") { + val exceptions = + listOf( + IllegalArgumentException("a"), + IllegalStateException("a"), + NullPointerException("a"), + IOException("a"), + ) + + for (ex in exceptions) { + shouldThrow { + JsonPathError(ex) + }.cause shouldBeSameInstanceAs ex + } + } + } + } + + context("The 'PrematureEof' error") { + should("produce the correct message from toString") { + checkAll { expected, line, col -> + JsonPathError.UnexpectedEof(expected, line, col).toString() shouldBe + "Error at [$line:$col]: Premature end of input, expected $expected" + } + } + } + + context("The 'IllegalCharacter' error") { + should("produce the correct message from toString") { + checkAll { ch, line, col, reason -> + JsonPathError.IllegalCharacter(ch, line, col, reason).toString() shouldBe + "Error at [$line:$col]: Illegal character '$ch' ($reason)" + } + } + } + + context("The 'UnterminatedString' error") { + should("produce the correct message from toString") { + checkAll { line, col, startLine, startCol -> + JsonPathError.UnterminatedString(line, col, startLine, startCol).toString() shouldBe + "Error at [$line:$col]: Unterminated string literal starting at [$startLine:$startCol]" + } + } + } + + context("The 'IntOutOfBounds' error") { + should("produce the correct message from toString") { + checkAll { string, line, col -> + JsonPathError.IntOutOfBounds(string, line, col).toString() shouldBe + "Error at [$line:$col]: Invalid integer value (Out of bounds)" + } + } + } + + context("The 'UnexpectedToken' error") { + should("produce the correct message from toString") { + checkAll { token, string -> + JsonPathError.UnexpectedToken(token, string).toString() shouldBe + "Error at [${token.line}:${token.column}]: Unexpected token '${token.name}' while parsing $string" + } + } + } + + context("The 'IllegalSelector' error") { + should("produce the correct message from toString") { + checkAll { line, col, string -> + JsonPathError.IllegalSelector(line, col, string).toString() shouldBe + "Error at [$line:$col]: Illegal selector ($string)" + } + } + } + + context("The 'UnknownFunction' error") { + should("produce the correct message from toString") { + checkAll { line, col, name -> + JsonPathError.UnknownFunction(name, line, col).toString() shouldBe + "Error at [$line:$col]: Unknown function extension '$name'" + } + } + } + + context("The 'MustBeSingularQuery' error") { + should("produce the correct message from toString") { + checkAll { line, col -> + JsonPathError.MustBeSingularQuery(line, col).toString() shouldBe + "Error at [$line:$col]: A singular query is expected" + } + } + } + + context("The 'InvalidEscapeSequence' error") { + should("produce the correct message from toString") { + checkAll { string, line, col, pos, reason -> + JsonPathError.InvalidEscapeSequence(string, line, col, pos, reason).toString() shouldBe + "Error at [$line:$col]: Invalid escape sequence at position $pos in string literal '$string' ($reason)" + } + } + } + }) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/testing/Gen.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/testing/Gen.kt new file mode 100644 index 0000000..e006616 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/testing/Gen.kt @@ -0,0 +1,69 @@ +package com.kobil.vertx.jsonpath.testing + +import com.kobil.vertx.jsonpath.ComparableExpression +import com.kobil.vertx.jsonpath.JsonPath +import com.kobil.vertx.jsonpath.QueryExpression +import com.kobil.vertx.jsonpath.get +import io.kotest.property.Arb +import io.kotest.property.arbitrary.Codepoint +import io.kotest.property.arbitrary.arbitrary +import io.kotest.property.arbitrary.boolean +import io.kotest.property.arbitrary.choice +import io.kotest.property.arbitrary.constant +import io.kotest.property.arbitrary.double +import io.kotest.property.arbitrary.int +import io.kotest.property.arbitrary.map +import io.kotest.property.arbitrary.of +import io.kotest.property.arbitrary.string +import io.kotest.property.resolution.default + +fun Codepoint.Companion.nameChar(): Arb = + Arb.of( + ('0'.code..'9'.code).map(::Codepoint) + + ('A'.code..'Z'.code).map(::Codepoint) + + ('a'.code..'z'.code).map(::Codepoint) + + Codepoint('_'.code) + + (0x80..0xd7ff).map(::Codepoint) + + (0xe000..0xffff).map(::Codepoint), + ) + +fun Arb.Companion.normalizedJsonPath(): Arb = + arbitrary { + val length = Arb.int(0..10).bind() + var path = JsonPath.ROOT + + for (i in 1..length) { + path = + if (Arb.boolean().bind()) { + path[Arb.default().bind()] + } else { + path[Arb.int(0..Int.MAX_VALUE).bind()] + } + } + + path + } + +fun Arb.Companion.comparable(): Arb = + choice( + literal(), + queryExpression(), + queryExpression().map { it.count() }, + queryExpression().map { it.length() }, + queryExpression().map { it.value() }, + ) + +fun Arb.Companion.queryExpression(): Arb> = + choice( + normalizedJsonPath().map { (segments) -> QueryExpression.absolute(segments) }, + normalizedJsonPath().map { (segments) -> QueryExpression.relative(segments) }, + ) + +fun Arb.Companion.literal(): Arb = + choice(int(), double(), string(), boolean(), constant(null)).map(ComparableExpression::Literal) + +fun Arb.Companion.matchOperand(): Arb = + choice( + string().map(ComparableExpression::Literal), + queryExpression(), + ) diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/testing/Util.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/testing/Util.kt new file mode 100644 index 0000000..3247da0 --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/testing/Util.kt @@ -0,0 +1,6 @@ +package com.kobil.vertx.jsonpath.testing + +import io.kotest.core.spec.style.scopes.ShouldSpecContainerScope + +typealias SpecContext = suspend Container.(String, suspend Container.() -> Unit) -> Unit +typealias ShouldSpecContext = SpecContext diff --git a/src/test/kotlin/com/kobil/vertx/jsonpath/testing/VertxExtension.kt b/src/test/kotlin/com/kobil/vertx/jsonpath/testing/VertxExtension.kt new file mode 100644 index 0000000..d25f29b --- /dev/null +++ b/src/test/kotlin/com/kobil/vertx/jsonpath/testing/VertxExtension.kt @@ -0,0 +1,87 @@ +package com.kobil.vertx.jsonpath.testing + +import io.kotest.assertions.fail +import io.kotest.core.extensions.SpecExtension +import io.kotest.core.extensions.TestCaseExtension +import io.kotest.core.spec.Spec +import io.kotest.core.spec.style.scopes.ContainerScope +import io.kotest.core.test.TestCase +import io.kotest.core.test.TestResult +import io.kotest.core.test.TestScope +import io.vertx.core.Vertx +import io.vertx.kotlin.coroutines.coAwait +import io.vertx.kotlin.coroutines.dispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext + +class VertxExtension( + private val lifecycle: Lifecycle = Lifecycle.Spec, +) : TestCaseExtension, + SpecExtension { + companion object { + val TestScope.vertx: Vertx + get() = + coroutineContext[VertxKey]?.vertx + ?: fail("VertxExtension not installed for this test") + val ContainerScope.vertx: Vertx + get() = + coroutineContext[VertxKey]?.vertx + ?: fail("VertxExtension not installed for this test") + } + + override suspend fun intercept( + testCase: TestCase, + execute: suspend (TestCase) -> TestResult, + ): TestResult { + if (lifecycle == Lifecycle.Test) { + val vertx = Vertx.vertx() + + val job = + CoroutineScope(vertx.dispatcher() + VertxElement(vertx)).async { + execute(testCase) + } + + val result = job.await() + + vertx.close().coAwait() + + return result + } else { + return execute(testCase) + } + } + + override suspend fun intercept( + spec: Spec, + execute: suspend (Spec) -> Unit, + ) { + if (lifecycle == Lifecycle.Spec) { + val vertx = Vertx.vertx() + + val job = + CoroutineScope(vertx.dispatcher() + VertxElement(vertx)).launch { + execute(spec) + } + + job.join() + + vertx.close().coAwait() + } else { + execute(spec) + } + } + + enum class Lifecycle { + Spec, + Test, + } + + private data object VertxKey : CoroutineContext.Key + + private data class VertxElement( + val vertx: Vertx, + ) : AbstractCoroutineContextElement(VertxKey) +} diff --git a/src/test/resources/compliance-test-suite b/src/test/resources/compliance-test-suite new file mode 160000 index 0000000..9277705 --- /dev/null +++ b/src/test/resources/compliance-test-suite @@ -0,0 +1 @@ +Subproject commit 9277705cda4489c3d0d984831e7656e48145399b