home · contact · privacy
afb1841e9a6c230a64f66c9144169999e70da372
[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_from_table_row(self) -> None:
23         """Test .from_table_row() properly reads in class from DB"""
24         super().test_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              '_versioned': {
78                  'title': {},
79                  'description': {}
80                  }
81              }
82         titles = titles if titles else []
83         descriptions = descriptions if descriptions else []
84         assert isinstance(d['_versioned'], dict)
85         for i, title in enumerate(titles):
86             d['_versioned']['title'][i] = title
87         for i, description in enumerate(descriptions):
88             d['_versioned']['description'][i] = description
89         return d
90
91     @staticmethod
92     def proc_as_dict(id_: int = 1,
93                      title: str = 'A',
94                      enables: None | list[dict[str, object]] = None,
95                      disables: None | list[dict[str, object]] = None,
96                      conditions: None | list[dict[str, object]] = None,
97                      blockers: None | list[dict[str, object]] = None
98                      ) -> dict[str, object]:
99         """Return JSON of Process to expect."""
100         # pylint: disable=too-many-arguments
101         d = {'id': id_,
102              'calendarize': False,
103              'suppressed_steps': [],
104              'explicit_steps': [],
105              '_versioned': {
106                  'title': {0: title},
107                  'description': {0: ''},
108                  'effort': {0: 1.0}
109                  },
110              'conditions': conditions if conditions else [],
111              'disables': disables if disables else [],
112              'enables': enables if enables else [],
113              'blockers': blockers if blockers else []}
114         return d
115
116     def test_do_POST_condition(self) -> None:
117         """Test POST /condition and its effect on GET /condition[s]."""
118         # check empty POST fails
119         self.check_post({}, '/condition', 400)
120         # test valid POST's effect on …
121         post = {'title': 'foo', 'description': 'oof', 'is_active': False}
122         self.check_post(post, '/condition', 302, '/condition?id=1')
123         # … single /condition
124         cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
125         expected_single: dict[str, object]
126         expected_single = {'is_new': False,
127                            'enabled_processes': [],
128                            'disabled_processes': [],
129                            'enabling_processes': [],
130                            'disabling_processes': [],
131                            'condition': cond}
132         self.check_json_get('/condition?id=1', expected_single)
133         # … full /conditions
134         expected_all: dict[str, object]
135         expected_all = {'conditions': [cond],
136                         'sort_by': 'title', 'pattern': ''}
137         self.check_json_get('/conditions', expected_all)
138         # test effect of invalid POST to existing Condition on /condition
139         self.check_post({}, '/condition?id=1', 400)
140         self.check_json_get('/condition?id=1', expected_single)
141         # test effect of POST changing title and activeness
142         post = {'title': 'bar', 'description': 'oof', 'is_active': True}
143         self.check_post(post, '/condition?id=1', 302)
144         assert isinstance(expected_single['condition'], dict)
145         expected_single['condition']['_versioned']['title'][1] = 'bar'
146         expected_single['condition']['is_active'] = True
147         self.check_json_get('/condition?id=1', expected_single)
148         # test deletion POST's effect on …
149         self.check_post({'delete': ''}, '/condition?id=1', 302, '/conditions')
150         cond = self.cond_as_dict()
151         expected_single['condition'] = cond
152         self.check_json_get('/condition?id=1', expected_single)
153         # … full /conditions
154         expected_all['conditions'] = []
155         self.check_json_get('/conditions', expected_all)
156
157     def test_do_GET_condition(self) -> None:
158         """More GET /condition testing, especially for Process relations."""
159         # check expected default status codes
160         self.check_get_defaults('/condition')
161         # check display of process relations
162         form_data = {'title': 'foo', 'description': 'oof', 'is_active': False}
163         self.check_post(form_data, '/condition', 302, '/condition?id=1')
164         proc_1_post = {'title': 'A', 'description': '', 'effort': 1.0,
165                        'condition': [1], 'disables': [1]}
166         self.post_process(1, proc_1_post)
167         proc_2_post = {'title': 'B', 'description': '', 'effort': 1.0,
168                        'enables': [1], 'blocker': [1]}
169         self.post_process(2, proc_2_post)
170         cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
171         proc_1 = self.proc_as_dict(conditions=[cond], disables=[cond])
172         proc_2 = self.proc_as_dict(2, 'B', blockers=[cond], enables=[cond])
173         expected_single = {'is_new': False,
174                            'enabled_processes': [proc_1],
175                            'disabled_processes': [proc_2],
176                            'enabling_processes': [proc_2],
177                            'disabling_processes': [proc_1],
178                            'condition': cond}
179         self.check_json_get('/condition?id=1', expected_single)
180
181     def test_do_GET_conditions(self) -> None:
182         """Test GET /conditions."""
183         # test empty result on empty DB, default-settings on empty params
184         expected_json: dict[str, object] = {'conditions': [],
185                                             'sort_by': 'title',
186                                             'pattern': ''}
187         self.check_json_get('/conditions', expected_json)
188         # test on meaningless non-empty params (incl. entirely un-used key)
189         expected_json = {'conditions': [],
190                          'sort_by': 'title',  # nonsense "foo" defaulting
191                          'pattern': 'bar'}  # preserved despite zero effect
192         self.check_json_get('/conditions?sort_by=foo&pattern=bar&foo=x',
193                             expected_json)
194         # test non-empty result, automatic (positive) sorting by title
195         post_1 = {'title': 'foo', 'description': 'oof', 'is_active': False}
196         self.check_post(post_1, '/condition', 302, '/condition?id=1')
197         post_2 = {'title': 'bar', 'description': 'rab', 'is_active': False}
198         self.check_post(post_2, '/condition', 302, '/condition?id=2')
199         post_3 = {'title': 'baz', 'description': 'zab', 'is_active': True}
200         self.check_post(post_3, '/condition', 302, '/condition?id=3')
201         cond_1 = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
202         cond_2 = self.cond_as_dict(2, titles=['bar'], descriptions=['rab'])
203         cond_3 = self.cond_as_dict(3, True, ['baz'], ['zab'])
204         cons = [cond_2, cond_3, cond_1]
205         expected_json = {'conditions': cons, 'sort_by': 'title', 'pattern': ''}
206         self.check_json_get('/conditions', expected_json)
207         # test other sortings
208         # (NB: by .is_active has two items of =False, their order currently
209         # is not explicitly made predictable, so mail fail until we do)
210         expected_json['conditions'] = [cond_1, cond_3, cond_2]
211         expected_json['sort_by'] = '-title'
212         self.check_json_get('/conditions?sort_by=-title', expected_json)
213         expected_json['conditions'] = [cond_1, cond_2, cond_3]
214         expected_json['sort_by'] = 'is_active'
215         self.check_json_get('/conditions?sort_by=is_active', expected_json)
216         expected_json['conditions'] = [cond_3, cond_1, cond_2]
217         expected_json['sort_by'] = '-is_active'
218         self.check_json_get('/conditions?sort_by=-is_active', expected_json)
219         # test pattern matching on title
220         expected_json = {'conditions': [cond_2, cond_3],
221                          'sort_by': 'title', 'pattern': 'ba'}
222         self.check_json_get('/conditions?pattern=ba', expected_json)
223         # test pattern matching on description
224         expected_json['conditions'] = [cond_1]
225         expected_json['pattern'] = 'oo'
226         self.check_json_get('/conditions?pattern=oo', expected_json)