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