Skip to content

Instantly share code, notes, and snippets.

@Checksum
Last active December 29, 2023 17:09
Show Gist options
  • Save Checksum/72d927471c76c76c46418b3ee88e0a7c to your computer and use it in GitHub Desktop.
Save Checksum/72d927471c76c76c46418b3ee88e0a7c to your computer and use it in GitHub Desktop.
Assertion library for jq
# 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;
# 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;
@eddiewebb
Copy link

eddiewebb commented Aug 12, 2022

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.

# must be relative path to assertion utility
include "../utilities/assert";

def check_decision:
  # Declaration
  . as $response
  # Empty array to collect responses
  | []
  # Assertions
  | assert($response | type == "object"; "Response is not an object")
  | assert($response.status | . == "HARD_FAIL"; "Status not Failure not an array")
  | assert($response.hard_failures | type == "array"; "Hard Failutres not an array")
  # Output
  | validate;

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment