Castle: The best Real-Time/Embedded/HighTech language EVER. Attempt 2
Revision | cb6ed189fcdc464830d380c22479d2a9224d3f4e (tree) |
---|---|
Zeit | 2021-12-09 21:49:50 |
Autor | Albert Mietus < albert AT mietus DOT nl > |
Commiter | Albert Mietus < albert AT mietus DOT nl > |
more unit-tests & fixes
@@ -9,4 +9,19 @@ | ||
9 | 9 | @property |
10 | 10 | def position_end(self): return self.parse_tree.position_end |
11 | 11 | |
12 | -class ID(str): pass | |
12 | + | |
13 | +class IDError(ValueError): | |
14 | + "The given ID is not valid as an ID" | |
15 | + | |
16 | +import re | |
17 | + | |
18 | +class ID(str): | |
19 | + _pattern = re.compile(r'[A-Za-z_][A-Za-z0-9_]*') | |
20 | + | |
21 | + @staticmethod | |
22 | + def validate_or_raise(value): | |
23 | + if not isinstance(value, str): | |
24 | + raise IDError("not a str of ID") | |
25 | + if ID._pattern.fullmatch(value) is None: | |
26 | + raise IDError("not a valid pattern") | |
27 | + |
@@ -25,8 +25,9 @@ | ||
25 | 25 | class Setting(PEG): |
26 | 26 | def __init__(self, *, |
27 | 27 | name: ID, |
28 | - value=None, | |
28 | + value, | |
29 | 29 | **kwargs): |
30 | + ID.validate_or_raise(name) | |
30 | 31 | super().__init__(**kwargs) |
31 | 32 | self.name = name |
32 | 33 | self.value = value |
@@ -38,6 +39,7 @@ | ||
38 | 39 | name: ID, |
39 | 40 | value :Expression, |
40 | 41 | **kwargs): |
42 | + ID.validate_or_raise(name) | |
41 | 43 | super().__init__(**kwargs) |
42 | 44 | self.name = name |
43 | 45 | self.value = value |
@@ -0,0 +1,21 @@ | ||
1 | +import pytest | |
2 | + | |
3 | +from castle.peg import Setting | |
4 | + | |
5 | +def test_a_ID(): | |
6 | + a_name, a_val = 'aName', 42 | |
7 | + s=Setting(name=a_name, value=a_val) | |
8 | + assert s.name == a_name, "Remember the ID" | |
9 | + assert s.value == a_val, "Remember the value" | |
10 | + | |
11 | + | |
12 | +def test_needID(): | |
13 | + with pytest.raises(ValueError): | |
14 | + Setting(name=42, value="the name should be an ID, or string") | |
15 | + with pytest.raises(ValueError): | |
16 | + Setting(name='a b', value="a space in not allowed in an ID") | |
17 | + | |
18 | +def test_needID(): | |
19 | + with pytest.raises(TypeError): | |
20 | + Setting(name='Forgot_a_Value') | |
21 | + |