Last active
December 29, 2023 17:09
-
-
Save Checksum/72d927471c76c76c46418b3ee88e0a7c to your computer and use it in GitHub Desktop.
Assertion library for jq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A simple assertion library for jq (https://github.com/stedolan/jq) | |
# Author: Srinath Sankar | |
def assert(level; expr; msg): | |
if expr then | |
. | |
else | |
. |= . + [{ level: level, message: msg }] | |
end; | |
def assert(expr; msg): | |
assert("error"; expr; msg); | |
def validate: | |
. as $errors | |
| ($errors | map("\(.level | ascii_upcase): \(.message)") | join("\n")) as $output | |
| if $errors | map(select(.level == "error")) | length > 0 then | |
error("\n" + $output) | |
elif $errors | length > 0 then | |
$output | |
else | |
true | |
end; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage | |
# echo '{"authors": [ { "name": "Srinath", "id": "Checksum" } ]}' | jq -L assert.jq -M 'include "assert"; check_authors' | |
def check_authors: | |
# Declaration | |
. as $response | |
# Empty array to collect responses | |
| [] | |
# Assertions | |
| assert($response | type == "object"; "Response is not an object") | |
| assert($response.authors | type == "array"; "Authors not an array") | |
| assert("warn"; $response.authors.length > 0; "No authors in response") | |
# Output | |
| validate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For others struggling, both files must be impored, iether as single module or individual.
I opted for a collection of specific "assertions" that import the "assert" utility.
and then call by specifying multiple library paths if needed, multiple includes
jq -L test_data/utilities/ -L test_data/boa_invalid -M 'include "assert"; include "assertion"; check_decision' /tmp/output