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
9 class TestsSansDB(TestCaseSansDB):
10 """Days module tests not requiring DB setup."""
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']
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))
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)
30 class TestsWithDB(TestCaseWithDB):
31 """Tests requiring DB, but not server setup."""
33 default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
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)
39 def test_Day_with_filled_gaps(self) -> None:
40 """Test .with_filled_gaps."""
42 def test(range_indexes: tuple[int, int], indexes_to_provide: list[int]
44 start_i, end_i = range_indexes
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,
55 self.assertEqual(days_result, days_expected)
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
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
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)]
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')
87 result = self.checked_class.with_filled_gaps([today], 'yesterday',
89 self.assertEqual(result, [yesterday, today, tomorrow])
92 class TestsWithServer(TestCaseWithServer):
93 """Tests against our HTTP server/handler (and database)."""
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,
105 'conditions_present': [],
107 '_library': {'Day': cls.as_refs([day])}}
111 def GET_calendar_dict(cls, start: int, end: int) -> dict[str, object]:
112 """Return JSON of GET /calendar to expect.
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.
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}
128 def _todo_as_dict(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
140 'process_id': process_id,
142 'calendarize': False,
147 'conditions': conditions if conditions else [],
148 'disables': disables if disables else [],
149 'blockers': blockers if blockers else [],
150 'enables': enables if enables else []}
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}
159 def _day_as_dict(date: str) -> dict[str, object]:
160 return {'id': date, 'comment': '', 'todos': []}
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."""
171 for args in list_of_args:
172 expecteds += [f_as_dict(*args)]
173 for expected in expecteds:
174 assert isinstance(expected['_versioned'], dict)
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)
183 def _post_day(self, params: str = '',
184 form_data: None | dict[str, object] = None,
188 """POST /day?{params} with form_data."""
190 form_data = {'day_comment': '', 'make_type': ''}
191 target = f'/day?{params}'
193 redir_to = f'{target}&make_type={form_data["make_type"]}'
194 self.check_post(form_data, target, status, redir_to)
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 …
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)
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
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)
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
257 self.check_post(post, url, 400)
258 post['comment'] = ['foo', 'foo']
259 self.check_post(post, url, 400)
260 post['comment'] = ['foo']
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)
274 def test_basic_POST_day(self) -> None:
275 """Test basic (no Todos) POST /day.
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'
282 for name, dist, test_str in [('2024-01-01', None, 'a'),
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)
296 def test_GET_day_with_processes_and_todos(self) -> None:
297 """Test GET /day displaying Processes and Todos (no trees)."""
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', ''],
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)
331 def test_GET_day_with_conditions(self) -> None:
332 """Test GET /day displaying Conditions and their relations."""
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'],
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)
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)