home · contact · privacy
Simplify JSON-ification of VersionedAttributes.
[plomtask] / tests / processes.py
1 """Test Processes module."""
2 from tests.utils import TestCaseWithDB, TestCaseWithServer, TestCaseSansDB
3 from plomtask.processes import Process, ProcessStep, ProcessStepsNode
4 from plomtask.conditions import Condition
5 from plomtask.exceptions import HandledException, NotFoundException
6 from plomtask.todos import Todo
7
8
9 class TestsSansDB(TestCaseSansDB):
10     """Module tests not requiring DB setup."""
11     checked_class = Process
12     do_id_test = True
13     versioned_defaults_to_test = {'title': 'UNNAMED', 'description': '',
14                                   'effort': 1.0}
15
16
17 class TestsSansDBProcessStep(TestCaseSansDB):
18     """Module tests not requiring DB setup."""
19     checked_class = ProcessStep
20     do_id_test = True
21     default_init_args = [2, 3, 4]
22
23
24 class TestsWithDB(TestCaseWithDB):
25     """Module tests requiring DB setup."""
26     checked_class = Process
27     test_versioneds = {'title': str, 'description': str, 'effort': float}
28
29     def three_processes(self) -> tuple[Process, Process, Process]:
30         """Return three saved processes."""
31         p1, p2, p3 = Process(None), Process(None), Process(None)
32         for p in [p1, p2, p3]:
33             p.save(self.db_conn)
34         return p1, p2, p3
35
36     def p_of_conditions(self) -> tuple[Process, list[Condition],
37                                        list[Condition], list[Condition]]:
38         """Return Process and its three Condition sets."""
39         p = Process(None)
40         c1, c2, c3 = Condition(None), Condition(None), Condition(None)
41         for c in [c1, c2, c3]:
42             c.save(self.db_conn)
43         assert isinstance(c1.id_, int)
44         assert isinstance(c2.id_, int)
45         assert isinstance(c3.id_, int)
46         set_1 = [c1, c2]
47         set_2 = [c2, c3]
48         set_3 = [c1, c3]
49         p.set_conditions(self.db_conn, [c.id_ for c in set_1
50                                         if isinstance(c.id_, int)])
51         p.set_enables(self.db_conn, [c.id_ for c in set_2
52                                      if isinstance(c.id_, int)])
53         p.set_disables(self.db_conn, [c.id_ for c in set_3
54                                       if isinstance(c.id_, int)])
55         p.save(self.db_conn)
56         return p, set_1, set_2, set_3
57
58     def test_Process_conditions_saving(self) -> None:
59         """Test .save/.save_core."""
60         p, set1, set2, set3 = self.p_of_conditions()
61         r = Process.by_id(self.db_conn, p.id_)
62         self.assertEqual(sorted(r.conditions), sorted(set1))
63         self.assertEqual(sorted(r.enables), sorted(set2))
64         self.assertEqual(sorted(r.disables), sorted(set3))
65
66     def test_Process_from_table_row(self) -> None:
67         """Test .from_table_row() properly reads in class from DB"""
68         self.check_from_table_row()
69         self.check_versioned_from_table_row('title', str)
70         self.check_versioned_from_table_row('description', str)
71         self.check_versioned_from_table_row('effort', float)
72         p, set1, set2, set3 = self.p_of_conditions()
73         p.save(self.db_conn)
74         assert isinstance(p.id_, int)
75         for row in self.db_conn.row_where(self.checked_class.table_name,
76                                           'id', p.id_):
77             r = Process.from_table_row(self.db_conn, row)
78             self.assertEqual(sorted(r.conditions), sorted(set1))
79             self.assertEqual(sorted(r.enables), sorted(set2))
80             self.assertEqual(sorted(r.disables), sorted(set3))
81
82     def test_Process_steps(self) -> None:
83         """Test addition, nesting, and non-recursion of ProcessSteps"""
84         # pylint: disable=too-many-locals
85         # pylint: disable=too-many-statements
86         p1, p2, p3 = self.three_processes()
87         assert isinstance(p1.id_, int)
88         assert isinstance(p2.id_, int)
89         assert isinstance(p3.id_, int)
90         steps_p1: list[ProcessStep] = []
91         # add step of process p2 as first (top-level) step to p1
92         s_p2_to_p1 = ProcessStep(None, p1.id_, p2.id_, None)
93         steps_p1 += [s_p2_to_p1]
94         p1.set_steps(self.db_conn, steps_p1)
95         p1_dict: dict[int, ProcessStepsNode] = {}
96         p1_dict[1] = ProcessStepsNode(p2, None, True, {})
97         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
98         # add step of process p3 as second (top-level) step to p1
99         s_p3_to_p1 = ProcessStep(None, p1.id_, p3.id_, None)
100         steps_p1 += [s_p3_to_p1]
101         p1.set_steps(self.db_conn, steps_p1)
102         p1_dict[2] = ProcessStepsNode(p3, None, True, {})
103         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
104         # add step of process p3 as first (top-level) step to p2,
105         steps_p2: list[ProcessStep] = []
106         s_p3_to_p2 = ProcessStep(None, p2.id_, p3.id_, None)
107         steps_p2 += [s_p3_to_p2]
108         p2.set_steps(self.db_conn, steps_p2)
109         # expect it as implicit sub-step of p1's second (p3) step
110         p2_dict = {3: ProcessStepsNode(p3, None, False, {})}
111         p1_dict[1].steps[3] = p2_dict[3]
112         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
113         # add step of process p2 as explicit sub-step to p1's second sub-step
114         s_p2_to_p1_first = ProcessStep(None, p1.id_, p2.id_, s_p3_to_p1.id_)
115         steps_p1 += [s_p2_to_p1_first]
116         p1.set_steps(self.db_conn, steps_p1)
117         seen_3 = ProcessStepsNode(p3, None, False, {}, False)
118         p1_dict[1].steps[3].seen = True
119         p1_dict[2].steps[4] = ProcessStepsNode(p2, s_p3_to_p1.id_, True,
120                                                {3: seen_3})
121         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
122         # add step of process p3 as explicit sub-step to non-existing p1
123         # sub-step (of id=999), expect it to become another p1 top-level step
124         s_p3_to_p1_999 = ProcessStep(None, p1.id_, p3.id_, 999)
125         steps_p1 += [s_p3_to_p1_999]
126         p1.set_steps(self.db_conn, steps_p1)
127         p1_dict[5] = ProcessStepsNode(p3, None, True, {})
128         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
129         # add step of process p3 as explicit sub-step to p1's implicit p3
130         # sub-step, expect it to become another p1 top-level step
131         s_p3_to_p1_impl_p3 = ProcessStep(None, p1.id_, p3.id_, s_p3_to_p2.id_)
132         steps_p1 += [s_p3_to_p1_impl_p3]
133         p1.set_steps(self.db_conn, steps_p1)
134         p1_dict[6] = ProcessStepsNode(p3, None, True, {})
135         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
136         self.assertEqual(p1.used_as_step_by(self.db_conn), [])
137         self.assertEqual(p2.used_as_step_by(self.db_conn), [p1])
138         self.assertEqual(p3.used_as_step_by(self.db_conn), [p1, p2])
139         # # add step of process p3 as explicit sub-step to p1's first sub-step,
140         # # expect it to eliminate implicit p3 sub-step
141         # s_p3_to_p1_first_explicit = ProcessStep(None, p1.id_, p3.id_,
142         #                                         s_p2_to_p1.id_)
143         # p1_dict[1].steps = {7: ProcessStepsNode(p3, 1, True, {})}
144         # p1_dict[2].steps[4].steps[3].seen = False
145         # steps_p1 += [s_p3_to_p1_first_explicit]
146         # p1.set_steps(self.db_conn, steps_p1)
147         # self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
148         # ensure implicit steps non-top explicit steps are shown
149         s_p3_to_p2_first = ProcessStep(None, p2.id_, p3.id_, s_p3_to_p2.id_)
150         steps_p2 += [s_p3_to_p2_first]
151         p2.set_steps(self.db_conn, steps_p2)
152         p1_dict[1].steps[3].steps[7] = ProcessStepsNode(p3, 3, False, {}, True)
153         p1_dict[2].steps[4].steps[3].steps[7] = ProcessStepsNode(p3, 3, False,
154                                                                  {}, False)
155         self.assertEqual(p1.get_steps(self.db_conn, None), p1_dict)
156         # ensure suppressed step nodes are hidden
157         assert isinstance(s_p3_to_p2.id_, int)
158         p1.set_step_suppressions(self.db_conn, [s_p3_to_p2.id_])
159         p1_dict[1].steps[3].steps = {}
160         p1_dict[1].steps[3].is_suppressed = True
161         p1_dict[2].steps[4].steps[3].steps = {}
162         p1_dict[2].steps[4].steps[3].is_suppressed = True
163         self.assertEqual(p1.get_steps(self.db_conn), p1_dict)
164
165     def test_Process_conditions(self) -> None:
166         """Test setting Process.conditions/enables/disables."""
167         p = Process(None)
168         p.save(self.db_conn)
169         for target in ('conditions', 'enables', 'disables'):
170             method = getattr(p, f'set_{target}')
171             c1, c2 = Condition(None), Condition(None)
172             c1.save(self.db_conn)
173             c2.save(self.db_conn)
174             assert isinstance(c1.id_, int)
175             assert isinstance(c2.id_, int)
176             method(self.db_conn, [])
177             self.assertEqual(getattr(p, target), [])
178             method(self.db_conn, [c1.id_])
179             self.assertEqual(getattr(p, target), [c1])
180             method(self.db_conn, [c2.id_])
181             self.assertEqual(getattr(p, target), [c2])
182             method(self.db_conn, [c1.id_, c2.id_])
183             self.assertEqual(getattr(p, target), [c1, c2])
184
185     def test_Process_by_id(self) -> None:
186         """Test .by_id(), including creation"""
187         self.check_by_id()
188
189     def test_Process_all(self) -> None:
190         """Test .all()."""
191         self.check_all()
192
193     def test_Process_singularity(self) -> None:
194         """Test pointers made for single object keep pointing to it."""
195         self.check_singularity('conditions', [Condition(None)])
196
197     def test_Process_versioned_attributes_singularity(self) -> None:
198         """Test behavior of VersionedAttributes on saving (with .title)."""
199         self.check_versioned_singularity()
200
201     def test_Process_removal(self) -> None:
202         """Test removal of Processes and ProcessSteps."""
203         self.check_remove()
204         p1, p2, p3 = self.three_processes()
205         assert isinstance(p1.id_, int)
206         assert isinstance(p2.id_, int)
207         assert isinstance(p3.id_, int)
208         step = ProcessStep(None, p2.id_, p1.id_, None)
209         p2.set_steps(self.db_conn, [step])
210         step_id = step.id_
211         with self.assertRaises(HandledException):
212             p1.remove(self.db_conn)
213         p2.set_steps(self.db_conn, [])
214         with self.assertRaises(NotFoundException):
215             ProcessStep.by_id(self.db_conn, step_id)
216         p1.remove(self.db_conn)
217         step = ProcessStep(None, p2.id_, p3.id_, None)
218         step_id = step.id_
219         p2.set_steps(self.db_conn, [step])
220         p2.remove(self.db_conn)
221         with self.assertRaises(NotFoundException):
222             ProcessStep.by_id(self.db_conn, step_id)
223         todo = Todo(None, p3, False, '2024-01-01')
224         todo.save(self.db_conn)
225         with self.assertRaises(HandledException):
226             p3.remove(self.db_conn)
227         todo.remove(self.db_conn)
228         p3.remove(self.db_conn)
229
230
231 class TestsWithDBForProcessStep(TestCaseWithDB):
232     """Module tests requiring DB setup."""
233     checked_class = ProcessStep
234     default_init_kwargs = {'owner_id': 2, 'step_process_id': 3,
235                            'parent_step_id': 4}
236
237     def setUp(self) -> None:
238         super().setUp()
239         p = Process(1)
240         p.save(self.db_conn)
241         p = Process(2)
242         p.save(self.db_conn)
243
244     def test_saving_and_caching(self) -> None:
245         """Test storage and initialization of instances and attributes."""
246         self.check_saving_and_caching(id_=1, **self.default_init_kwargs)
247
248     def test_ProcessStep_remove(self) -> None:
249         """Test .remove and unsetting of owner's .explicit_steps entry."""
250         p1 = Process(None)
251         p2 = Process(None)
252         p1.save(self.db_conn)
253         p2.save(self.db_conn)
254         assert isinstance(p1.id_, int)
255         assert isinstance(p2.id_, int)
256         step = ProcessStep(None, p1.id_, p2.id_, None)
257         p1.set_steps(self.db_conn, [step])
258         step.remove(self.db_conn)
259         self.assertEqual(p1.explicit_steps, [])
260         self.check_storage([])
261
262
263 class TestsWithServer(TestCaseWithServer):
264     """Module tests against our HTTP server/handler (and database)."""
265
266     def test_do_POST_process(self) -> None:
267         """Test POST /process and its effect on the database."""
268         self.assertEqual(0, len(Process.all(self.db_conn)))
269         form_data = self.post_process()
270         self.assertEqual(1, len(Process.all(self.db_conn)))
271         self.check_post(form_data, '/process?id=FOO', 400)
272         self.check_post(form_data | {'effort': 'foo'}, '/process?id=', 400)
273         self.check_post({}, '/process?id=', 400)
274         self.check_post({'title': '', 'description': ''}, '/process?id=', 400)
275         self.check_post({'title': '', 'effort': 1.1}, '/process?id=', 400)
276         self.check_post({'description': '', 'effort': 1.0},
277                         '/process?id=', 400)
278         self.assertEqual(1, len(Process.all(self.db_conn)))
279         form_data = {'title': 'foo', 'description': 'foo', 'effort': 1.0}
280         self.post_process(2, form_data | {'condition': []})
281         self.check_post(form_data | {'condition': [1]}, '/process?id=', 404)
282         self.check_post({'title': 'foo', 'description': 'foo',
283                          'is_active': False},
284                         '/condition', 302, '/condition?id=1')
285         self.post_process(3, form_data | {'condition': [1]})
286         self.post_process(4, form_data | {'disables': [1]})
287         self.post_process(5, form_data | {'enables': [1]})
288         form_data['delete'] = ''
289         self.check_post(form_data, '/process?id=', 404)
290         self.check_post(form_data, '/process?id=6', 404)
291         self.check_post(form_data, '/process?id=5', 302, '/processes')
292
293     def test_do_POST_process_steps(self) -> None:
294         """Test behavior of ProcessStep posting."""
295         # pylint: disable=too-many-statements
296         form_data_1 = self.post_process(1)
297         self.post_process(2)
298         self.post_process(3)
299         # post first (top-level) step of process 2 to process 1
300         form_data_1['new_top_step'] = [2]
301         self.post_process(1, form_data_1)
302         retrieved_process = Process.by_id(self.db_conn, 1)
303         self.assertEqual(len(retrieved_process.explicit_steps), 1)
304         retrieved_step = retrieved_process.explicit_steps[0]
305         retrieved_step_id = retrieved_step.id_
306         self.assertEqual(retrieved_step.step_process_id, 2)
307         self.assertEqual(retrieved_step.owner_id, 1)
308         self.assertEqual(retrieved_step.parent_step_id, None)
309         # post empty steps list to process, expect clean slate, and old step to
310         # completely disappear
311         form_data_1['new_top_step'] = []
312         self.post_process(1, form_data_1)
313         retrieved_process = Process.by_id(self.db_conn, 1)
314         self.assertEqual(retrieved_process.explicit_steps, [])
315         with self.assertRaises(NotFoundException):
316             ProcessStep.by_id(self.db_conn, retrieved_step_id)
317         # post new first (top_level) step of process 3 to process 1
318         form_data_1['new_top_step'] = [3]
319         self.post_process(1, form_data_1)
320         retrieved_process = Process.by_id(self.db_conn, 1)
321         retrieved_step = retrieved_process.explicit_steps[0]
322         self.assertEqual(retrieved_step.step_process_id, 3)
323         self.assertEqual(retrieved_step.owner_id, 1)
324         self.assertEqual(retrieved_step.parent_step_id, None)
325         # post to process steps list without keeps, expect clean slate
326         form_data_1['new_top_step'] = []
327         form_data_1['steps'] = [retrieved_step.id_]
328         self.post_process(1, form_data_1)
329         retrieved_process = Process.by_id(self.db_conn, 1)
330         self.assertEqual(retrieved_process.explicit_steps, [])
331         # post to process empty steps list but keep, expect 400
332         form_data_1['steps'] = []
333         form_data_1['keep_step'] = [retrieved_step_id]
334         self.check_post(form_data_1, '/process?id=1', 400, '/process?id=1')
335         # post to process steps list with keep on non-created step, expect 400
336         form_data_1['steps'] = [retrieved_step_id]
337         form_data_1['keep_step'] = [retrieved_step_id]
338         self.check_post(form_data_1, '/process?id=1', 400, '/process?id=1')
339         # post to process steps list with keep and process ID, expect 200
340         form_data_1[f'step_{retrieved_step_id}_process_id'] = [2]
341         self.post_process(1, form_data_1)
342         retrieved_process = Process.by_id(self.db_conn, 1)
343         self.assertEqual(len(retrieved_process.explicit_steps), 1)
344         retrieved_step = retrieved_process.explicit_steps[0]
345         self.assertEqual(retrieved_step.step_process_id, 2)
346         self.assertEqual(retrieved_step.owner_id, 1)
347         self.assertEqual(retrieved_step.parent_step_id, None)
348         # post nonsense, expect 400 and preservation of previous state
349         form_data_1['steps'] = ['foo']
350         form_data_1['keep_step'] = []
351         self.check_post(form_data_1, '/process?id=1', 400, '/process?id=1')
352         retrieved_process = Process.by_id(self.db_conn, 1)
353         self.assertEqual(len(retrieved_process.explicit_steps), 1)
354         retrieved_step = retrieved_process.explicit_steps[0]
355         self.assertEqual(retrieved_step.step_process_id, 2)
356         self.assertEqual(retrieved_step.owner_id, 1)
357         self.assertEqual(retrieved_step.parent_step_id, None)
358         # post to process steps list with keep and process ID, expect 200
359         form_data_1['new_top_step'] = [3]
360         form_data_1['steps'] = [retrieved_step.id_]
361         form_data_1['keep_step'] = [retrieved_step.id_]
362         self.post_process(1, form_data_1)
363         retrieved_process = Process.by_id(self.db_conn, 1)
364         self.assertEqual(len(retrieved_process.explicit_steps), 2)
365         retrieved_step_0 = retrieved_process.explicit_steps[0]
366         self.assertEqual(retrieved_step_0.step_process_id, 3)
367         self.assertEqual(retrieved_step_0.owner_id, 1)
368         self.assertEqual(retrieved_step_0.parent_step_id, None)
369         retrieved_step_1 = retrieved_process.explicit_steps[1]
370         self.assertEqual(retrieved_step_1.step_process_id, 2)
371         self.assertEqual(retrieved_step_1.owner_id, 1)
372         self.assertEqual(retrieved_step_1.parent_step_id, None)
373         # post to process steps list with keeps etc., but trigger recursion
374         form_data_1['new_top_step'] = []
375         form_data_1['steps'] = [retrieved_step_0.id_, retrieved_step_1.id_]
376         form_data_1['keep_step'] = [retrieved_step_0.id_, retrieved_step_1.id_]
377         form_data_1[f'step_{retrieved_step_0.id_}_process_id'] = [2]
378         form_data_1[f'step_{retrieved_step_1.id_}_process_id'] = [1]
379         self.check_post(form_data_1, '/process?id=1', 400, '/process?id=1')
380         # check previous status preserved despite failed steps setting
381         retrieved_process = Process.by_id(self.db_conn, 1)
382         self.assertEqual(len(retrieved_process.explicit_steps), 2)
383         retrieved_step_0 = retrieved_process.explicit_steps[0]
384         self.assertEqual(retrieved_step_0.step_process_id, 2)
385         self.assertEqual(retrieved_step_0.owner_id, 1)
386         self.assertEqual(retrieved_step_0.parent_step_id, None)
387         retrieved_step_1 = retrieved_process.explicit_steps[1]
388         self.assertEqual(retrieved_step_1.step_process_id, 3)
389         self.assertEqual(retrieved_step_1.owner_id, 1)
390         self.assertEqual(retrieved_step_1.parent_step_id, None)
391         # post sub-step to step
392         form_data_1[f'step_{retrieved_step_0.id_}_process_id'] = [3]
393         form_data_1[f'new_step_to_{retrieved_step_0.id_}'] = [3]
394         self.post_process(1, form_data_1)
395         retrieved_process = Process.by_id(self.db_conn, 1)
396         self.assertEqual(len(retrieved_process.explicit_steps), 3)
397         retrieved_step_0 = retrieved_process.explicit_steps[0]
398         self.assertEqual(retrieved_step_0.step_process_id, 2)
399         self.assertEqual(retrieved_step_0.owner_id, 1)
400         self.assertEqual(retrieved_step_0.parent_step_id, None)
401         retrieved_step_1 = retrieved_process.explicit_steps[1]
402         self.assertEqual(retrieved_step_1.step_process_id, 3)
403         self.assertEqual(retrieved_step_1.owner_id, 1)
404         self.assertEqual(retrieved_step_1.parent_step_id, None)
405         retrieved_step_2 = retrieved_process.explicit_steps[2]
406         self.assertEqual(retrieved_step_2.step_process_id, 3)
407         self.assertEqual(retrieved_step_2.owner_id, 1)
408         self.assertEqual(retrieved_step_2.parent_step_id, retrieved_step_1.id_)
409
410     def test_do_GET(self) -> None:
411         """Test /process and /processes response codes."""
412         self.check_get_defaults('/process')
413         self.check_get('/processes', 200)