home · contact · privacy
Re-organize and extend 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     @staticmethod
114     def GET_day_dict(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]
118         d = {'day': date,
119              'top_nodes': [],
120              'make_type': '',
121              'enablers_for': {},
122              'disablers_for': {},
123              'conditions_present': [],
124              'processes': [],
125              '_library': {'Day': TestsWithServer.as_refs([day])}}
126         return d
127
128     def post_day(self, params: str = '',
129                  form_data: None | dict[str, object] = None,
130                  redir_to: str = '',
131                  status: int = 302,
132                  ) -> None:
133         """POST /day?{params} with form_data."""
134         if not form_data:
135             form_data = {'day_comment': '', 'make_type': ''}
136         target = f'/day?{params}'
137         if not redir_to:
138             redir_to = f'{target}&make_type={form_data["make_type"]}'
139         self.check_post(form_data, target, status, redir_to)
140
141     @staticmethod
142     def post_batch(list_of_args: list[list[object]],
143                    names_of_simples: list[str],
144                    names_of_versioneds: list[str],
145                    f_as_dict: Callable[..., dict[str, object]],
146                    f_to_post: Callable[..., None | dict[str, object]]
147                    ) -> list[dict[str, object]]:
148         """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
149         expecteds = []
150         for args in list_of_args:
151             expecteds += [f_as_dict(*args)]
152         for expected in expecteds:
153             assert isinstance(expected['_versioned'], dict)
154             post = {}
155             for name in names_of_simples:
156                 post[name] = expected[name]
157             for name in names_of_versioneds:
158                 post[name] = expected['_versioned'][name][0]
159             f_to_post(expected['id'], post)
160         return expecteds
161
162     def post_cond(self, id_: int, form_data: dict[str, object]) -> None:
163         """POST Condition of id_ with form_data."""
164         self.check_post(form_data, f'/condition?id={id_}', 302)
165
166     def test_do_GET_day_with_processes_and_todos(self) -> None:
167         """Test GET /day displaying Processes and Todos."""
168         date = '2024-01-01'
169         # check Processes get displayed in ['processes'] and ['_library']
170         procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
171         procs_expected = self.post_batch(procs_data, [],
172                                          ['title', 'description', 'effort'],
173                                          self.proc_as_dict, self.post_process)
174         expected = self.GET_day_dict(date)
175         assert isinstance(expected['_library'], dict)
176         expected['processes'] = self.as_id_list(procs_expected)
177         expected['_library']['Process'] = self.as_refs(procs_expected)
178         self.post_day(f'date={date}')
179         self.check_json_get(f'/day?date={date}', expected)
180         # post Todos of either process and check their display
181         post_day: dict[str, object]
182         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
183         todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
184         expected['_library']['Todo'] = self.as_refs(todos)
185         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
186         nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
187         expected['top_nodes'] = nodes
188         self.post_day(f'date={date}', post_day)
189         self.check_json_get(f'/day?date={date}', expected)
190         # add a comment to one Todo and set the other's doneness and effort
191         post_day['new_todo'] = []
192         post_day['todo_id'] = [1, 2]
193         post_day['done'] = [2]
194         post_day['comment'] = ['FOO', '']
195         post_day['effort'] = ['2.3', '']
196         expected['_library']['Todo']['1']['comment'] = 'FOO'
197         expected['_library']['Todo']['1']['effort'] = 2.3
198         expected['_library']['Todo']['2']['is_done'] = True
199         self.post_day(f'date={date}', post_day)
200         self.check_json_get(f'/day?date={date}', expected)
201
202     def test_do_GET_day_with_conditions(self) -> None:
203         """Test GET /day displaying Conditions and their relations."""
204         # add Process with Conditions and their Todos, check display
205         conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
206         conds_expected = self.post_batch(conds_data, ['is_active'],
207                                          ['title', 'description'],
208                                          self.cond_as_dict, self.post_cond)
209         cond_names = ['conditions', 'disables', 'blockers', 'enables']
210         procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
211                       [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
212         procs_expected = self.post_batch(procs_data, cond_names,
213                                          ['title', 'description', 'effort'],
214                                          self.proc_as_dict, self.post_process)
215         date = '2024-01-01'
216         expected = self.GET_day_dict(date)
217         assert isinstance(expected['_library'], dict)
218         expected['processes'] = self.as_id_list(procs_expected)
219         expected['_library']['Process'] = self.as_refs(procs_expected)
220         expected['_library']['Condition'] = self.as_refs(conds_expected)
221         self.post_day(f'date={date}')
222         self.check_json_get(f'/day?date={date}', expected)
223         # add Todos in relation to Conditions, check consequences
224         post_day: dict[str, object]
225         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
226         todos = [self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
227                  self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
228         expected['_library']['Todo'] = self.as_refs(todos)
229         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
230         nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
231         expected['top_nodes'] = nodes
232         expected['disablers_for'] = {'1': [1], '2': [2]}
233         expected['enablers_for'] = {'1': [2], '2': [1]}
234         expected['conditions_present'] = self.as_id_list(conds_expected)
235         self.post_day(f'date={date}', post_day)
236         self.check_json_get(f'/day?date={date}', expected)
237
238     def test_do_GET_calendar(self) -> None:
239         """Test /calendar response codes, and / redirect."""
240         self.check_get('/calendar', 200)
241         self.check_get('/calendar?start=&end=', 200)
242         self.check_get('/calendar?start=today&end=today', 200)
243         self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
244         self.check_get('/calendar?start=foo', 400)
245
246     def test_fail_GET_day(self) -> None:
247         """Test malformed/illegal GET /day requests."""
248         self.check_get('/day?date=foo', 400)
249         self.check_get('/day?date=2024-02-30', 400)
250
251     def test_basic_GET_day(self) -> None:
252         """Test basic (no Processes/Conditions/Todos) GET /day basics."""
253         # check undefined day
254         date = date_in_n_days(0)
255         expected = self.GET_day_dict(date)
256         self.check_json_get('/day', expected)
257         # NB: GET ?date="today"/"yesterday"/"tomorrow" in test_basic_POST_day
258         # check 'make_type' GET parameter affects immediate reply, but …
259         date = '2024-01-01'
260         expected = self.GET_day_dict(date)
261         expected['make_type'] = 'bar'
262         self.check_json_get(f'/day?date={date}&make_type=bar', expected)
263         # … not any following, …
264         expected['make_type'] = ''
265         self.check_json_get(f'/day?date={date}', expected)
266         # … not even when part of a POST request
267         post: dict[str, object] = {'day_comment': '', 'make_type': 'foo'}
268         self.post_day(f'date={date}', post)
269         self.check_json_get(f'/day?date={date}', expected)
270
271     def test_fail_POST_day(self) -> None:
272         """Test malformed/illegal POST /day requests."""
273         # check payloads lacking minimum expecteds
274         url = '/day?date=2024-01-01'
275         self.check_post({}, url, 400)
276         self.check_post({'day_comment': ''}, url, 400)
277         self.check_post({'make_type': ''}, url, 400)
278         # to next check illegal new_todo values, we need an actual Process
279         self.post_process(1)
280         # check illegal new_todo values
281         post: dict[str, object]
282         post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
283         self.check_post(post, url, 400)
284         post['new_todo'] = [1, 2]  # no Process of .id_=2 exists
285         # to next check illegal old_todo inputs, we need to first post Todo
286         post['new_todo'] = [1]
287         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
288         # check illegal old_todo inputs (equal list lengths though)
289         post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
290                 'effort': [3.3], 'done': [], 'todo_id': [1]}
291         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
292         post['todo_id'] = [2]  # reference to non-existant Process
293         self.check_post(post, url, 404)
294         post['todo_id'] = ['a']
295         self.check_post(post, url, 400)
296         post['todo_id'] = [1]
297         post['done'] = ['foo']
298         self.check_post(post, url, 400)
299         post['done'] = [2]  # reference to non-posted todo_id
300         self.check_post(post, url, 400)
301         post['done'] = []
302         post['effort'] = ['foo']
303         self.check_post(post, url, 400)
304         post['effort'] = [None]
305         self.check_post(post, url, 400)
306         post['effort'] = [3.3]
307         # check illegal old_todo inputs: unequal list lengths
308         post['comment'] = []
309         self.check_post(post, url, 400)
310         post['comment'] = ['foo', 'foo']
311         self.check_post(post, url, 400)
312         post['comment'] = ['foo']
313         post['effort'] = []
314         self.check_post(post, url, 400)
315         post['effort'] = [3.3, 3.3]
316         self.check_post(post, url, 400)
317         post['effort'] = [3.3]
318         post['todo_id'] = [1, 1]
319         self.check_post(post, url, 400)
320         post['todo_id'] = [1]
321         # # check valid POST payload on bad paths
322         self.check_post(post, '/day', 400)
323         self.check_post(post, '/day?date=', 400)
324         self.check_post(post, '/day?date=foo', 400)
325
326     def test_basic_POST_day(self) -> None:
327         """Test basic (no Todos) POST /day.
328
329         Check POST (& GET!) requests properly parse 'today', 'tomorrow',
330         'yesterday', and actual date strings;
331         preserve 'make_type' setting in redirect even if nonsensical;
332         and store 'day_comment'
333         """
334         for name, dist, test_str in [('2024-01-01', None, 'a'),
335                                      ('today', 0, 'b'),
336                                      ('yesterday', -1, 'c'),
337                                      ('tomorrow', +1, 'd')]:
338             date = name if dist is None else date_in_n_days(dist)
339             post = {'day_comment': test_str, 'make_type': f'x:{test_str}'}
340             post_url = f'/day?date={name}'
341             redir_url = f'{post_url}&make_type={post["make_type"]}'
342             self.check_post(post, post_url, 302, redir_url)
343             expected = self.GET_day_dict(date)
344             assert isinstance(expected['_library'], dict)
345             expected['_library']['Day'][date]['comment'] = test_str
346             self.check_json_get(post_url, expected)