home · contact · privacy
7fdd4d44823d5b80b5a788267f82d26a8c53fa12
[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         titles = titles if titles else []
58         descriptions = descriptions if descriptions else []
59         assert isinstance(d['_versioned'], dict)
60         for i, title in enumerate(titles):
61             d['_versioned']['title'][i] = title
62         for i, description in enumerate(descriptions):
63             d['_versioned']['description'][i] = description
64         return d
65
66     def test_do_POST_condition(self) -> None:
67         """Test POST /condition and its effect on GET /condition[s]."""
68         # check empty POST fails
69         self.check_post({}, '/condition', 400)
70         # test valid POST's effect on …
71         post = {'title': 'foo', 'description': 'oof', 'is_active': False}
72         self.check_post(post, '/condition', 302, '/condition?id=1')
73         # … single /condition
74         cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
75         expected_single: dict[str, object]
76         expected_single = {'is_new': False,
77                            'enabled_processes': [],
78                            'disabled_processes': [],
79                            'enabling_processes': [],
80                            'disabling_processes': [],
81                            'condition': cond['id'],
82                            '_library': {'Condition': self.as_refs([cond])}}
83         self.check_json_get('/condition?id=1', expected_single)
84         # … full /conditions
85         expected_all: dict[str, object]
86         expected_all = {'conditions': self.as_id_list([cond]),
87                         'sort_by': 'title', 'pattern': '',
88                         '_library': {'Condition': self.as_refs([cond])}}
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(cond['_versioned'], dict)
97         cond['_versioned']['title'][1] = 'bar'
98         cond['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         assert isinstance(expected_single['_library'], dict)
104         assert isinstance(expected_single['_library']['Condition'], dict)
105         expected_single['_library']['Condition'] = self.as_refs([cond])
106         self.check_json_get('/condition?id=1', expected_single)
107         # … full /conditions
108         expected_all['conditions'] = []
109         expected_all['_library'] = {}
110         self.check_json_get('/conditions', expected_all)
111
112     def test_do_GET_condition(self) -> None:
113         """More GET /condition testing, especially for Process relations."""
114         # check expected default status codes
115         self.check_get_defaults('/condition')
116         # check display of process relations
117         form_data = {'title': 'foo', 'description': 'oof', 'is_active': False}
118         self.check_post(form_data, '/condition', 302, '/condition?id=1')
119         proc_1_post = {'title': 'A', 'description': '', 'effort': 1.0,
120                        'condition': [1], 'disables': [1]}
121         self.post_process(1, proc_1_post)
122         proc_2_post = {'title': 'B', 'description': '', 'effort': 1.0,
123                        'enables': [1], 'blocker': [1]}
124         self.post_process(2, proc_2_post)
125         cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
126         proc_1 = self.proc_as_dict(conditions=[cond], disables=[cond])
127         proc_2 = self.proc_as_dict(2, 'B', blockers=[cond], enables=[cond])
128         expected = {'is_new': False,
129                     'enabled_processes': self.as_id_list([proc_1]),
130                     'disabled_processes': self.as_id_list([proc_2]),
131                     'enabling_processes': self.as_id_list([proc_2]),
132                     'disabling_processes': self.as_id_list([proc_1]),
133                     'condition': cond['id'],
134                     '_library': {'Condition': self.as_refs([cond]),
135                                  'Process': self.as_refs([proc_1, proc_2])}}
136         self.check_json_get('/condition?id=1', expected)
137
138     def test_do_GET_conditions(self) -> None:
139         """Test GET /conditions."""
140         # test empty result on empty DB, default-settings on empty params
141         expected_json: dict[str, object] = {'conditions': [],
142                                             'sort_by': 'title',
143                                             'pattern': '',
144                                             '_library': {}}
145         self.check_json_get('/conditions', expected_json)
146         # test on meaningless non-empty params (incl. entirely un-used key)
147         expected_json = {'conditions': [],
148                          'sort_by': 'title',  # nonsense "foo" defaulting
149                          'pattern': 'bar',  # preserved despite zero effect
150                          '_library': {}}
151         self.check_json_get('/conditions?sort_by=foo&pattern=bar&foo=x',
152                             expected_json)
153         # test non-empty result, automatic (positive) sorting by title
154         post_1 = {'title': 'foo', 'description': 'oof', 'is_active': False}
155         self.check_post(post_1, '/condition', 302, '/condition?id=1')
156         post_2 = {'title': 'bar', 'description': 'rab', 'is_active': False}
157         self.check_post(post_2, '/condition', 302, '/condition?id=2')
158         post_3 = {'title': 'baz', 'description': 'zab', 'is_active': True}
159         self.check_post(post_3, '/condition', 302, '/condition?id=3')
160         cond_1 = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
161         cond_2 = self.cond_as_dict(2, titles=['bar'], descriptions=['rab'])
162         cond_3 = self.cond_as_dict(3, True, ['baz'], ['zab'])
163         cons = [cond_2, cond_3, cond_1]
164         expected_json = {'conditions': self.as_id_list(cons),
165                          'sort_by': 'title',
166                          'pattern': '',
167                          '_library': {'Condition': self.as_refs(cons)}}
168         self.check_json_get('/conditions', expected_json)
169         # test other sortings
170         # (NB: by .is_active has two items of =False, their order currently
171         # is not explicitly made predictable, so mail fail until we do)
172         expected_json['conditions'] = self.as_id_list([cond_1, cond_3, cond_2])
173         expected_json['sort_by'] = '-title'
174         self.check_json_get('/conditions?sort_by=-title', expected_json)
175         expected_json['conditions'] = self.as_id_list([cond_1, cond_2, cond_3])
176         expected_json['sort_by'] = 'is_active'
177         self.check_json_get('/conditions?sort_by=is_active', expected_json)
178         expected_json['conditions'] = self.as_id_list([cond_3, cond_1, cond_2])
179         expected_json['sort_by'] = '-is_active'
180         self.check_json_get('/conditions?sort_by=-is_active', expected_json)
181         # test pattern matching on title
182         cons = [cond_2, cond_3]
183         expected_json = {'conditions': self.as_id_list(cons),
184                          'sort_by': 'title', 'pattern': 'ba',
185                          '_library': {'Condition': self.as_refs(cons)}}
186         self.check_json_get('/conditions?pattern=ba', expected_json)
187         # test pattern matching on description
188         expected_json['conditions'] = self.as_id_list([cond_1])
189         assert isinstance(expected_json['_library'], dict)
190         expected_json['_library']['Condition'] = self.as_refs([cond_1])
191         expected_json['pattern'] = 'oo'
192         self.check_json_get('/conditions?pattern=oo', expected_json)