jqlang / jq

Command-line JSON processor
https://jqlang.github.io/jq/
Other
30.23k stars 1.57k forks source link

Allow tests to use slurpfile and rawfile arguments #3123

Open jadutter opened 4 months ago

jadutter commented 4 months ago

Fixed it so that jq can use --slurpfile and --rawfile when running tests. I think it's useful to be able to reference a file containing some data instead of needing to repeatedly copy-paste the same input to different test cases. Particularly since if the input is a larger object, then it's difficult to read since it needs to be all on one line in the test file.

Simple example

Given the following files

raw.csv

id,name
1,Alice
2,Bob

slurp.json

{"foo":"bar"}

and this test file

myjq.test

$raw|split("\n")|.[1]|split(",")|.[1]
null
"Alice"

$slurp|.[0]|.foo
null
"bar"

map(($slurp|.[0]|.foo)+.)
["ista","yonx"]
["barista","baryonx"]

then this command

jq --rawfile raw ./raw.csv --slurpfile slurp ./slurp.json  --run-tests ./myjq.test

should output

Test #1: '$raw|split("\n")|.[1]|split(",")|.[1]' at line number 1
Test #2: '$slurp|.[0]|.foo' at line number 5
Test #3: 'map(($slurp|.[0]|.foo)+.)' at line number 9
3 of 3 tests passed (0 malformed, 0 skipped)
wader commented 4 months ago

I've thought about some kind of binding support in the .test format, either inline or read from a file. Could that be an alternative?

Can't come up with a neat syntax now but something like this:

# read json value inline
%%BIND $input
{
   "a": 123
}

.a
$input
123

type
$input
"object"

# read json value from file.json
%%BIND $input file.json
...
wader commented 4 months ago

Doh i got it wrong, probably more like:

# read json value inline
%%BIND $input
{
   "a": 123
}

$input | .a
null
123

$input | type
null
"object"