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