home · contact · privacy
Re-organize and extend/improve POST/GET /day tests.
[plomtask] / tests / days.py
1 """Test Days module."""
2 from unittest import TestCase
3 from datetime import datetime
4 from typing import Callable
5 from tests.utils import TestCaseWithDB, TestCaseWithServer
6 from plomtask.dating import date_in_n_days
7 from plomtask.days import Day
8
9
10 class TestsSansDB(TestCase):
11     """Days module tests not requiring DB setup."""
12     legal_ids = ['2024-01-01']
13     illegal_ids = ['foo', '2024-02-30', '2024-02-01 23:00:00']
14
15     def test_Day_datetime_weekday_neighbor_dates(self) -> None:
16         """Test Day's date parsing."""
17         self.assertEqual(datetime(2024, 5, 1), Day('2024-05-01').datetime)
18         self.assertEqual('Sunday', Day('2024-03-17').weekday)
19         self.assertEqual('March', Day('2024-03-17').month_name)
20         self.assertEqual('2023-12-31', Day('2024-01-01').prev_date)
21         self.assertEqual('2023-03-01', Day('2023-02-28').next_date)
22
23     def test_Day_sorting(self) -> None:
24         """Test sorting by .__lt__ and Day.__eq__."""
25         day1 = Day('2024-01-01')
26         day2 = Day('2024-01-02')
27         day3 = Day('2024-01-03')
28         days = [day3, day1, day2]
29         self.assertEqual(sorted(days), [day1, day2, day3])
30
31
32 class TestsWithDB(TestCaseWithDB):
33     """Tests requiring DB, but not server setup."""
34     checked_class = Day
35     default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
36
37     def test_Day_by_date_range_filled(self) -> None:
38         """Test Day.by_date_range_filled."""
39         date1, date2, date3 = self.default_ids
40         day1 = Day(date1)
41         day2 = Day(date2)
42         day3 = Day(date3)
43         for day in [day1, day2, day3]:
44             day.save(self.db_conn)
45         # check date range includes limiter days
46         self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date3),
47                          [day1, day2, day3])
48         # check first date range value excludes what's earlier
49         self.assertEqual(Day.by_date_range_filled(self.db_conn, date2, date3),
50                          [day2, day3])
51         # check second date range value excludes what's later
52         self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date2),
53                          [day1, day2])
54         # check swapped (impossible) date range returns emptiness
55         self.assertEqual(Day.by_date_range_filled(self.db_conn, date3, date1),
56                          [])
57         # check fill_gaps= instantiates unsaved dates within date range
58         # (but does not store them)
59         day5 = Day('2024-01-05')
60         day6 = Day('2024-01-06')
61         day6.save(self.db_conn)
62         day7 = Day('2024-01-07')
63         self.assertEqual(Day.by_date_range_filled(self.db_conn,
64                                                   day5.date, day7.date),
65                          [day5, day6, day7])
66         self.check_identity_with_cache_and_db([day1, day2, day3, day6])
67         # check 'today' is interpreted as today's date
68         today = Day(date_in_n_days(0))
69         self.assertEqual(Day.by_date_range_filled(self.db_conn,
70                                                   'today', 'today'),
71                          [today])
72         prev_day = Day(date_in_n_days(-1))
73         next_day = Day(date_in_n_days(1))
74         self.assertEqual(Day.by_date_range_filled(self.db_conn,
75                                                   'yesterday', 'tomorrow'),
76                          [prev_day, today, next_day])
77
78
79 class TestsWithServer(TestCaseWithServer):
80     """Tests against our HTTP server/handler (and database)."""
81
82     @staticmethod
83     def todo_as_dict(id_: int = 1,
84                      process_id: int = 1,
85                      date: str = '2024-01-01',
86                      conditions: None | list[int] = None,
87                      disables: None | list[int] = None,
88                      blockers: None | list[int] = None,
89                      enables: None | list[int] = None
90                      ) -> dict[str, object]:
91         """Return JSON of Process to expect."""
92         # pylint: disable=too-many-arguments
93         d = {'id': id_,
94              'date': date,
95              'process_id': process_id,
96              'is_done': False,
97              'calendarize': False,
98              'comment': '',
99              'children': [],
100              'parents': [],
101              'effort': None,
102              'conditions': conditions if conditions else [],
103              'disables': disables if disables else [],
104              'blockers': blockers if blockers else [],
105              'enables': enables if enables else []}
106         return d
107
108     @staticmethod
109     def _todo_node_as_dict(todo_id: int) -> dict[str, object]:
110         """Return JSON of TodoNode to expect."""
111         return {'children': [], 'seen': False, 'todo': todo_id}
112
113     @classmethod
114     def GET_day_dict(cls, date: str) -> dict[str, object]:
115         """Return JSON of GET /day to expect."""
116         day: dict[str, object] = {'id': date, 'comment': '', 'todos': []}
117         d: dict[str, object] = {'day': date,
118                                 'top_nodes': [],
119                                 'make_type': '',
120                                 'enablers_for': {},
121                                 'disablers_for': {},
122                                 'conditions_present': [],
123                                 'processes': [],
124                                 '_library': {'Day': cls.as_refs([day])}}
125         return d
126
127     def _post_day(self, params: str = '',
128                   form_data: None | dict[str, object] = None,
129                   redir_to: str = '',
130                   status: int = 302,
131                   ) -> None:
132         """POST /day?{params} with form_data."""
133         if not form_data:
134             form_data = {'day_comment': '', 'make_type': ''}
135         target = f'/day?{params}'
136         if not redir_to:
137             redir_to = f'{target}&make_type={form_data["make_type"]}'
138         self.check_post(form_data, target, status, redir_to)
139
140     @staticmethod
141     def _post_batch(list_of_args: list[list[object]],
142                     names_of_simples: list[str],
143                     names_of_versioneds: list[str],
144                     f_as_dict: Callable[..., dict[str, object]],
145                     f_to_post: Callable[..., None | dict[str, object]]
146                     ) -> list[dict[str, object]]:
147         """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
148         expecteds = []
149         for args in list_of_args:
150             expecteds += [f_as_dict(*args)]
151         for expected in expecteds:
152             assert isinstance(expected['_versioned'], dict)
153             post = {}
154             for name in names_of_simples:
155                 post[name] = expected[name]
156             for name in names_of_versioneds:
157                 post[name] = expected['_versioned'][name][0]
158             f_to_post(expected['id'], post)
159         return expecteds
160
161     def test_do_GET_calendar(self) -> None:
162         """Test /calendar response codes, and / redirect."""
163         self.check_get('/calendar', 200)
164         self.check_get('/calendar?start=&end=', 200)
165         self.check_get('/calendar?start=today&end=today', 200)
166         self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
167         self.check_get('/calendar?start=foo', 400)
168
169     def test_fail_GET_day(self) -> None:
170         """Test malformed/illegal GET /day requests."""
171         self.check_get('/day?date=foo', 400)
172         self.check_get('/day?date=2024-02-30', 400)
173
174     def test_basic_GET_day(self) -> None:
175         """Test basic (no Processes/Conditions/Todos) GET /day basics."""
176         # check undefined day
177         date = date_in_n_days(0)
178         expected = self.GET_day_dict(date)
179         self.check_json_get('/day', expected)
180         # NB: GET ?date="today"/"yesterday"/"tomorrow" in test_basic_POST_day
181         # check 'make_type' GET parameter affects immediate reply, but …
182         date = '2024-01-01'
183         expected = self.GET_day_dict(date)
184         expected['make_type'] = 'bar'
185         self.check_json_get(f'/day?date={date}&make_type=bar', expected)
186         # … not any following, …
187         expected['make_type'] = ''
188         self.check_json_get(f'/day?date={date}', expected)
189         # … not even when part of a POST request
190         post: dict[str, object] = {'day_comment': '', 'make_type': 'foo'}
191         self._post_day(f'date={date}', post)
192         self.check_json_get(f'/day?date={date}', expected)
193
194     def test_fail_POST_day(self) -> None:
195         """Test malformed/illegal POST /day requests."""
196         # check payloads lacking minimum expecteds
197         url = '/day?date=2024-01-01'
198         self.check_post({}, url, 400)
199         self.check_post({'day_comment': ''}, url, 400)
200         self.check_post({'make_type': ''}, url, 400)
201         # to next check illegal new_todo values, we need an actual Process
202         self.post_process(1)
203         # check illegal new_todo values
204         post: dict[str, object]
205         post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
206         self.check_post(post, url, 400)
207         post['new_todo'] = [1, 2]  # no Process of .id_=2 exists
208         # to next check illegal old_todo inputs, we need to first post Todo
209         post['new_todo'] = [1]
210         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
211         # check illegal old_todo inputs (equal list lengths though)
212         post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
213                 'effort': [3.3], 'done': [], 'todo_id': [1]}
214         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
215         post['todo_id'] = [2]  # reference to non-existant Process
216         self.check_post(post, url, 404)
217         post['todo_id'] = ['a']
218         self.check_post(post, url, 400)
219         post['todo_id'] = [1]
220         post['done'] = ['foo']
221         self.check_post(post, url, 400)
222         post['done'] = [2]  # reference to non-posted todo_id
223         self.check_post(post, url, 400)
224         post['done'] = []
225         post['effort'] = ['foo']
226         self.check_post(post, url, 400)
227         post['effort'] = [None]
228         self.check_post(post, url, 400)
229         post['effort'] = [3.3]
230         # check illegal old_todo inputs: unequal list lengths
231         post['comment'] = []
232         self.check_post(post, url, 400)
233         post['comment'] = ['foo', 'foo']
234         self.check_post(post, url, 400)
235         post['comment'] = ['foo']
236         post['effort'] = []
237         self.check_post(post, url, 400)
238         post['effort'] = [3.3, 3.3]
239         self.check_post(post, url, 400)
240         post['effort'] = [3.3]
241         post['todo_id'] = [1, 1]
242         self.check_post(post, url, 400)
243         post['todo_id'] = [1]
244         # # check valid POST payload on bad paths
245         self.check_post(post, '/day', 400)
246         self.check_post(post, '/day?date=', 400)
247         self.check_post(post, '/day?date=foo', 400)
248
249     def test_basic_POST_day(self) -> None:
250         """Test basic (no Todos) POST /day.
251
252         Check POST (& GET!) requests properly parse 'today', 'tomorrow',
253         'yesterday', and actual date strings;
254         preserve 'make_type' setting in redirect even if nonsensical;
255         and store 'day_comment'
256         """
257         for name, dist, test_str in [('2024-01-01', None, 'a'),
258                                      ('today', 0, 'b'),
259                                      ('yesterday', -1, 'c'),
260                                      ('tomorrow', +1, 'd')]:
261             date = name if dist is None else date_in_n_days(dist)
262             post = {'day_comment': test_str, 'make_type': f'x:{test_str}'}
263             post_url = f'/day?date={name}'
264             redir_url = f'{post_url}&make_type={post["make_type"]}'
265             self.check_post(post, post_url, 302, redir_url)
266             expected = self.GET_day_dict(date)
267             assert isinstance(expected['_library'], dict)
268             expected['_library']['Day'][date]['comment'] = test_str
269             self.check_json_get(post_url, expected)
270
271     def test_GET_day_with_processes_and_todos(self) -> None:
272         """Test GET /day displaying Processes and Todos (no trees)."""
273         date = '2024-01-01'
274         # check Processes get displayed in ['processes'] and ['_library']
275         procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
276         procs_expected = self._post_batch(procs_data, [],
277                                           ['title', 'description', 'effort'],
278                                           self.proc_as_dict, self.post_process)
279         expected = self.GET_day_dict(date)
280         assert isinstance(expected['_library'], dict)
281         expected['processes'] = self.as_id_list(procs_expected)
282         expected['_library']['Process'] = self.as_refs(procs_expected)
283         self._post_day(f'date={date}')
284         self.check_json_get(f'/day?date={date}', expected)
285         # post Todos of either process and check their display
286         post_day: dict[str, object]
287         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
288         todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
289         expected['_library']['Todo'] = self.as_refs(todos)
290         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
291         nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
292         expected['top_nodes'] = nodes
293         self._post_day(f'date={date}', post_day)
294         self.check_json_get(f'/day?date={date}', expected)
295         # add a comment to one Todo and set the other's doneness and effort
296         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [],
297                     'todo_id': [1, 2], 'done': [2], 'comment': ['FOO', ''],
298                     'effort': [2.3, '']}
299         expected['_library']['Todo']['1']['comment'] = 'FOO'
300         expected['_library']['Todo']['1']['effort'] = 2.3
301         expected['_library']['Todo']['2']['is_done'] = True
302         self._post_day(f'date={date}', post_day)
303         self.check_json_get(f'/day?date={date}', expected)
304
305     def test_GET_day_with_conditions(self) -> None:
306         """Test GET /day displaying Conditions and their relations."""
307         date = '2024-01-01'
308         # add Process with Conditions and their Todos, check display
309         conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
310         conds_expected = self._post_batch(
311                 conds_data, ['is_active'], ['title', 'description'],
312                 self.cond_as_dict,
313                 lambda x, y: self.check_post(y, f'/condition?id={x}', 302))
314         cond_names = ['conditions', 'disables', 'blockers', 'enables']
315         procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
316                       [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
317         procs_expected = self._post_batch(procs_data, cond_names,
318                                           ['title', 'description', 'effort'],
319                                           self.proc_as_dict, self.post_process)
320         expected = self.GET_day_dict(date)
321         assert isinstance(expected['_library'], dict)
322         expected['processes'] = self.as_id_list(procs_expected)
323         expected['_library']['Process'] = self.as_refs(procs_expected)
324         expected['_library']['Condition'] = self.as_refs(conds_expected)
325         self._post_day(f'date={date}')
326         self.check_json_get(f'/day?date={date}', expected)
327         # add Todos in relation to Conditions, check consequences
328         post_day: dict[str, object]
329         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
330         todos = [self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
331                  self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
332         expected['_library']['Todo'] = self.as_refs(todos)
333         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
334         nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
335         expected['top_nodes'] = nodes
336         expected['disablers_for'] = {'1': [1], '2': [2]}
337         expected['enablers_for'] = {'1': [2], '2': [1]}
338         expected['conditions_present'] = self.as_id_list(conds_expected)
339         self._post_day(f'date={date}', post_day)
340         self.check_json_get(f'/day?date={date}', expected)