diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..e9381c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# Gradle +.gradle/ +build/ +*.log + +# IDEA +.idea/ +*.iml +*.ipr +*.iws +out/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..bd7aa59 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,8 @@ +script: ./gradlew clean build + +jdk: + - oraclejdk8 + - oraclejdk7 + +script: +- ./gradlew clean build diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. \ No newline at end of file diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..cfb1ba4 --- /dev/null +++ b/NOTICE @@ -0,0 +1,17 @@ +========================================================================= +== NOTICE file corresponding to the section 4 d of == +== the Apache License, Version 2.0, == +== in this case for the Spock distribution. == +========================================================================= + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +It includes the following other software: + +gentyref (http://code.google.com/p/gentyref/) + +For licenses see the LICENSE file. + +If any software distributed with Spock does not have an Apache 2 License, its license is explicitly listed in the +LICENSE file. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100755 index 0000000..0d2dfed --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +[![Build Status](https://travis-ci.org/marcingrzejszczak/jsonpathassert.svg?branch=master)](https://travis-ci.org/marcingrzejszczak/jsonpathassert) +[![Join the chat at https://gitter.im/marcingrzejszczak/jsonpathassert](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/marcingrzejszczak/jsonpathassert?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +JSON Path assert +=============== + +TODO + +Changelog +-------------------- +[Changes are available here](CHANGELOG.md) + +Contact +-------------------- +[Gitter chat](https://gitter.im/marcingrzejszczak/jsonpathassert) diff --git a/build.gradle b/build.gradle new file mode 100755 index 0000000..6e2398d --- /dev/null +++ b/build.gradle @@ -0,0 +1,67 @@ +apply plugin: 'groovy' +apply plugin: 'maven' +apply plugin: 'maven-publish' + +buildscript { + repositories { + jcenter() + } + dependencies { + if (!version.contains('SNAPSHOT')) { + classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:+' + classpath "io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.5.3" + } + } +} + + +group = 'com.blogspot.toomuchcoding' +version = '0.0.1-SNAPSHOT' +description = "JSON Path assertion library" + +sourceCompatibility = 1.7 + +repositories { + jcenter() +} + +dependencies { + compile "com.jayway.jsonpath:json-path:2.0.0" + compile "org.codehaus.groovy:groovy-all:2.4.5" + + testCompile "org.spockframework:spock-core:1.0-groovy-2.4" + testCompile 'cglib:cglib-nodep:3.1' + testCompile 'org.objenesis:objenesis:2.1' +} + +test { + maxParallelForks = Runtime.runtime.availableProcessors() / 2 +} + +publishing { + publications { + code(MavenPublication) { + from components.java + pom.withXml { + //#89 - workaround to not to have only runtime dependencies in generated pom.xml + //Known limitation in maven-publish - - http://forums.gradle.org/gradle/topics/maven_publish_plugin_generated_pom_making_dependency_scope_runtime#reply_14120711 + asNode().dependencies.'*'.findAll() { + it.scope.text() == 'runtime' && project.configurations.compile.allDependencies.find { dep -> + dep.name == it.artifactId.text() + } + }.each() { + it.scope*.value = 'compile' + } + } + } + } +} + +task wrapper(type: Wrapper) { + gradleVersion = '2.11' +} + +if (!version.contains('SNAPSHOT')) { + apply from: "$rootDir/gradle/release.gradle" +} + diff --git a/closeRepo.sh b/closeRepo.sh new file mode 100644 index 0000000..05d44e4 --- /dev/null +++ b/closeRepo.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +./gradlew closeRepository promoteRepository diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..dfdfa4e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.daemon=true +sonatypeUsername= +sonatypePassword= +#signing.keyId= +#signing.password= +#signing.secretKeyRingFile= \ No newline at end of file diff --git a/gradle/release.gradle b/gradle/release.gradle new file mode 100644 index 0000000..3dccb09 --- /dev/null +++ b/gradle/release.gradle @@ -0,0 +1,87 @@ +apply plugin: 'maven' +apply plugin: 'signing' +apply plugin: 'com.jfrog.bintray' +apply plugin: 'io.codearte.nexus-staging' + +String projectDescription = '''Spock extension that allows you to inject Collaborators into Subjects. Bases on Mockito's @InjectMocks functionality''' + +task javadocJar(type: Jar) { + classifier = 'javadoc' + from javadoc +} + +task sourcesJar(type: Jar) { + classifier = 'sources' + from sourceSets.main.allSource +} + +artifacts { + archives javadocJar, sourcesJar +} + +signing { + sign configurations.archives +} + +uploadArchives { + repositories { + mavenDeployer { + beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + + repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { + authentication(userName: sonatypeUsername, password: sonatypePassword) + } + + snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { + authentication(userName: sonatypeUsername, password: sonatypePassword) + } + + pom.project { + name "$project.name" + packaging 'jar' + description projectDescription + url 'https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension' + + scm { + connection 'git@github.com:marcingrzejszczak/spock-subjects-collaborators-extension.git' + developerConnection 'git@github.com:marcingrzejszczak/spock-subjects-collaborators-extension.git' + url 'https://github.com/marcingrzejszczak/spock-subjects-collaborators-extension' + } + + licenses { + license { + name 'The Apache License, Version 2.0' + url 'http://www.apache.org/licenses/LICENSE-2.0.txt' + } + } + + developers { + developer { + id 'marcingrzejszczak' + name 'Marcin Grzejszczak' + email 'marcin ATT grzejszczak DOTT pl' + } + } + } + } + } +} + +uploadArchives.dependsOn(check) +bintrayUpload.dependsOn(check) + +task release(dependsOn:['uploadArchives', 'bintrayUpload']) {} + +bintray { + user = project.properties['bintrayUser'] + key = project.properties['bintrayKey'] + publications = ['code'] + pkg { + repo = 'com-blogspot-toomuchcoding' + name = 'spock-subjects-collaborators-extension' + desc = projectDescription + licenses = ['Apache-2.0'] + labels = ['spock'] + } +} + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b5166da 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 100755 index 0000000..5dbf0e5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Feb 14 13:45:58 CET 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..91a7e26 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +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" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@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 + +@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= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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 init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +: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 %CMD_LINE_ARGS% + +: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 b/settings.gradle new file mode 100755 index 0000000..6dd4878 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "jsonpathassert" diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ArrayAssertion.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ArrayAssertion.java new file mode 100644 index 0000000..09f843a --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ArrayAssertion.java @@ -0,0 +1,20 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; + +class ArrayAssertion extends JsonPathAsserter { + protected ArrayAssertion(DocumentContext parsedJson, LinkedList jsonPathBuffer, Object arrayName) { + super(parsedJson, jsonPathBuffer, arrayName); + } + + protected ArrayAssertion(DocumentContext parsedJson, LinkedList jsonPathBuffer) { + super(parsedJson, jsonPathBuffer, null); + } + + @Override + public boolean isIteratingOverArray() { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ArrayValueAssertion.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ArrayValueAssertion.java new file mode 100644 index 0000000..b0f97f7 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ArrayValueAssertion.java @@ -0,0 +1,58 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; + +class ArrayValueAssertion extends FieldAssertion { + protected ArrayValueAssertion(DocumentContext parsedJson, LinkedList jsonPathBuffer, Object arrayName) { + super(parsedJson, jsonPathBuffer, arrayName); + } + + protected ArrayValueAssertion(DocumentContext parsedJson, LinkedList jsonPathBuffer) { + super(parsedJson, jsonPathBuffer, null); + } + + @Override + public JsonPathVerifiable contains(Object value) { + return new ArrayValueAssertion(parsedJson, jsonPathBuffer, value).isEqualTo(value); + } + + @Override + public JsonPathVerifiable isEqualTo(String value) { + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.offer("[?(@ == " + wrapValueWithSingleQuotes(value) + ")]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable isEqualTo(Number value) { + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.offer("[?(@ == " + String.valueOf(value) + ")]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable matches(String value) { + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.offer("[?(@ =~ /" + value + "/)]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable isEqualTo(Boolean value) { + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.offer("[?(@ == " + String.valueOf(value) + ")]"); + return readyToCheck; + } + + @Override + public boolean isAssertingAValueInArray() { + return true; + } + +} \ No newline at end of file diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/FieldAssertion.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/FieldAssertion.java new file mode 100644 index 0000000..ccab900 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/FieldAssertion.java @@ -0,0 +1,11 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; + +class FieldAssertion extends JsonPathAsserter { + protected FieldAssertion(DocumentContext parsedJson, LinkedList jsonPathBuffer, Object fieldName) { + super(parsedJson, jsonPathBuffer, fieldName); + } +} \ No newline at end of file diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/IteratingOverArray.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/IteratingOverArray.java new file mode 100644 index 0000000..559d571 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/IteratingOverArray.java @@ -0,0 +1,19 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +public interface IteratingOverArray { + /** + * True if is in progress of iterating over nameless array + */ + boolean isIteratingOverNamelessArray(); + + /** + * True if is in progress of iterating over an array + */ + boolean isIteratingOverArray(); + + /** + * True if current element is a particular value on which concrete assertion will take place + */ + boolean isAssertingAValueInArray(); + +} \ No newline at end of file diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAsserter.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAsserter.java new file mode 100644 index 0000000..744b321 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAsserter.java @@ -0,0 +1,222 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; + +import net.minidev.json.JSONArray; + +class JsonPathAsserter implements JsonPathVerifiable { + + protected final DocumentContext parsedJson; + protected final LinkedList jsonPathBuffer; + protected final Object fieldName; + + protected JsonPathAsserter(DocumentContext parsedJson, LinkedList jsonPathBuffer, Object fieldName) { + this.parsedJson = parsedJson; + this.jsonPathBuffer = new LinkedList(jsonPathBuffer); + this.fieldName = fieldName; + } + + @Override + public JsonPathVerifiable contains(final Object value) { + FieldAssertion asserter = new FieldAssertion(parsedJson, jsonPathBuffer, value); + // this is fake part of jsonpath since in the next section we will remove this entry + asserter.jsonPathBuffer.offer("[*]"); + return asserter; + } + + @Override + public FieldAssertion field(final Object value) { + FieldAssertion asserter = new FieldAssertion(parsedJson, jsonPathBuffer, value); + asserter.jsonPathBuffer.offer("." + String.valueOf(value)); + return asserter; + } + + @Override + public ArrayAssertion array(final Object value) { + if (value == null) { + return array(); + } + ArrayAssertion asserter = new ArrayAssertion(parsedJson, jsonPathBuffer, value); + asserter.jsonPathBuffer.offer("." + String.valueOf(value) + "[*]"); + return asserter; + } + + @Override + public ArrayValueAssertion arrayField(final Object value) { + ArrayValueAssertion asserter = new ArrayValueAssertion(parsedJson, jsonPathBuffer, value); + asserter.jsonPathBuffer.offer("." + String.valueOf(value)); + return asserter; + } + + @Override + public ArrayValueAssertion arrayField() { + return new ArrayValueAssertion(parsedJson, jsonPathBuffer); + } + + @Override + public ArrayAssertion array() { + ArrayAssertion asserter = new ArrayAssertion(parsedJson, jsonPathBuffer); + asserter.jsonPathBuffer.offer("[*]"); + return asserter; + } + + @Override + public ArrayAssertion iterationPassingArray() { + return new ArrayAssertion(parsedJson, jsonPathBuffer); + } + + @Override + public JsonPathVerifiable isEqualTo(String value) { + if (value == null) { + return isNull(); + } + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.removeLast(); + readyToCheck.jsonPathBuffer.offer("[?(@." + String.valueOf(fieldName)+ " == " + wrapValueWithSingleQuotes(value) + ")]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable isEqualTo(Object value) { + if (value == null) { + return isNull(); + } + if (value instanceof Number) { + return isEqualTo((Number) value); + } else if (value instanceof Boolean) { + return isEqualTo((Boolean) value); + } + return isEqualTo(value.toString()); + } + + @Override + public JsonPathVerifiable isEqualTo(Number value) { + if (value == null) { + return isNull(); + } + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.removeLast(); + readyToCheck.jsonPathBuffer.offer("[?(@." + String.valueOf(fieldName)+ " == " + value + ")]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable isNull() { + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.removeLast(); + readyToCheck.jsonPathBuffer.offer("[?(@." + String.valueOf(fieldName) + " == null)]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable matches(String value) { + if (value == null) { + return isNull(); + } + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.removeLast(); + readyToCheck.jsonPathBuffer.offer("[?(@." + String.valueOf(fieldName) + + " =~ /" + stringWithEscapedSingleQuotes(value) + "/)]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable isEqualTo(Boolean value) { + if (value == null) { + return isNull(); + } + ReadyToCheckAsserter readyToCheck = new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + readyToCheck.jsonPathBuffer.removeLast(); + readyToCheck.jsonPathBuffer.offer("[?(@." + String.valueOf(fieldName)+ " == " + String.valueOf(value) + ")]"); + return readyToCheck; + } + + @Override + public JsonPathVerifiable value() { + return new ReadyToCheckAsserter(parsedJson, + jsonPathBuffer, fieldName); + } + + @Override + public void check() { + assert !parsedJson.read(createJsonPathString(), JSONArray.class).isEmpty(); + } + + private String createJsonPathString() { + LinkedList queue = new LinkedList(jsonPathBuffer); + StringBuilder stringBuffer = new StringBuilder(); + while (!queue.isEmpty()) { + stringBuffer.append(queue.remove()); + } + return stringBuffer.toString(); + } + + @Override + public String jsonPath() { + return createJsonPathString(); + } + + public boolean equals(Object o) { + if (this == o) + return true; + if (!getClass().equals(o.getClass())) + return false; + JsonPathAsserter jsonPathAsserter = (JsonPathAsserter) o; + if (!fieldName.equals(jsonPathAsserter.fieldName)) + return false; + return jsonPathBuffer.equals(jsonPathAsserter.jsonPathBuffer); + + } + + public int hashCode() { + int result; + result = (parsedJson != null ? parsedJson.hashCode() : 0); + result = 31 * result + (jsonPathBuffer != null ? jsonPathBuffer.hashCode() : 0); + result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "\\nAsserter{\n " + "jsonPathBuffer=" + String.valueOf(jsonPathBuffer) + + "\n}"; + } + + @Override + public boolean isReadyToCheck() { + return false; + } + + @Override + public boolean isIteratingOverNamelessArray() { + return false; + } + + @Override + public boolean isIteratingOverArray() { + return false; + } + + @Override + public boolean isAssertingAValueInArray() { + return false; + } + + protected static String stringWithEscapedSingleQuotes(Object object) { + String stringValue = object.toString(); + return stringValue.replaceAll("'", "\\\\'"); + } + + protected String wrapValueWithSingleQuotes(Object value) { + return value instanceof String ? + "'" + stringWithEscapedSingleQuotes(value) + "'" : + value.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAssertion.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAssertion.java new file mode 100644 index 0000000..31d4799 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAssertion.java @@ -0,0 +1,40 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; +import com.jayway.jsonpath.JsonPath; + +import net.minidev.json.JSONArray; + +/** + * Entry point for assertions. Use the static factory method and you're ready to go! + * + * @see JsonPathVerifiable + * + * @author Marcin Grzejszczak + */ +public class JsonPathAssertion { + private final DocumentContext parsedJson; + private final LinkedList jsonPathBuffer = new LinkedList(); + + private JsonPathAssertion(DocumentContext parsedJson) { + this.parsedJson = parsedJson; + } + + public static JsonPathVerifiable assertThat(String body) { + DocumentContext parsedJson = JsonPath.parse(body); + return new JsonPathAssertion(parsedJson).root(); + } + + private JsonPathVerifiable root() { + NamelessArrayHavingFieldAssertion asserter = new NamelessArrayHavingFieldAssertion(parsedJson, jsonPathBuffer, ""); + asserter.jsonPathBuffer.offer("$"); + return asserter; + } + + public void matchesJsonPath(String jsonPath) { + assert !parsedJson.read(jsonPath, JSONArray.class).isEmpty(); + } + +} diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathVerifiable.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathVerifiable.java new file mode 100644 index 0000000..87dfc75 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/JsonPathVerifiable.java @@ -0,0 +1,87 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +/** + * Contract to match a parsed JSON via JSON Path + * + * @author Marcin Grzejszczak + */ +public interface JsonPathVerifiable extends ReadyToCheck, IteratingOverArray { + + /** + * Assertion of a field inside an array. Use it only for assertion and not traversing + */ + JsonPathVerifiable contains(Object value); + + /** + * Field assertion. Adds a JSON Path entry for the given field. + */ + JsonPathVerifiable field(Object value); + + /** + * When you want to assert values in a array with a given name + */ + JsonPathVerifiable array(Object value); + + /** + * When you want to compare values of a particular field in a named array + */ + JsonPathVerifiable arrayField(Object value); + + /** + * When you want to compare values of a field in a nameless array + */ + JsonPathVerifiable arrayField(); + + /** + * When in JSON path you iterate over a nameless array + */ + JsonPathVerifiable array(); + + /** + * When in JSON path you iterate over arrays and need to skip iteration + * + * TODO: Think of removing this + */ + JsonPathVerifiable iterationPassingArray(); + + //TODO: All below should return ReadyToCheck + /** + * Equality comparison with String + */ + JsonPathVerifiable isEqualTo(String value); + + /** + * Equality comparison with any object + */ + JsonPathVerifiable isEqualTo(Object value); + + /** + * Equality comparison with a Number + */ + JsonPathVerifiable isEqualTo(Number value); + + /** + * Equality comparison to null + */ + JsonPathVerifiable isNull(); + + /** + * Regex matching + */ + JsonPathVerifiable matches(String value); + + /** + * Equality comparison with a Boolean + */ + JsonPathVerifiable isEqualTo(Boolean value); + + /** + * Call this to to perform assertion against an array of primitives + */ + JsonPathVerifiable value(); + + /** + * Returns current JSON Path expression + */ + String jsonPath(); +} diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/NamelessArrayHavingFieldAssertion.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/NamelessArrayHavingFieldAssertion.java new file mode 100644 index 0000000..6f1f5d2 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/NamelessArrayHavingFieldAssertion.java @@ -0,0 +1,18 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; + +class NamelessArrayHavingFieldAssertion extends FieldAssertion { + protected NamelessArrayHavingFieldAssertion(DocumentContext parsedJson, + LinkedList jsonPathBuffer, Object fieldName) { + super(parsedJson, jsonPathBuffer, fieldName); + } + + @Override + public boolean isIteratingOverNamelessArray() { + return true; + } + +} \ No newline at end of file diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ReadyToCheck.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ReadyToCheck.java new file mode 100644 index 0000000..c4b2391 --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ReadyToCheck.java @@ -0,0 +1,14 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +public interface ReadyToCheck { + /** + * True if the whole JSON Path got built + */ + boolean isReadyToCheck(); + + /** + * Perform the assertion of the object against JSON Path + */ + void check(); +} + diff --git a/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ReadyToCheckAsserter.java b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ReadyToCheckAsserter.java new file mode 100644 index 0000000..c97582f --- /dev/null +++ b/src/main/java/com/blogspot/toomuchcoding/jsonpathassert/ReadyToCheckAsserter.java @@ -0,0 +1,18 @@ +package com.blogspot.toomuchcoding.jsonpathassert; + +import java.util.LinkedList; + +import com.jayway.jsonpath.DocumentContext; + +class ReadyToCheckAsserter extends JsonPathAsserter { + + public ReadyToCheckAsserter(DocumentContext parsedJson, LinkedList jsonPathBuffer, Object fieldName) { + super(parsedJson, jsonPathBuffer, fieldName); + } + + @Override + public boolean isReadyToCheck() { + return true; + } + +} \ No newline at end of file diff --git a/src/test/groovy/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAssertionSpec.groovy b/src/test/groovy/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAssertionSpec.groovy new file mode 100644 index 0000000..63bc908 --- /dev/null +++ b/src/test/groovy/com/blogspot/toomuchcoding/jsonpathassert/JsonPathAssertionSpec.groovy @@ -0,0 +1,308 @@ +package com.blogspot.toomuchcoding.jsonpathassert + +import spock.lang.Shared +import spock.lang.Specification +import spock.lang.Unroll + +import java.util.regex.Pattern + +import static com.blogspot.toomuchcoding.jsonpathassert.JsonPathAssertion.assertThat +import static groovy.json.JsonOutput.toJson + +/** + * @author Marcin Grzejszczak + */ +public class JsonPathAssertionSpec extends Specification { + + def 'should work'() { + expect: + assertThat('body').field('foo').isEqualTo('bar') + assertThat('body').field('foo').array('nested').contains('withlist').isEqualTo('bar') + } + + @Shared String json1 = ''' + { + "some" : { + "nested" : { + "json" : "with \\"val'ue", + "anothervalue": 4, + "withlist" : [ + { "name" :"name1"} , {"name": "name2"} + ] + } + } + } + ''' + + @Unroll + def 'should convert a json with a map as root to a map of path to value '() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json1).field("some").field("nested").field("anothervalue").isEqualTo(4) || '''$.some.nested[?(@.anothervalue == 4)]''' + assertThat(json1).field("some").field("nested").array("withlist").contains("name").isEqualTo("name1") || '''$.some.nested.withlist[*][?(@.name == 'name1')]''' + assertThat(json1).field("some").field("nested").array("withlist").contains("name").isEqualTo("name2") || '''$.some.nested.withlist[*][?(@.name == 'name2')]''' + assertThat(json1).field("some").field("nested").field("json").isEqualTo("with \"val'ue") || '''$.some.nested[?(@.json == 'with "val\\'ue')]''' + } + + @Shared String json2 = '''{ + "property1": "a", + "property2": "b" + }''' + + @Unroll + def "should generate assertions for simple response body"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json2).field("property1").isEqualTo("a") || '''$[?(@.property1 == 'a')]''' + assertThat(json2).field("property2").isEqualTo("b") || '''$[?(@.property2 == 'b')]''' + } + + @Shared String json3 = '''{ + "property1": "true", + "property2": null, + "property3": false + }''' + + @Unroll + def "should generate assertions for null and boolean values"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json3).field("property1").isEqualTo("true") || '''$[?(@.property1 == 'true')]''' + assertThat(json3).field("property2").isNull() || '''$[?(@.property2 == null)]''' + assertThat(json3).field("property3").isEqualTo(false) || '''$[?(@.property3 == false)]''' + } + + @Shared Map json4 = [ + property1: 'a', + property2: [ + [a: 'sth'], + [b: 'sthElse'] + ] + ] + + @Unroll + def "should generate assertions for simple response body constructed from map with a list"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(toJson(json4)).field("property1").isEqualTo("a") || '''$[?(@.property1 == 'a')]''' + assertThat(toJson(json4)).array("property2").contains("a").isEqualTo("sth") || '''$.property2[*][?(@.a == 'sth')]''' + assertThat(toJson(json4)).array("property2").contains("b").isEqualTo("sthElse") || '''$.property2[*][?(@.b == 'sthElse')]''' + } + + @Shared Map json5 = [ + property: [ + 14: 0.0, + 7 : 0.0 + ] + ] + + @Unroll + def "should generate assertions for a response body containing map with integers as keys"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(toJson(json5)).field("property").field(7).isEqualTo(0.0) || '''$.property[?(@.7 == 0.0)]''' + assertThat(toJson(json5)).field("property").field(14).isEqualTo(0.0) || '''$.property[?(@.14 == 0.0)]''' + } + + @Shared String json6 = '''[ + { + "property1": "a" + }, + { + "property2": "b" + }]''' + + @Unroll + def "should generate assertions for array in response body"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json6).array().contains("property1").isEqualTo("a") || '''$[*][?(@.property1 == 'a')]''' + assertThat(json6).array().contains("property2").isEqualTo("b") || '''$[*][?(@.property2 == 'b')]''' + } + + @Shared String json7 = '''{ + "property1": [ + { "property2": "test1"}, + { "property3": "test2"} + ] + }''' + + @Unroll + def "should generate assertions for array inside response body element"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json7).array("property1").contains("property2").isEqualTo("test1") || '''$.property1[*][?(@.property2 == 'test1')]''' + assertThat(json7).array("property1").contains("property3").isEqualTo("test2") || '''$.property1[*][?(@.property3 == 'test2')]''' + } + + @Shared String json8 = """{ + "property1": "a", + "property2": {"property3": "b"} + }""" + + def "should generate assertions for nested objects in response body"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json8).field("property2").field("property3").isEqualTo("b") || '''$.property2[?(@.property3 == 'b')]''' + assertThat(json8).field("property1").isEqualTo("a") || '''$[?(@.property1 == 'a')]''' + } + + @Shared Map json9 = [ + property1: "a", + property2: Pattern.compile('[0-9]{3}') + ] + + @Unroll + def "should generate regex assertions for map objects in response body"() { + expect: + verifiable.jsonPath() == expectedJsonPath + where: + verifiable || expectedJsonPath + assertThat(toJson(json9)).field("property2").matches("[0-9]{3}") || '''$[?(@.property2 =~ /[0-9]{3}/)]''' + assertThat(toJson(json9)).field("property1").isEqualTo("a") || '''$[?(@.property1 == 'a')]''' + } + + def "should generate escaped regex assertions for string objects in response body"() { + given: + Map json = [ + property2: Pattern.compile('\\d+') + ] + expect: + def verifiable = assertThat(toJson(json)).field("property2").matches("\\d+") + verifiable.jsonPath() == '''$[?(@.property2 =~ /\\d+/)]''' + } + + @Shared Map json10 = [ + errors: [ + [property: "bank_account_number", + message: "incorrect_format"] + ] + ] + + @Unroll + def "should work with more complex stuff and jsonpaths"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(toJson(json10)).array("errors").contains("property").isEqualTo("bank_account_number") || '''$.errors[*][?(@.property == 'bank_account_number')]''' + assertThat(toJson(json10)).array("errors").contains("message").isEqualTo("incorrect_format") || '''$.errors[*][?(@.message == 'incorrect_format')]''' + } + + @Shared String json11 = ''' + [{ + "place": + { + "bounding_box": + { + "coordinates": + [[ + [-77.119759,38.995548], + [-76.909393,38.791645] + ]] + } + } + }] + ''' + + @Unroll + def "should manage to parse a double array"() { + expect: + verifiable.jsonPath() == expectedJsonPath + verifiable.check() + where: + verifiable || expectedJsonPath + assertThat(json11).array().field("place").field("bounding_box").array("coordinates").array().arrayField().contains(38.995548).value() || '''$[*].place.bounding_box.coordinates[*][*][?(@ == 38.995548)]''' + assertThat(json11).array().field("place").field("bounding_box").array("coordinates").array().arrayField().contains(-77.119759).value() || '''$[*].place.bounding_box.coordinates[*][*][?(@ == -77.119759)]''' + assertThat(json11).array().field("place").field("bounding_box").array("coordinates").array().arrayField().contains(-76.909393).value() || '''$[*].place.bounding_box.coordinates[*][*][?(@ == -76.909393)]''' + assertThat(json11).array().field("place").field("bounding_box").array("coordinates").array().arrayField().contains(38.791645).value() || '''$[*].place.bounding_box.coordinates[*][*][?(@ == 38.791645)]''' + + } + + @Unroll + def 'should convert a json with list as root to a map of path to value'() { + expect: + assertThat(json).array().field("some").field("nested").field("json").isEqualTo("with value").jsonPath() == '''$[*].some.nested[?(@.json == 'with value')]''' + assertThat(json).array().field("some").field("nested").field("anothervalue").isEqualTo(4).jsonPath() == '''$[*].some.nested[?(@.anothervalue == 4)]''' + assertThat(json).array().field("some").field("nested").array("withlist").contains("name").isEqualTo("name1").jsonPath() == '''$[*].some.nested.withlist[*][?(@.name == 'name1')]''' + assertThat(json).array().field("some").field("nested").array("withlist").contains("name").isEqualTo("name2").jsonPath() == '''$[*].some.nested.withlist[*][?(@.name == 'name2')]''' + assertThat(json).array().field("some").field("nested").array("withlist").field("anothernested").field("name").isEqualTo("name3").jsonPath() == '''$[*].some.nested.withlist[*].anothernested[?(@.name == 'name3')]''' + where: + json << [ + ''' + [ { + "some" : { + "nested" : { + "json" : "with value", + "anothervalue": 4, + "withlist" : [ + { "name" :"name1"} , {"name": "name2"}, {"anothernested": { "name": "name3"} } + ] + } + } + }, + { + "someother" : { + "nested" : { + "json" : "with value", + "anothervalue": 4, + "withlist" : [ + { "name" :"name1"} , {"name": "name2"} + ] + } + } + } + ] + ''', + ''' + [{ + "someother" : { + "nested" : { + "json" : "with value", + "anothervalue": 4, + "withlist" : [ + { "name" :"name1"} , {"name": "name2"} + ] + } + } + }, + { + "some" : { + "nested" : { + "json" : "with value", + "anothervalue": 4, + "withlist" : [ + {"name": "name2"}, {"anothernested": { "name": "name3"} }, { "name" :"name1"} + ] + } + } + } + ]'''] + } + +} \ No newline at end of file