Skip to content

Commit

Permalink
[feat] Parse convertible mapping objects with json module
Browse files Browse the repository at this point in the history
The advantage is that we can automatically convert nested mappings, like for
example the `extra_resources` attribute, which can thus be set from the command
line.
  • Loading branch information
giordano committed May 2, 2023
1 parent 45675f9 commit 3488a0e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
23 changes: 10 additions & 13 deletions reframe/utility/typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@

import abc
import datetime
import json
import re


Expand Down Expand Up @@ -322,19 +323,15 @@ def __rfm_cast_str__(cls, s):
mappping_type = cls._type
key_type = cls._key_type
value_type = cls._value_type
seq = []
for key_datum in s.split(','):
try:
k, v = key_datum.split(':')
except ValueError:
# Re-raise as TypeError
raise TypeError(
f'cannot convert string {s!r} to {cls.__name__!r}'
) from None

seq.append((key_type(k), value_type(v)))

return mappping_type(seq)
# Convert string to JSON format: wrap it with braces and add double
# quotes where necessary.
s = f'{{{s}}}'
s = re.sub('([:,{] *)([^":,{}]+)', r'\1"\2"', s)
# Parse the JSON string.
d = json.loads(s)
# Enforce the desired output types.
d = {key_type(key): value_type(value) for key, value in d.items()}
return mappping_type(d)


class _StrType(_SequenceType):
Expand Down
4 changes: 2 additions & 2 deletions unittests/test_typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import pytest

import reframe.utility.typecheck as typ

import json

def assert_type_hierarchy(builtin_type, ctype):
assert isinstance(ctype, type)
Expand Down Expand Up @@ -208,7 +208,7 @@ def test_mapping_type():
# Test conversions
assert typ.Dict[str, int]('a:1,b:2') == {'a': 1, 'b': 2}

with pytest.raises(TypeError):
with pytest.raises(json.decoder.JSONDecodeError):
typ.Dict[str, int]('a:1,b')


Expand Down

0 comments on commit 3488a0e

Please sign in to comment.