From e5be4a47a7e5b86818451327cec145aa69cb167d Mon Sep 17 00:00:00 2001 From: Valentin Deniaud Date: Tue, 29 Nov 2022 16:16:26 +0100 Subject: [PATCH 3/3] testdef: test field conditions (#71296) --- tests/test_testdef.py | 39 +++++++++++++++++++++++++++++++++++++++ wcs/testdef.py | 8 ++++++++ 2 files changed, 47 insertions(+) diff --git a/tests/test_testdef.py b/tests/test_testdef.py index d1dbc3a3f..87d18c192 100644 --- a/tests/test_testdef.py +++ b/tests/test_testdef.py @@ -95,3 +95,42 @@ def test_page_post_condition_invalid(pub): with pytest.raises(TestError) as excinfo: testdef.run(formdef) assert str(excinfo.value) == 'Failed to evaluate page 1 post condition.' + + +def test_field_conditions(pub): + formdef = FormDef() + formdef.name = 'test title' + formdef.fields = [ + fields.StringField(id='1', label='Text', varname='text'), + fields.StringField( + id='2', + label='Text with condition', + varname='text_cond', + required=False, + condition={'type': 'django', 'value': 'form_var_text == "a"'}, + ), + ] + formdef.store() + + formdata = formdef.data_class()() + formdata.just_created() + formdata.receipt_time = datetime.datetime(2021, 1, 1, 0, 0).timetuple() + formdata.data['1'] = 'a' + formdata.data['2'] = 'xxx' + + testdef = TestDef.create_from_formdata(formdef, formdata) + testdef.run(formdef) + + formdata.data['1'] = 'b' + testdef = TestDef.create_from_formdata(formdef, formdata) + with pytest.raises(TestError) as excinfo: + testdef.run(formdef) + assert str(excinfo.value) == 'Tried to fill field "Text with condition" on page 0 but it is hidden.' + + del formdata.data['2'] + testdef = TestDef.create_from_formdata(formdef, formdata) + testdef.run(formdef) + + formdata.data['1'] = 'a' + testdef = TestDef.create_from_formdata(formdef, formdata) + testdef.run(formdef) diff --git a/wcs/testdef.py b/wcs/testdef.py index 10432df96..73edba367 100644 --- a/wcs/testdef.py +++ b/wcs/testdef.py @@ -83,6 +83,14 @@ class TestDef(StorableObject): if field.type in ('subtitle', 'title', 'comment', 'computed'): continue + if not field.is_visible(formdata.data, objectdef): + if field.id in self.data['fields']: + raise TestError( + _('Tried to fill field "%(label)s" on page %(no)d but it is hidden.') + % {'label': field.label, 'no': page_no} + ) + continue + formdata.data[field.id] = self.data['fields'].get(field.id) get_publisher().substitutions.invalidate_cache() -- 2.35.1