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