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