home · contact · privacy
Minor refactoring.
[plomtask] / tests / days.py
1 """Test Days module."""
2 from datetime import datetime, timedelta
3 from typing import Callable
4 from tests.utils import TestCaseSansDB, TestCaseWithDB, TestCaseWithServer
5 from plomtask.dating import date_in_n_days, DATE_FORMAT
6 from plomtask.days import Day
7
8
9 class TestsSansDB(TestCaseSansDB):
10     """Days module tests not requiring DB setup."""
11     checked_class = Day
12     legal_ids = ['2024-01-01', '2024-02-29']
13     illegal_ids = ['foo', '2023-02-29', '2024-02-30', '2024-02-01 23:00:00']
14
15     def test_date_in_n_days(self) -> None:
16         """Test dating.date_in_n_days, as we rely on it in later tests."""
17         for n in [-100, -2, -1, 0, 1, 2, 1000]:
18             date = datetime.now() + timedelta(days=n)
19             self.assertEqual(date_in_n_days(n), date.strftime(DATE_FORMAT))
20
21     def test_Day_datetime_weekday_neighbor_dates(self) -> None:
22         """Test Day's date parsing and neighbourhood resolution."""
23         self.assertEqual(datetime(2024, 5, 1), Day('2024-05-01').datetime)
24         self.assertEqual('Sunday', Day('2024-03-17').weekday)
25         self.assertEqual('March', Day('2024-03-17').month_name)
26         self.assertEqual('2023-12-31', Day('2024-01-01').prev_date)
27         self.assertEqual('2023-03-01', Day('2023-02-28').next_date)
28
29
30 class TestsWithDB(TestCaseWithDB):
31     """Tests requiring DB, but not server setup."""
32     checked_class = Day
33     default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
34
35     def test_Day_by_date_range_with_limits(self) -> None:
36         """Test .by_date_range_with_limits."""
37         self.check_by_date_range_with_limits('id', set_id_field=False)
38
39     def test_Day_with_filled_gaps(self) -> None:
40         """Test .with_filled_gaps."""
41
42         def test(range_indexes: tuple[int, int], indexes_to_provide: list[int]
43                  ) -> None:
44             start_i, end_i = range_indexes
45             days_provided = []
46             days_expected = days_sans_comment[:]
47             for i in indexes_to_provide:
48                 day_with_comment = days_with_comment[i]
49                 days_provided += [day_with_comment]
50                 days_expected[i] = day_with_comment
51             days_expected = days_expected[start_i:end_i+1]
52             start, end = dates[start_i], dates[end_i]
53             days_result = self.checked_class.with_filled_gaps(days_provided,
54                                                               start, end)
55             self.assertEqual(days_result, days_expected)
56
57         # for provided Days we use those from days_with_comment, to identify
58         # them against same-dated mere filler Days by their lack of comment
59         # (identity with Day at the respective position in days_sans_comment)
60         dates = [f'2024-02-0{n+1}' for n in range(9)]
61         days_with_comment = [Day(date, comment=date[-1:]) for date in dates]
62         days_sans_comment = [Day(date, comment='') for date in dates]
63         # check provided Days recognizable in (full-range) interval
64         test((0, 8), [0, 4, 8])
65         # check limited range, but limiting Days provided
66         test((2, 6), [2, 5, 6])
67         # check Days within range but beyond provided Days also filled in
68         test((1, 7), [2, 5])
69         # check provided Days beyond range ignored
70         test((3, 5), [1, 2, 4, 6, 7])
71         # check inversion of start_date and end_date returns empty list
72         test((5, 3), [2, 4, 6])
73         # check empty provision still creates filler elements in interval
74         test((3, 5), [])
75         # check single-element selection creating only filler beyond provided
76         test((1, 1), [2, 4, 6])
77         # check (un-saved) filler Days don't show up in cache or DB
78         # dates = [f'2024-02-0{n}' for n in range(1, 6)]
79         day = Day(dates[3])
80         day.save(self.db_conn)
81         self.checked_class.with_filled_gaps([day], dates[0], dates[-1])
82         self.check_identity_with_cache_and_db([day])
83         # check 'today', 'yesterday', 'tomorrow' are interpreted
84         yesterday = Day('yesterday')
85         tomorrow = Day('tomorrow')
86         today = Day('today')
87         result = self.checked_class.with_filled_gaps([today], 'yesterday',
88                                                      'tomorrow')
89         self.assertEqual(result, [yesterday, today, tomorrow])
90
91
92 class TestsWithServer(TestCaseWithServer):
93     """Tests against our HTTP server/handler (and database)."""
94
95     @classmethod
96     def GET_day_dict(cls, date: str) -> dict[str, object]:
97         """Return JSON of GET /day to expect."""
98         # day: dict[str, object] = {'id': date, 'comment': '', 'todos': []}
99         day = cls._day_as_dict(date)
100         d: dict[str, object] = {'day': date,
101                                 'top_nodes': [],
102                                 'make_type': '',
103                                 'enablers_for': {},
104                                 'disablers_for': {},
105                                 'conditions_present': [],
106                                 'processes': [],
107                                 '_library': {'Day': cls.as_refs([day])}}
108         return d
109
110     @classmethod
111     def GET_calendar_dict(cls, start: int, end: int) -> dict[str, object]:
112         """Return JSON of GET /calendar to expect.
113
114         NB: the date string list to key 'days' implies/expects a continuous (=
115         gaps filled) alphabetical order of dates by virtue of range(start,
116         end+1) and date_in_n_days tested in TestsSansDB.test_date_in_n_days.
117         """
118         today_date = date_in_n_days(0)
119         start_date = date_in_n_days(start)
120         end_date = date_in_n_days(end)
121         dates = [date_in_n_days(i) for i in range(start, end+1)]
122         days = [cls._day_as_dict(d) for d in dates]
123         library = {'Day': cls.as_refs(days)} if len(days) > 0 else {}
124         return {'today': today_date, 'start': start_date, 'end': end_date,
125                 'days': dates, '_library': library}
126
127     @staticmethod
128     def _todo_as_dict(id_: int = 1,
129                       process_id: int = 1,
130                       date: str = '2024-01-01',
131                       conditions: None | list[int] = None,
132                       disables: None | list[int] = None,
133                       blockers: None | list[int] = None,
134                       enables: None | list[int] = None
135                       ) -> dict[str, object]:
136         """Return JSON of Todo to expect."""
137         # pylint: disable=too-many-arguments
138         d = {'id': id_,
139              'date': date,
140              'process_id': process_id,
141              'is_done': False,
142              'calendarize': False,
143              'comment': '',
144              'children': [],
145              'parents': [],
146              'effort': None,
147              'conditions': conditions if conditions else [],
148              'disables': disables if disables else [],
149              'blockers': blockers if blockers else [],
150              'enables': enables if enables else []}
151         return d
152
153     @staticmethod
154     def _todo_node_as_dict(todo_id: int) -> dict[str, object]:
155         """Return JSON of TodoNode to expect."""
156         return {'children': [], 'seen': False, 'todo': todo_id}
157
158     @staticmethod
159     def _day_as_dict(date: str) -> dict[str, object]:
160         return {'id': date, 'comment': '', 'todos': []}
161
162     @staticmethod
163     def _post_batch(list_of_args: list[list[object]],
164                     names_of_simples: list[str],
165                     names_of_versioneds: list[str],
166                     f_as_dict: Callable[..., dict[str, object]],
167                     f_to_post: Callable[..., None | dict[str, object]]
168                     ) -> list[dict[str, object]]:
169         """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
170         expecteds = []
171         for args in list_of_args:
172             expecteds += [f_as_dict(*args)]
173         for expected in expecteds:
174             assert isinstance(expected['_versioned'], dict)
175             post = {}
176             for name in names_of_simples:
177                 post[name] = expected[name]
178             for name in names_of_versioneds:
179                 post[name] = expected['_versioned'][name][0]
180             f_to_post(expected['id'], post)
181         return expecteds
182
183     def _post_day(self, params: str = '',
184                   form_data: None | dict[str, object] = None,
185                   redir_to: str = '',
186                   status: int = 302,
187                   ) -> None:
188         """POST /day?{params} with form_data."""
189         if not form_data:
190             form_data = {'day_comment': '', 'make_type': ''}
191         target = f'/day?{params}'
192         if not redir_to:
193             redir_to = f'{target}&make_type={form_data["make_type"]}'
194         self.check_post(form_data, target, status, redir_to)
195
196     def test_basic_GET_day(self) -> None:
197         """Test basic (no Processes/Conditions/Todos) GET /day basics."""
198         # check illegal date parameters
199         self.check_get('/day?date=foo', 400)
200         self.check_get('/day?date=2024-02-30', 400)
201         # check undefined day
202         date = date_in_n_days(0)
203         expected = self.GET_day_dict(date)
204         self.check_json_get('/day', expected)
205         # NB: GET ?date="today"/"yesterday"/"tomorrow" in test_basic_POST_day
206         # check 'make_type' GET parameter affects immediate reply, but …
207         date = '2024-01-01'
208         expected = self.GET_day_dict(date)
209         expected['make_type'] = 'bar'
210         self.check_json_get(f'/day?date={date}&make_type=bar', expected)
211         # … not any following, …
212         expected['make_type'] = ''
213         self.check_json_get(f'/day?date={date}', expected)
214         # … not even when part of a POST request
215         post: dict[str, object] = {'day_comment': '', 'make_type': 'foo'}
216         self._post_day(f'date={date}', post)
217         self.check_json_get(f'/day?date={date}', expected)
218
219     def test_fail_POST_day(self) -> None:
220         """Test malformed/illegal POST /day requests."""
221         # check payloads lacking minimum expecteds
222         url = '/day?date=2024-01-01'
223         self.check_post({}, url, 400)
224         self.check_post({'day_comment': ''}, url, 400)
225         self.check_post({'make_type': ''}, url, 400)
226         # to next check illegal new_todo values, we need an actual Process
227         self.post_process(1)
228         # check illegal new_todo values
229         post: dict[str, object]
230         post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
231         self.check_post(post, url, 400)
232         post['new_todo'] = [1, 2]  # no Process of .id_=2 exists
233         # to next check illegal old_todo inputs, we need to first post Todo
234         post['new_todo'] = [1]
235         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
236         # check illegal old_todo inputs (equal list lengths though)
237         post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
238                 'effort': [3.3], 'done': [], 'todo_id': [1]}
239         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
240         post['todo_id'] = [2]  # reference to non-existant Process
241         self.check_post(post, url, 404)
242         post['todo_id'] = ['a']
243         self.check_post(post, url, 400)
244         post['todo_id'] = [1]
245         post['done'] = ['foo']
246         self.check_post(post, url, 400)
247         post['done'] = [2]  # reference to non-posted todo_id
248         self.check_post(post, url, 400)
249         post['done'] = []
250         post['effort'] = ['foo']
251         self.check_post(post, url, 400)
252         post['effort'] = [None]
253         self.check_post(post, url, 400)
254         post['effort'] = [3.3]
255         # check illegal old_todo inputs: unequal list lengths
256         post['comment'] = []
257         self.check_post(post, url, 400)
258         post['comment'] = ['foo', 'foo']
259         self.check_post(post, url, 400)
260         post['comment'] = ['foo']
261         post['effort'] = []
262         self.check_post(post, url, 400)
263         post['effort'] = [3.3, 3.3]
264         self.check_post(post, url, 400)
265         post['effort'] = [3.3]
266         post['todo_id'] = [1, 1]
267         self.check_post(post, url, 400)
268         post['todo_id'] = [1]
269         # # check valid POST payload on bad paths
270         self.check_post(post, '/day', 400)
271         self.check_post(post, '/day?date=', 400)
272         self.check_post(post, '/day?date=foo', 400)
273
274     def test_basic_POST_day(self) -> None:
275         """Test basic (no Todos) POST /day.
276
277         Check POST (& GET!) requests properly parse 'today', 'tomorrow',
278         'yesterday', and actual date strings;
279         preserve 'make_type' setting in redirect even if nonsensical;
280         and store 'day_comment'
281         """
282         for name, dist, test_str in [('2024-01-01', None, 'a'),
283                                      ('today', 0, 'b'),
284                                      ('yesterday', -1, 'c'),
285                                      ('tomorrow', +1, 'd')]:
286             date = name if dist is None else date_in_n_days(dist)
287             post = {'day_comment': test_str, 'make_type': f'x:{test_str}'}
288             post_url = f'/day?date={name}'
289             redir_url = f'{post_url}&make_type={post["make_type"]}'
290             self.check_post(post, post_url, 302, redir_url)
291             expected = self.GET_day_dict(date)
292             assert isinstance(expected['_library'], dict)
293             expected['_library']['Day'][date]['comment'] = test_str
294             self.check_json_get(post_url, expected)
295
296     def test_GET_day_with_processes_and_todos(self) -> None:
297         """Test GET /day displaying Processes and Todos (no trees)."""
298         date = '2024-01-01'
299         # check Processes get displayed in ['processes'] and ['_library']
300         procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
301         procs_expected = self._post_batch(procs_data, [],
302                                           ['title', 'description', 'effort'],
303                                           self.proc_as_dict, self.post_process)
304         expected = self.GET_day_dict(date)
305         assert isinstance(expected['_library'], dict)
306         expected['processes'] = self.as_id_list(procs_expected)
307         expected['_library']['Process'] = self.as_refs(procs_expected)
308         self._post_day(f'date={date}')
309         self.check_json_get(f'/day?date={date}', expected)
310         # post Todos of either process and check their display
311         post_day: dict[str, object]
312         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
313         todos = [self._todo_as_dict(1, 1, date),
314                  self._todo_as_dict(2, 2, date)]
315         expected['_library']['Todo'] = self.as_refs(todos)
316         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
317         nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
318         expected['top_nodes'] = nodes
319         self._post_day(f'date={date}', post_day)
320         self.check_json_get(f'/day?date={date}', expected)
321         # add a comment to one Todo and set the other's doneness and effort
322         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [],
323                     'todo_id': [1, 2], 'done': [2], 'comment': ['FOO', ''],
324                     'effort': [2.3, '']}
325         expected['_library']['Todo']['1']['comment'] = 'FOO'
326         expected['_library']['Todo']['1']['effort'] = 2.3
327         expected['_library']['Todo']['2']['is_done'] = True
328         self._post_day(f'date={date}', post_day)
329         self.check_json_get(f'/day?date={date}', expected)
330
331     def test_GET_day_with_conditions(self) -> None:
332         """Test GET /day displaying Conditions and their relations."""
333         date = '2024-01-01'
334         # add Process with Conditions and their Todos, check display
335         conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
336         conds_expected = self._post_batch(
337                 conds_data, ['is_active'], ['title', 'description'],
338                 self.cond_as_dict,
339                 lambda x, y: self.check_post(y, f'/condition?id={x}', 302))
340         cond_names = ['conditions', 'disables', 'blockers', 'enables']
341         procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
342                       [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
343         procs_expected = self._post_batch(procs_data, cond_names,
344                                           ['title', 'description', 'effort'],
345                                           self.proc_as_dict, self.post_process)
346         expected = self.GET_day_dict(date)
347         assert isinstance(expected['_library'], dict)
348         expected['processes'] = self.as_id_list(procs_expected)
349         expected['_library']['Process'] = self.as_refs(procs_expected)
350         expected['_library']['Condition'] = self.as_refs(conds_expected)
351         self._post_day(f'date={date}')
352         self.check_json_get(f'/day?date={date}', expected)
353         # add Todos in relation to Conditions, check consequences
354         post_day: dict[str, object]
355         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
356         todos = [self._todo_as_dict(1, 1, date, [1], [1], [2], [2]),
357                  self._todo_as_dict(2, 2, date, [2], [2], [1], [1])]
358         expected['_library']['Todo'] = self.as_refs(todos)
359         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
360         nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
361         expected['top_nodes'] = nodes
362         expected['disablers_for'] = {'1': [1], '2': [2]}
363         expected['enablers_for'] = {'1': [2], '2': [1]}
364         expected['conditions_present'] = self.as_id_list(conds_expected)
365         self._post_day(f'date={date}', post_day)
366         self.check_json_get(f'/day?date={date}', expected)
367
368     def test_GET_calendar(self) -> None:
369         """Test GET /calendar responses based on various inputs, DB states."""
370         # check illegal date range delimiters
371         self.check_get('/calendar?start=foo', 400)
372         self.check_get('/calendar?end=foo', 400)
373         # check default range for expected selection/order without saved days
374         expected = self.GET_calendar_dict(-1, 366)
375         self.check_json_get('/calendar', expected)
376         self.check_json_get('/calendar?start=&end=', expected)
377         # check with named days as delimiters
378         expected = self.GET_calendar_dict(-1, +1)
379         self.check_json_get('/calendar?start=yesterday&end=tomorrow', expected)
380         # check zero-element range
381         expected = self.GET_calendar_dict(+1, 0)
382         self.check_json_get('/calendar?start=tomorrow&end=today', expected)
383         # check saved day shows up in results, proven by its comment
384         post_day: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
385         date1 = date_in_n_days(-2)
386         self._post_day(f'date={date1}', post_day)
387         start_date = date_in_n_days(-5)
388         end_date = date_in_n_days(+5)
389         url = f'/calendar?start={start_date}&end={end_date}'
390         expected = self.GET_calendar_dict(-5, +5)
391         assert isinstance(expected['_library'], dict)
392         expected['_library']['Day'][date1]['comment'] = post_day['day_comment']
393         self.check_json_get(url, expected)