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