home · contact · privacy
Refactor Conditions GET/POST testing.
[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     do_id_test = True
13     versioned_defaults_to_test = {'title': 'UNNAMED', 'description': ''}
14
15
16 class TestsWithDB(TestCaseWithDB):
17     """Tests requiring DB, but not server setup."""
18     checked_class = Condition
19     default_init_kwargs = {'is_active': False}
20     test_versioneds = {'title': str, 'description': str}
21
22     def test_Condition_from_table_row(self) -> None:
23         """Test .from_table_row() properly reads in class from DB"""
24         self.check_from_table_row()
25         self.check_versioned_from_table_row('title', str)
26         self.check_versioned_from_table_row('description', str)
27
28     def test_Condition_by_id(self) -> None:
29         """Test .by_id(), including creation."""
30         self.check_by_id()
31
32     def test_Condition_all(self) -> None:
33         """Test .all()."""
34         self.check_all()
35
36     def test_Condition_singularity(self) -> None:
37         """Test pointers made for single object keep pointing to it."""
38         self.check_singularity('is_active', True)
39
40     def test_Condition_versioned_attributes_singularity(self) -> None:
41         """Test behavior of VersionedAttributes on saving (with .title)."""
42         self.check_versioned_singularity()
43
44     def test_Condition_remove(self) -> None:
45         """Test .remove() effects on DB and cache."""
46         self.check_remove()
47         proc = Process(None)
48         proc.save(self.db_conn)
49         todo = Todo(None, proc, False, '2024-01-01')
50         for depender in (proc, todo):
51             assert hasattr(depender, 'save')
52             assert hasattr(depender, 'set_conditions')
53             c = Condition(None)
54             c.save(self.db_conn)
55             depender.save(self.db_conn)
56             depender.set_conditions(self.db_conn, [c.id_], 'conditions')
57             depender.save(self.db_conn)
58             with self.assertRaises(HandledException):
59                 c.remove(self.db_conn)
60             depender.set_conditions(self.db_conn, [], 'conditions')
61             depender.save(self.db_conn)
62             c.remove(self.db_conn)
63
64
65 class TestsWithServer(TestCaseWithServer):
66     """Module tests against our HTTP server/handler (and database)."""
67
68     @staticmethod
69     def cond_as_dict(id_: int = 1,
70                      is_active: bool = False,
71                      titles: None | list[str] = None,
72                      descriptions: None | list[str] = None
73                      ) -> dict[str, object]:
74         """Return JSON of Condition to expect."""
75         d = {'id': id_,
76              'is_active': is_active,
77              'title': {'history': {}, 'parent_id': id_},
78              'description': {'history': {}, 'parent_id': id_}}
79         titles = titles if titles else []
80         descriptions = descriptions if descriptions else []
81         for i, title in enumerate(titles):
82             assert isinstance(d['title'], dict)
83             d['title']['history'][f'[{i}]'] = title
84         for i, description in enumerate(descriptions):
85             assert isinstance(d['description'], dict)
86             d['description']['history'][f'[{i}]'] = description
87         return d
88
89     @staticmethod
90     def proc_as_dict(id_: int = 1,
91                      title: str = 'A',
92                      enables: None | list[dict[str, object]] = None,
93                      disables: None | list[dict[str, object]] = None,
94                      conditions: None | list[dict[str, object]] = None,
95                      blockers: None | list[dict[str, object]] = None
96                      ) -> dict[str, object]:
97         """Return JSON of Process to expect."""
98         # pylint: disable=too-many-arguments
99         d = {'id': id_,
100              'calendarize': False,
101              'suppressed_steps': [],
102              'explicit_steps': [],
103              'title': {'history': {'[0]': title}, 'parent_id': id_},
104              'effort': {'history': {'[0]': 1.0}, 'parent_id': id_},
105              'description': {'history': {'[0]': ''}, 'parent_id': id_},
106              'conditions': conditions if conditions else [],
107              'disables': disables if disables else [],
108              'enables': enables if enables else [],
109              'blockers': blockers if blockers else []}
110         return d
111
112     def test_do_POST_condition(self) -> None:
113         """Test POST /condition and its effect on GET /condition[s]."""
114         # check empty POST fails
115         self.check_post({}, '/condition', 400)
116         # test valid POST's effect on …
117         post = {'title': 'foo', 'description': 'oof', 'is_active': False}
118         self.check_post(post, '/condition', 302, '/condition?id=1')
119         # … single /condition
120         cond = self.cond_as_dict(titles = ['foo'], descriptions = ['oof'])
121         expected_single: dict[str, object]
122         expected_single = {'is_new': False,
123                            'enabled_processes': [],
124                            'disabled_processes': [],
125                            'enabling_processes': [],
126                            'disabling_processes': [],
127                            'condition': cond}
128         self.check_json_get('/condition?id=1', expected_single)
129         # … full /conditions
130         expected_all: dict[str, object]
131         expected_all = {'conditions': [cond],
132                         'sort_by': 'title', 'pattern': ''}
133         self.check_json_get('/conditions', expected_all)
134         # test effect of invalid POST to existing Condition on /condition
135         self.check_post({}, '/condition?id=1', 400)
136         self.check_json_get('/condition?id=1', expected_single)
137         # test effect of POST changing title and activeness
138         post = {'title': 'bar', 'description': 'oof', 'is_active': True}
139         self.check_post(post, '/condition?id=1', 302)
140         expected_single['condition']['title']['history']['[1]'] = 'bar'
141         expected_single['condition']['is_active'] = True
142         self.check_json_get('/condition?id=1', expected_single)
143         # test deletion POST's effect on …
144         self.check_post({'delete': ''}, '/condition?id=1', 302, '/conditions')
145         cond = self.cond_as_dict()
146         expected_single['condition'] = cond
147         self.check_json_get('/condition?id=1', expected_single)
148         # … full /conditions
149         expected_all['conditions'] = []
150         self.check_json_get('/conditions', expected_all)
151
152     def test_do_GET_condition(self) -> None:
153         """More GET /condition testing, especially for Process relations."""
154         # check expected default status codes
155         self.check_get_defaults('/condition')
156         # check display of process relations
157         form_data = {'title': 'foo', 'description': 'oof', 'is_active': False}
158         self.check_post(form_data, '/condition', 302, '/condition?id=1')
159         proc_1_post = {'title': 'A', 'description': '', 'effort': 1.0,
160                        'condition': [1], 'disables': [1]}
161         self.post_process(1, proc_1_post)
162         proc_2_post = {'title': 'B', 'description': '', 'effort': 1.0,
163                        'enables': [1], 'blocker': [1]}
164         self.post_process(2, proc_2_post)
165         cond = self.cond_as_dict(titles = ['foo'], descriptions = ['oof'])
166         proc_1 = self.proc_as_dict(conditions=[cond], disables=[cond])
167         proc_2 = self.proc_as_dict(2, 'B', blockers=[cond], enables=[cond])
168         expected_single = {'is_new': False,
169                            'enabled_processes': [proc_1],
170                            'disabled_processes': [proc_2],
171                            'enabling_processes': [proc_2],
172                            'disabling_processes': [proc_1],
173                            'condition': cond}
174         self.check_json_get('/condition?id=1', expected_single)
175
176     def test_do_GET_conditions(self) -> None:
177         """Test GET /conditions."""
178         # test empty result on empty DB, default-settings on empty params
179         expected_json: dict[str, object] = {'conditions': [],
180                                             'sort_by': 'title',
181                                             'pattern': ''}
182         self.check_json_get('/conditions', expected_json)
183         # test on meaningless non-empty params (incl. entirely un-used key)
184         expected_json = {'conditions': [],
185                          'sort_by': 'title',  # nonsense "foo" defaulting
186                          'pattern': 'bar'}  # preserved despite zero effect
187         self.check_json_get('/conditions?sort_by=foo&pattern=bar&foo=x',
188                             expected_json)
189         # test non-empty result, automatic (positive) sorting by title
190         post_1 = {'title': 'foo', 'description': 'oof', 'is_active': False}
191         self.check_post(post_1, '/condition', 302, '/condition?id=1')
192         post_2 = {'title': 'bar', 'description': 'rab', 'is_active': False}
193         self.check_post(post_2, '/condition', 302, '/condition?id=2')
194         post_3 = {'title': 'baz', 'description': 'zab', 'is_active': True}
195         self.check_post(post_3, '/condition', 302, '/condition?id=3')
196         cond_1 = self.cond_as_dict(titles = ['foo'], descriptions = ['oof'])
197         cond_2 = self.cond_as_dict(2, titles=['bar'], descriptions=['rab'])
198         cond_3 = self.cond_as_dict(3, True, ['baz'], ['zab'])
199         cons = [cond_2, cond_3, cond_1]
200         expected_json = {'conditions': cons, 'sort_by': 'title', 'pattern': ''}
201         self.check_json_get('/conditions', expected_json)
202         # test other sortings
203         # (NB: by .is_active has two items of =False, their order currently
204         # is not explicitly made predictable, so mail fail until we do)
205         expected_json['conditions'] = [cond_1, cond_3, cond_2]
206         expected_json['sort_by'] = '-title'
207         self.check_json_get('/conditions?sort_by=-title', expected_json)
208         expected_json['conditions'] = [cond_1, cond_2, cond_3]
209         expected_json['sort_by'] = 'is_active'
210         self.check_json_get('/conditions?sort_by=is_active', expected_json)
211         expected_json['conditions'] = [cond_3, cond_1, cond_2]
212         expected_json['sort_by'] = '-is_active'
213         self.check_json_get('/conditions?sort_by=-is_active', expected_json)
214         # test pattern matching on title
215         expected_json = {'conditions': [cond_2, cond_3],
216                          'sort_by': 'title', 'pattern': 'ba'}
217         self.check_json_get('/conditions?pattern=ba', expected_json)
218         # test pattern matching on description
219         expected_json['conditions'] = [cond_1]
220         expected_json['pattern'] = 'oo'
221         self.check_json_get('/conditions?pattern=oo', expected_json)