1 """Test Conditions module."""
2 from tests.utils import TestCaseWithDB, TestCaseWithServer, TestCaseSansDB
3 from plomtask.conditions import Condition
4 from plomtask.processes import Process
5 from plomtask.todos import Todo
6 from plomtask.exceptions import HandledException
9 class TestsSansDB(TestCaseSansDB):
10 """Tests requiring no DB setup."""
11 checked_class = Condition
12 versioned_defaults_to_test = {'title': 'UNNAMED', 'description': ''}
15 class TestsWithDB(TestCaseWithDB):
16 """Tests requiring DB, but not server setup."""
17 checked_class = Condition
18 default_init_kwargs = {'is_active': False}
19 test_versioneds = {'title': str, 'description': str}
21 def test_remove(self) -> None:
22 """Test .remove() effects on DB and cache."""
25 proc.save(self.db_conn)
26 todo = Todo(None, proc, False, '2024-01-01')
27 todo.save(self.db_conn)
28 # check condition can only be deleted if not depended upon
29 for depender in (proc, todo):
30 assert hasattr(depender, 'save')
31 assert hasattr(depender, 'set_conditions')
34 depender.set_conditions(self.db_conn, [c.id_])
35 depender.save(self.db_conn)
36 with self.assertRaises(HandledException):
37 c.remove(self.db_conn)
38 depender.set_conditions(self.db_conn, [])
39 depender.save(self.db_conn)
40 c.remove(self.db_conn)
43 class TestsWithServer(TestCaseWithServer):
44 """Module tests against our HTTP server/handler (and database)."""
47 def GET_condition_dict(cls, cond: dict[str, object]) -> dict[str, object]:
48 """Return JSON of GET /condition to expect."""
49 return {'is_new': False,
50 'enabled_processes': [],
51 'disabled_processes': [],
52 'enabling_processes': [],
53 'disabling_processes': [],
54 'condition': cond['id'],
55 '_library': {'Condition': cls.as_refs([cond])}}
58 def GET_conditions_dict(cls, conds: list[dict[str, object]]
59 ) -> dict[str, object]:
60 """Return JSON of GET /conditions to expect."""
61 library = {'Condition': cls.as_refs(conds)} if conds else {}
62 d: dict[str, object] = {'conditions': cls.as_id_list(conds),
68 def test_fail_POST_condition(self) -> None:
69 """Test malformed/illegal POST /condition requests."""
70 # check incomplete POST payloads
72 self.check_post({}, url, 400)
73 self.check_post({'title': ''}, url, 400)
74 self.check_post({'title': '', 'description': ''}, url, 400)
75 self.check_post({'title': '', 'is_active': False}, url, 400)
76 self.check_post({'description': '', 'is_active': False}, url, 400)
77 # check valid POST payload on bad paths
78 valid_payload = {'title': '', 'description': '', 'is_active': False}
79 self.check_post(valid_payload, '/condition?id=foo', 400)
81 def test_POST_condition(self) -> None:
82 """Test (valid) POST /condition and its effect on GET /condition[s]."""
83 # test valid POST's effect on …
84 post = {'title': 'foo', 'description': 'oof', 'is_active': False}
85 self.check_post(post, '/condition', redir='/condition?id=1')
87 expected_cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
88 assert isinstance(expected_cond['_versioned'], dict)
89 expected_single = self.GET_condition_dict(expected_cond)
90 self.check_json_get('/condition?id=1', expected_single)
92 expected_all = self.GET_conditions_dict([expected_cond])
93 self.check_json_get('/conditions', expected_all)
94 # test (no) effect of invalid POST to existing Condition on /condition
95 self.check_post({}, '/condition?id=1', 400)
96 self.check_json_get('/condition?id=1', expected_single)
97 # test effect of POST changing title and activeness
98 post = {'title': 'bar', 'description': 'oof', 'is_active': True}
99 self.check_post(post, '/condition?id=1')
100 expected_cond['_versioned']['title'][1] = 'bar'
101 expected_cond['is_active'] = True
102 self.check_json_get('/condition?id=1', expected_single)
103 # test deletion POST's effect, both to return id=1 into empty single, …
104 self.check_post({'delete': ''}, '/condition?id=1', redir='/conditions')
105 expected_cond = self.cond_as_dict()
106 assert isinstance(expected_single['_library'], dict)
107 expected_single['_library']['Condition'] = self.as_refs(
109 self.check_json_get('/condition?id=1', expected_single)
110 # … and full /conditions into empty list
111 expected_all['conditions'] = []
112 expected_all['_library'] = {}
113 self.check_json_get('/conditions', expected_all)
115 def test_GET_condition(self) -> None:
116 """More GET /condition testing, especially for Process relations."""
117 # check expected default status codes
118 self.check_get_defaults('/condition')
119 # make Condition and two Processes that among them establish all
120 # possible ConditionsRelations to it, …
121 cond_post = {'title': 'foo', 'description': 'oof', 'is_active': False}
122 self.check_post(cond_post, '/condition', redir='/condition?id=1')
123 proc1_post = {'title': 'A', 'description': '', 'effort': 1.0,
124 'conditions': [1], 'disables': [1]}
125 proc2_post = {'title': 'B', 'description': '', 'effort': 1.0,
126 'enables': [1], 'blockers': [1]}
127 self.post_process(1, proc1_post)
128 self.post_process(2, proc2_post)
129 # … then check /condition displays all these properly.
130 cond_expected = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
131 assert isinstance(cond_expected['id'], int)
132 proc1 = self.proc_as_dict(conditions=[cond_expected['id']],
133 disables=[cond_expected['id']])
134 proc2 = self.proc_as_dict(2, 'B',
135 blockers=[cond_expected['id']],
136 enables=[cond_expected['id']])
137 display_expected = self.GET_condition_dict(cond_expected)
138 assert isinstance(display_expected['_library'], dict)
139 display_expected['enabled_processes'] = self.as_id_list([proc1])
140 display_expected['disabled_processes'] = self.as_id_list([proc2])
141 display_expected['enabling_processes'] = self.as_id_list([proc2])
142 display_expected['disabling_processes'] = self.as_id_list([proc1])
143 display_expected['_library']['Process'] = self.as_refs([proc1, proc2])
144 self.check_json_get('/condition?id=1', display_expected)
146 def test_GET_conditions(self) -> None:
147 """Test GET /conditions."""
148 # test empty result on empty DB, default-settings on empty params
149 expected = self.GET_conditions_dict([])
150 self.check_json_get('/conditions', expected)
151 # test ignorance of meaningless non-empty params (incl. unknown key),
152 # that 'sort_by' default to 'title' (even if set to something else, as
153 # long as without handler) and 'pattern' get preserved
154 expected['pattern'] = 'bar' # preserved despite zero effect!
155 expected['sort_by'] = 'title' # for clarity (actually already set)
156 url = '/conditions?sort_by=foo&pattern=bar&foo=x'
157 self.check_json_get(url, expected)
158 # test non-empty result, automatic (positive) sorting by title
159 post_cond1 = {'is_active': False, 'title': 'foo', 'description': 'oof'}
160 post_cond2 = {'is_active': False, 'title': 'bar', 'description': 'rab'}
161 post_cond3 = {'is_active': True, 'title': 'baz', 'description': 'zab'}
162 self.check_post(post_cond1, '/condition', redir='/condition?id=1')
163 self.check_post(post_cond2, '/condition', redir='/condition?id=2')
164 self.check_post(post_cond3, '/condition', redir='/condition?id=3')
165 cond1 = self.cond_as_dict(1, False, ['foo'], ['oof'])
166 cond2 = self.cond_as_dict(2, False, ['bar'], ['rab'])
167 cond3 = self.cond_as_dict(3, True, ['baz'], ['zab'])
168 expected = self.GET_conditions_dict([cond2, cond3, cond1])
169 self.check_json_get('/conditions', expected)
170 # test other sortings
171 # (NB: by .is_active has two items of =False, their order currently
172 # is not explicitly made predictable, so _may_ fail until we do)
173 expected['sort_by'] = '-title'
174 expected['conditions'] = self.as_id_list([cond1, cond3, cond2])
175 self.check_json_get('/conditions?sort_by=-title', expected)
176 expected['sort_by'] = 'is_active'
177 expected['conditions'] = self.as_id_list([cond1, cond2, cond3])
178 self.check_json_get('/conditions?sort_by=is_active', expected)
179 expected['sort_by'] = '-is_active'
180 expected['conditions'] = self.as_id_list([cond3, cond1, cond2])
181 self.check_json_get('/conditions?sort_by=-is_active', expected)
182 # test pattern matching on title
183 expected = self.GET_conditions_dict([cond2, cond3])
184 expected['pattern'] = 'ba'
185 self.check_json_get('/conditions?pattern=ba', expected)
186 # test pattern matching on description
187 assert isinstance(expected['_library'], dict)
188 expected['pattern'] = 'of'
189 expected['conditions'] = self.as_id_list([cond1])
190 expected['_library']['Condition'] = self.as_refs([cond1])
191 self.check_json_get('/conditions?pattern=of', expected)