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