From 69804ec9a5ffdf742ed6ca868062f3c8fa67e11f Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Mon, 1 May 2023 17:54:08 +0100 Subject: Support multiple input values --- jq.pyx | 8 ++++++++ tests/jq_tests.py | 23 ++++++++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/jq.pyx b/jq.pyx index a280687..15882ad 100644 --- a/jq.pyx +++ b/jq.pyx @@ -1,3 +1,4 @@ +import io import json import threading @@ -255,6 +256,13 @@ cdef class _Program(object): def input_value(self, value): return self.input_text(json.dumps(value)) + def input_values(self, values): + fileobj = io.StringIO() + for value in values: + json.dump(value, fileobj) + fileobj.write("\n") + return self.input_text(fileobj.getvalue()) + def input_text(self, text): return _ProgramWithInput(self._jq_state_pool, text.encode("utf8")) diff --git a/tests/jq_tests.py b/tests/jq_tests.py index d97b1c2..d97f2bd 100644 --- a/tests/jq_tests.py +++ b/tests/jq_tests.py @@ -73,6 +73,14 @@ def test_input_can_be_value(): assert_equal("42", result) +def test_input_can_be_multiple_values(): + program = jq.compile(".") + + result = program.input_values([1, 2, 3]).all() + + assert_equal([1, 2, 3], result) + + def test_input_can_be_text(): program = jq.compile(".") @@ -81,6 +89,14 @@ def test_input_can_be_text(): assert_equal(42, result) +def test_input_can_be_text_with_multiple_values_separated_by_newlines(): + program = jq.compile(".") + + result = program.input_text("1\n2\n3").all() + + assert_equal([1, 2, 3], result) + + def test_when_text_method_is_used_on_result_then_output_is_serialised_to_json_string(): assert_equal( '"42"', @@ -141,13 +157,6 @@ def test_iterators_from_same_program_and_input_are_independent(): assert_equal(4, next(second)) -def test_multiple_inputs_in_text_input_are_separated_by_newlines(): - assert_equal( - [2, 3, 4], - jq.compile(".+1").input(text="1\n2\n3").all() - ) - - def test_value_error_is_raised_if_program_is_invalid(): try: jq.compile("!") -- cgit v1.2.3