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