Skip to content

Commit 53641d0

Browse files
authored
Merge pull request #122 from asottile/custom-display-name
add a custom display name for loading from a file
2 parents a05f8f2 + a9dbeca commit 53641d0

File tree

2 files changed

+40
-7
lines changed

2 files changed

+40
-7
lines changed

cfgv.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,12 +392,15 @@ def load_from_filename(
392392
schema,
393393
load_strategy,
394394
exc_tp=ValidationError,
395+
*,
396+
display_filename=None,
395397
):
398+
display_filename = display_filename or filename
396399
with reraise_as(exc_tp):
397400
if not os.path.isfile(filename):
398-
raise ValidationError(f'{filename} is not a file')
401+
raise ValidationError(f'{display_filename} is not a file')
399402

400-
with validate_context(f'File {filename}'):
403+
with validate_context(f'File {display_filename}'):
401404
try:
402405
with open(filename, encoding='utf-8') as f:
403406
contents = f.read()

tests/cfgv_test.py

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,12 @@
3636

3737

3838
def _assert_exception_trace(e, trace):
39-
inner = e
40-
for ctx in trace[:-1]:
41-
assert inner.ctx == ctx
42-
inner = inner.error_msg
43-
assert inner.error_msg == trace[-1]
39+
parts = []
40+
while e.ctx is not None:
41+
parts.append(e.ctx)
42+
e = e.error_msg
43+
parts.append(e.error_msg)
44+
assert tuple(parts) == trace
4445

4546

4647
def test_ValidationError_simple_str():
@@ -582,6 +583,35 @@ def test_load_from_filename_applies_defaults(tmpdir):
582583
assert ret == {'key': False}
583584

584585

586+
def test_load_from_filename_custom_display_no_file(tmp_path):
587+
with pytest.raises(ValidationError) as excinfo:
588+
load_from_filename(
589+
tmp_path.joinpath('cfg.json'),
590+
map_required,
591+
json.loads,
592+
display_filename='cfg.json',
593+
)
594+
_assert_exception_trace(excinfo.value.args[0], ('cfg.json is not a file',))
595+
596+
597+
def test_load_from_filename_custom_display_error(tmp_path):
598+
f = tmp_path.joinpath('cfg.json')
599+
f.write_text('{}')
600+
with pytest.raises(ValidationError) as excinfo:
601+
load_from_filename(
602+
f,
603+
map_required,
604+
json.loads,
605+
display_filename='cfg.json',
606+
)
607+
expected = (
608+
'File cfg.json',
609+
'At foo(key=MISSING)',
610+
'Missing required key: key',
611+
)
612+
_assert_exception_trace(excinfo.value.args[0], expected)
613+
614+
585615
conditional_recurse = Map(
586616
'Map', None,
587617

0 commit comments

Comments
 (0)