Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,9 @@ test(
join_paths(meson.current_source_dir(), 'test/data')],
workdir : join_paths(meson.current_source_dir(), 'test/data'),
)

test(
'runner_arguments',
python,
args : ['-B', join_paths(meson.current_source_dir(), 'test/test_runjsontests.py')],
)
4 changes: 4 additions & 0 deletions src/jsontestrunner/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ if(PYTHONINTERP_FOUND)
WORKING_DIRECTORY "${TEST_DIR}/data"
)

add_test(NAME jsoncpp_runner_arguments
COMMAND "${PYTHON_EXECUTABLE}" -B "${TEST_DIR}/test_runjsontests.py"
)

# Both tests write .actual/.actual-rewrite along with test data, need to prevent collision when running tests via ctest -j
set_tests_properties(jsoncpp_readerwriter jsoncpp_readerwriter_json_checker
PROPERTIES RESOURCE_LOCK "test_data_files"
Expand Down
34 changes: 16 additions & 18 deletions test/runjsontests.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,23 @@
import os
import os.path
import optparse
import subprocess

VALGRIND_CMD = 'valgrind --tool=memcheck --leak-check=yes --undef-value-errors=yes '

def getStatusOutput(cmd):
"""
Return int, unicode (for both Python 2 and 3).
Note: os.popen().close() would return None for 0.
Return exit status and text output. Zero means success.
"""
print(cmd, file=sys.stderr)
pipe = os.popen(cmd)
process_output = pipe.read()
try:
# We have been using os.popen(). When we read() the result
# we get 'str' (bytes) in py2, and 'str' (unicode) in py3.
# Ugh! There must be a better way to handle this.
process_output = process_output.decode('utf-8')
except AttributeError:
pass # python3
status = pipe.close()
return status, process_output
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
universal_newlines=True)
except OSError as error:
print(error, file=sys.stderr)
return 1, ''
process_output = process.communicate()[0]
return process.returncode, process_output
def compareOutputs(expected, actual, message):
expected = expected.strip().replace('\r','').split('\n')
actual = actual.strip().replace('\r','').split('\n')
Expand Down Expand Up @@ -107,18 +104,19 @@ def runAllTests(jsontest_executable_path, input_path = None,
]

failed_tests = []
valgrind_path = use_valgrind and VALGRIND_CMD or ''
valgrind_args = VALGRIND_CMD.split() if use_valgrind else []
for input_path in tests:
expect_failure = os.path.basename(input_path).startswith('fail')
is_json_checker_test = os.path.basename(os.path.dirname(input_path)) == "jsonchecker"
is_parse_only = is_json_checker_test or expect_failure
is_strict_test = ('_strict_' in os.path.basename(input_path)) or is_json_checker_test
print('TESTING:', input_path, end=' ')
options = is_parse_only and '--parse-only' or ''
options += is_strict_test and ' --strict' or ''
options += ' --json-writer %s'%writerClass
cmd = '%s%s %s "%s"' % ( valgrind_path, jsontest_executable_path, options,
input_path)
cmd = valgrind_args + [jsontest_executable_path]
if is_parse_only:
cmd.append('--parse-only')
if is_strict_test:
cmd.append('--strict')
cmd.extend(['--json-writer', writerClass, input_path])
status, process_output = getStatusOutput(cmd)
if is_parse_only:
if expect_failure:
Expand Down
101 changes: 101 additions & 0 deletions test/test_runjsontests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Copyright 2026 The JsonCpp Authors
# Distributed under MIT license, or public domain if desired and recognized.
# See file LICENSE for details.

import contextlib
import io
import os
import sys
import tempfile
import unittest
from unittest import mock

import runjsontests


class RunnerTest(unittest.TestCase):
def test_arguments_are_not_split(self):
with contextlib.redirect_stderr(io.StringIO()):
status, output = runjsontests.getStatusOutput([
sys.executable, '-c',
'import sys; print(repr(sys.argv[1:]))',
'argument with spaces', 'quote"value', 'single\'quote'])
self.assertEqual(status, 0)
self.assertEqual(output.strip(),
repr(['argument with spaces', 'quote"value',
'single\'quote']))

def test_exit_status_and_output(self):
with contextlib.redirect_stderr(io.StringIO()):
status, output = runjsontests.getStatusOutput([
sys.executable, '-c',
'import sys; print("output"); sys.exit(7)'])
self.assertEqual(status, 7)
self.assertEqual(output, 'output\n')

def test_missing_executable_returns_failure(self):
with tempfile.TemporaryDirectory() as directory:
missing = os.path.join(directory, 'missing executable')
with contextlib.redirect_stderr(io.StringIO()):
status, output = runjsontests.getStatusOutput([missing])
self.assertTrue(status)
self.assertEqual(output, '')

@unittest.skipIf(os.name == 'nt', 'POSIX executable permission test')
def test_non_executable_file_returns_failure(self):
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, 'not executable')
with open(path, 'w') as executable:
executable.write('not executable')
os.chmod(path, 0o600)
with contextlib.redirect_stderr(io.StringIO()):
status, output = runjsontests.getStatusOutput([path])
self.assertTrue(status)
self.assertEqual(output, '')

def test_missing_executable_does_not_stop_remaining_fixtures(self):
with tempfile.TemporaryDirectory() as directory:
missing = os.path.join(directory, 'missing executable')
for name in ['first.json', 'second.json']:
with open(os.path.join(directory, name), 'w') as fixture:
fixture.write('{}')
output = io.StringIO()
with contextlib.redirect_stdout(output):
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(runjsontests.FailError):
runjsontests.runAllTests(missing, directory)
self.assertIn('first.json', output.getvalue())
self.assertIn('second.json', output.getvalue())
self.assertIn('Test results: 0 passed, 2 failed.', output.getvalue())

def check_command(self, input_path, expected_options, use_valgrind=False):
executable = os.path.join('build space', 'runner executable')
with mock.patch.object(runjsontests, 'getStatusOutput',
return_value=(1, 'expected parse failure')) as run:
with contextlib.redirect_stdout(io.StringIO()):
runjsontests.runAllTests(executable, input_path,
use_valgrind=use_valgrind)
expected = runjsontests.VALGRIND_CMD.split() if use_valgrind else []
expected += [executable] + expected_options
expected += ['--json-writer', 'StyledWriter', input_path]
run.assert_called_once_with(expected)

def test_parse_only_keeps_spaced_paths(self):
self.check_command(os.path.join('fixture space', 'fail_example.json'),
['--parse-only'])

def test_strict_parse_only_options(self):
self.check_command(os.path.join('fixture space', 'fail_strict_case.json'),
['--parse-only', '--strict'])

def test_json_checker_options(self):
self.check_command(os.path.join('jsonchecker', 'fail1.json'),
['--parse-only', '--strict'])

def test_valgrind_prefix(self):
self.check_command(os.path.join('fixture space', 'fail_example.json'),
['--parse-only'], use_valgrind=True)


if __name__ == '__main__':
unittest.main()