home · contact · privacy
Slightly improve and re-organize Condition 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     @classmethod
83     def GET_day_dict(cls, date: str) -> dict[str, object]:
84         """Return JSON of GET /day to expect."""
85         # day: dict[str, object] = {'id': date, 'comment': '', 'todos': []}
86         day = cls._day_as_dict(date)
87         d: dict[str, object] = {'day': date,
88                                 'top_nodes': [],
89                                 'make_type': '',
90                                 'enablers_for': {},
91                                 'disablers_for': {},
92                                 'conditions_present': [],
93                                 'processes': [],
94                                 '_library': {'Day': cls.as_refs([day])}}
95         return d
96
97     @classmethod
98     def GET_calendar_dict(cls, start: int, end: int) -> dict[str, object]:
99         """Return JSON of GET /calendar to expect."""
100         today_date = date_in_n_days(0)
101         start_date = date_in_n_days(start)
102         end_date = date_in_n_days(end)
103         dates = [date_in_n_days(i) for i in range(start, end+1)]
104         days = [cls._day_as_dict(d) for d in dates]
105         library = {'Day': cls.as_refs(days)} if len(days) > 0 else {}
106         return {'today': today_date, 'start': start_date, 'end': end_date,
107                 'days': dates, '_library': library}
108
109     @staticmethod
110     def _todo_as_dict(id_: int = 1,
111                       process_id: int = 1,
112                       date: str = '2024-01-01',
113                       conditions: None | list[int] = None,
114                       disables: None | list[int] = None,
115                       blockers: None | list[int] = None,
116                       enables: None | list[int] = None
117                       ) -> dict[str, object]:
118         """Return JSON of Todo to expect."""
119         # pylint: disable=too-many-arguments
120         d = {'id': id_,
121              'date': date,
122              'process_id': process_id,
123              'is_done': False,
124              'calendarize': False,
125              'comment': '',
126              'children': [],
127              'parents': [],
128              'effort': None,
129              'conditions': conditions if conditions else [],
130              'disables': disables if disables else [],
131              'blockers': blockers if blockers else [],
132              'enables': enables if enables else []}
133         return d
134
135     @staticmethod
136     def _todo_node_as_dict(todo_id: int) -> dict[str, object]:
137         """Return JSON of TodoNode to expect."""
138         return {'children': [], 'seen': False, 'todo': todo_id}
139
140     @staticmethod
141     def _day_as_dict(date: str) -> dict[str, object]:
142         return {'id': date, 'comment': '', 'todos': []}
143
144     @staticmethod
145     def _post_batch(list_of_args: list[list[object]],
146                     names_of_simples: list[str],
147                     names_of_versioneds: list[str],
148                     f_as_dict: Callable[..., dict[str, object]],
149                     f_to_post: Callable[..., None | dict[str, object]]
150                     ) -> list[dict[str, object]]:
151         """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
152         expecteds = []
153         for args in list_of_args:
154             expecteds += [f_as_dict(*args)]
155         for expected in expecteds:
156             assert isinstance(expected['_versioned'], dict)
157             post = {}
158             for name in names_of_simples:
159                 post[name] = expected[name]
160             for name in names_of_versioneds:
161                 post[name] = expected['_versioned'][name][0]
162             f_to_post(expected['id'], post)
163         return expecteds
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     def test_basic_GET_day(self) -> None:
179         """Test basic (no Processes/Conditions/Todos) GET /day basics."""
180         # check illegal date parameters
181         self.check_get('/day?date=foo', 400)
182         self.check_get('/day?date=2024-02-30', 400)
183         # check undefined day
184         date = date_in_n_days(0)
185         expected = self.GET_day_dict(date)
186         self.check_json_get('/day', expected)
187         # NB: GET ?date="today"/"yesterday"/"tomorrow" in test_basic_POST_day
188         # check 'make_type' GET parameter affects immediate reply, but …
189         date = '2024-01-01'
190         expected = self.GET_day_dict(date)
191         expected['make_type'] = 'bar'
192         self.check_json_get(f'/day?date={date}&make_type=bar', expected)
193         # … not any following, …
194         expected['make_type'] = ''
195         self.check_json_get(f'/day?date={date}', expected)
196         # … not even when part of a POST request
197         post: dict[str, object] = {'day_comment': '', 'make_type': 'foo'}
198         self._post_day(f'date={date}', post)
199         self.check_json_get(f'/day?date={date}', expected)
200
201     def test_fail_POST_day(self) -> None:
202         """Test malformed/illegal POST /day requests."""
203         # check payloads lacking minimum expecteds
204         url = '/day?date=2024-01-01'
205         self.check_post({}, url, 400)
206         self.check_post({'day_comment': ''}, url, 400)
207         self.check_post({'make_type': ''}, url, 400)
208         # to next check illegal new_todo values, we need an actual Process
209         self.post_process(1)
210         # check illegal new_todo values
211         post: dict[str, object]
212         post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
213         self.check_post(post, url, 400)
214         post['new_todo'] = [1, 2]  # no Process of .id_=2 exists
215         # to next check illegal old_todo inputs, we need to first post Todo
216         post['new_todo'] = [1]
217         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
218         # check illegal old_todo inputs (equal list lengths though)
219         post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
220                 'effort': [3.3], 'done': [], 'todo_id': [1]}
221         self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
222         post['todo_id'] = [2]  # reference to non-existant Process
223         self.check_post(post, url, 404)
224         post['todo_id'] = ['a']
225         self.check_post(post, url, 400)
226         post['todo_id'] = [1]
227         post['done'] = ['foo']
228         self.check_post(post, url, 400)
229         post['done'] = [2]  # reference to non-posted todo_id
230         self.check_post(post, url, 400)
231         post['done'] = []
232         post['effort'] = ['foo']
233         self.check_post(post, url, 400)
234         post['effort'] = [None]
235         self.check_post(post, url, 400)
236         post['effort'] = [3.3]
237         # check illegal old_todo inputs: unequal list lengths
238         post['comment'] = []
239         self.check_post(post, url, 400)
240         post['comment'] = ['foo', 'foo']
241         self.check_post(post, url, 400)
242         post['comment'] = ['foo']
243         post['effort'] = []
244         self.check_post(post, url, 400)
245         post['effort'] = [3.3, 3.3]
246         self.check_post(post, url, 400)
247         post['effort'] = [3.3]
248         post['todo_id'] = [1, 1]
249         self.check_post(post, url, 400)
250         post['todo_id'] = [1]
251         # # check valid POST payload on bad paths
252         self.check_post(post, '/day', 400)
253         self.check_post(post, '/day?date=', 400)
254         self.check_post(post, '/day?date=foo', 400)
255
256     def test_basic_POST_day(self) -> None:
257         """Test basic (no Todos) POST /day.
258
259         Check POST (& GET!) requests properly parse 'today', 'tomorrow',
260         'yesterday', and actual date strings;
261         preserve 'make_type' setting in redirect even if nonsensical;
262         and store 'day_comment'
263         """
264         for name, dist, test_str in [('2024-01-01', None, 'a'),
265                                      ('today', 0, 'b'),
266                                      ('yesterday', -1, 'c'),
267                                      ('tomorrow', +1, 'd')]:
268             date = name if dist is None else date_in_n_days(dist)
269             post = {'day_comment': test_str, 'make_type': f'x:{test_str}'}
270             post_url = f'/day?date={name}'
271             redir_url = f'{post_url}&make_type={post["make_type"]}'
272             self.check_post(post, post_url, 302, redir_url)
273             expected = self.GET_day_dict(date)
274             assert isinstance(expected['_library'], dict)
275             expected['_library']['Day'][date]['comment'] = test_str
276             self.check_json_get(post_url, expected)
277
278     def test_GET_day_with_processes_and_todos(self) -> None:
279         """Test GET /day displaying Processes and Todos (no trees)."""
280         date = '2024-01-01'
281         # check Processes get displayed in ['processes'] and ['_library']
282         procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
283         procs_expected = self._post_batch(procs_data, [],
284                                           ['title', 'description', 'effort'],
285                                           self.proc_as_dict, self.post_process)
286         expected = self.GET_day_dict(date)
287         assert isinstance(expected['_library'], dict)
288         expected['processes'] = self.as_id_list(procs_expected)
289         expected['_library']['Process'] = self.as_refs(procs_expected)
290         self._post_day(f'date={date}')
291         self.check_json_get(f'/day?date={date}', expected)
292         # post Todos of either process and check their display
293         post_day: dict[str, object]
294         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
295         todos = [self._todo_as_dict(1, 1, date),
296                  self._todo_as_dict(2, 2, date)]
297         expected['_library']['Todo'] = self.as_refs(todos)
298         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
299         nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
300         expected['top_nodes'] = nodes
301         self._post_day(f'date={date}', post_day)
302         self.check_json_get(f'/day?date={date}', expected)
303         # add a comment to one Todo and set the other's doneness and effort
304         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [],
305                     'todo_id': [1, 2], 'done': [2], 'comment': ['FOO', ''],
306                     'effort': [2.3, '']}
307         expected['_library']['Todo']['1']['comment'] = 'FOO'
308         expected['_library']['Todo']['1']['effort'] = 2.3
309         expected['_library']['Todo']['2']['is_done'] = True
310         self._post_day(f'date={date}', post_day)
311         self.check_json_get(f'/day?date={date}', expected)
312
313     def test_GET_day_with_conditions(self) -> None:
314         """Test GET /day displaying Conditions and their relations."""
315         date = '2024-01-01'
316         # add Process with Conditions and their Todos, check display
317         conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
318         conds_expected = self._post_batch(
319                 conds_data, ['is_active'], ['title', 'description'],
320                 self.cond_as_dict,
321                 lambda x, y: self.check_post(y, f'/condition?id={x}', 302))
322         cond_names = ['conditions', 'disables', 'blockers', 'enables']
323         procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
324                       [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
325         procs_expected = self._post_batch(procs_data, cond_names,
326                                           ['title', 'description', 'effort'],
327                                           self.proc_as_dict, self.post_process)
328         expected = self.GET_day_dict(date)
329         assert isinstance(expected['_library'], dict)
330         expected['processes'] = self.as_id_list(procs_expected)
331         expected['_library']['Process'] = self.as_refs(procs_expected)
332         expected['_library']['Condition'] = self.as_refs(conds_expected)
333         self._post_day(f'date={date}')
334         self.check_json_get(f'/day?date={date}', expected)
335         # add Todos in relation to Conditions, check consequences
336         post_day: dict[str, object]
337         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
338         todos = [self._todo_as_dict(1, 1, date, [1], [1], [2], [2]),
339                  self._todo_as_dict(2, 2, date, [2], [2], [1], [1])]
340         expected['_library']['Todo'] = self.as_refs(todos)
341         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
342         nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
343         expected['top_nodes'] = nodes
344         expected['disablers_for'] = {'1': [1], '2': [2]}
345         expected['enablers_for'] = {'1': [2], '2': [1]}
346         expected['conditions_present'] = self.as_id_list(conds_expected)
347         self._post_day(f'date={date}', post_day)
348         self.check_json_get(f'/day?date={date}', expected)
349
350     def test_GET_calendar(self) -> None:
351         """Test GET /calendar responses based on various inputs, DB states."""
352         # check illegal date range delimiters
353         self.check_get('/calendar?start=foo', 400)
354         self.check_get('/calendar?end=foo', 400)
355         # check default range without saved days
356         expected = self.GET_calendar_dict(-1, 366)
357         self.check_json_get('/calendar', expected)
358         self.check_json_get('/calendar?start=&end=', expected)
359         # check named days as delimiters
360         expected = self.GET_calendar_dict(-1, +1)
361         self.check_json_get('/calendar?start=yesterday&end=tomorrow', expected)
362         # check zero-element range
363         expected = self.GET_calendar_dict(+1, 0)
364         self.check_json_get('/calendar?start=tomorrow&end=today', expected)
365         # check saved day shows up in results with proven by its comment
366         post_day: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
367         date1 = date_in_n_days(-2)
368         self._post_day(f'date={date1}', post_day)
369         start_date = date_in_n_days(-5)
370         end_date = date_in_n_days(+5)
371         url = f'/calendar?start={start_date}&end={end_date}'
372         expected = self.GET_calendar_dict(-5, +5)
373         assert isinstance(expected['_library'], dict)
374         expected['_library']['Day'][date1]['comment'] = post_day['day_comment']
375         self.check_json_get(url, expected)