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
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'
13 class TestsSansDB(TestCaseSansDB):
14 """Days module tests not requiring DB setup."""
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']
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))
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)
35 class TestsWithDB(TestCaseWithDB):
36 """Tests requiring DB, but not server setup."""
38 default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
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)
44 def test_Day_with_filled_gaps(self) -> None:
45 """Test .with_filled_gaps."""
47 def test(range_indexes: tuple[int, int], indexes_to_provide: list[int]
49 start_i, end_i = range_indexes
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,
60 self.assertEqual(days_result, days_expected)
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
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
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)]
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')
92 result = self.checked_class.with_filled_gaps([today], 'yesterday',
94 self.assertEqual(result, [yesterday, today, tomorrow])
97 class TestsWithServer(TestCaseWithServer):
98 """Tests against our HTTP server/handler (and database)."""
101 def _testing_date_in_n_days(n: int) -> str:
102 """Return in TEST_DATE_FORMAT date from today + n days.
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.
108 date = datetime.now() + timedelta(days=n)
109 return date.strftime(TESTING_DATE_FORMAT)
112 def _day_as_dict(date: str) -> dict[str, object]:
113 return {'id': date, 'comment': '', 'todos': []}
116 def _todo_node_as_dict(todo_id: int) -> dict[str, object]:
117 """Return JSON of TodoNode to expect."""
118 return {'children': [], 'seen': False, 'todo': todo_id}
121 def _post_args_return_expectation(
123 names_of_simples: list[str],
124 names_of_versioneds: list[str],
125 f_as_dict: Callable[..., dict[str, object]],
126 f_to_post: Callable[..., None | dict[str, object]]
127 ) -> dict[str, object]:
128 """Create expected=f_as_dict(*args), post as names_* with f_to_post."""
129 expected = f_as_dict(*args)
130 assert isinstance(expected['_versioned'], dict)
132 for name in names_of_simples:
133 to_post[name] = expected[name]
134 for name in names_of_versioneds:
135 to_post[name] = expected['_versioned'][name][0]
136 f_to_post(expected['id'], to_post)
139 def _post_day(self, params: str = '',
140 form_data: None | dict[str, object] = None,
144 """POST /day?{params} with form_data."""
146 form_data = {'day_comment': '', 'make_type': ''}
147 target = f'/day?{params}'
149 redir_to = f'{target}&make_type={form_data["make_type"]}'
150 self.check_post(form_data, target, status, redir_to)
153 def GET_day_dict(cls, date: str) -> dict[str, object]:
154 """Return JSON of GET /day to expect."""
155 day = cls._day_as_dict(date)
156 d: dict[str, object] = {'day': date,
161 'conditions_present': [],
163 '_library': {'Day': cls.as_refs([day])}}
167 def GET_calendar_dict(cls, start: int, end: int) -> dict[str, object]:
168 """Return JSON of GET /calendar to expect.
170 NB: the date string list to key 'days' implies/expects a continuous (=
171 gaps filled) alphabetical order of dates by virtue of range(start,
172 end+1) and date_in_n_days.
174 today_date = cls._testing_date_in_n_days(0)
175 start_date = cls._testing_date_in_n_days(start)
176 end_date = cls._testing_date_in_n_days(end)
177 dates = [cls._testing_date_in_n_days(i) for i in range(start, end+1)]
178 days = [cls._day_as_dict(d) for d in dates]
179 library = {'Day': cls.as_refs(days)} if len(days) > 0 else {}
180 return {'today': today_date, 'start': start_date, 'end': end_date,
181 'days': dates, '_library': library}
183 def test_basic_GET_day(self) -> None:
184 """Test basic (no Processes/Conditions/Todos) GET /day basics."""
185 # check illegal date parameters
186 self.check_get('/day?date=foo', 400)
187 self.check_get('/day?date=2024-02-30', 400)
188 # check undefined day
189 date = self._testing_date_in_n_days(0)
190 expected = self.GET_day_dict(date)
191 self.check_json_get('/day', expected)
192 # check defined day, with and without make_type parameter
194 expected = self.GET_day_dict(date)
195 expected['make_type'] = 'bar'
196 self.check_json_get(f'/day?date={date}&make_type=bar', expected)
197 # check parsing of 'yesterday', 'today', 'tomorrow'
198 for name, dist in [('yesterday', -1), ('today', 0), ('tomorrow', +1)]:
199 date = self._testing_date_in_n_days(dist)
200 expected = self.GET_day_dict(date)
201 self.check_json_get(f'/day?date={name}', expected)
203 def test_fail_POST_day(self) -> None:
204 """Test malformed/illegal POST /day requests."""
205 # check payloads lacking minimum expecteds
206 url = '/day?date=2024-01-01'
207 self.check_post({}, url, 400)
208 self.check_post({'day_comment': ''}, url, 400)
209 self.check_post({'make_type': ''}, url, 400)
210 # to next check illegal new_todo values, we need an actual Process
212 # check illegal new_todo values
213 post: dict[str, object]
214 post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
215 self.check_post(post, url, 400)
216 post['new_todo'] = [1, 2] # no Process of .id_=2 exists
217 # to next check illegal old_todo inputs, we need to first post Todo
218 post['new_todo'] = [1]
219 self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
220 # check illegal old_todo inputs (equal list lengths though)
221 post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
222 'effort': [3.3], 'done': [], 'todo_id': [1]}
223 self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
224 post['todo_id'] = [2] # reference to non-existant Process
225 self.check_post(post, url, 404)
226 post['todo_id'] = ['a']
227 self.check_post(post, url, 400)
228 post['todo_id'] = [1]
229 post['done'] = ['foo']
230 self.check_post(post, url, 400)
231 post['done'] = [2] # reference to non-posted todo_id
232 self.check_post(post, url, 400)
234 post['effort'] = ['foo']
235 self.check_post(post, url, 400)
236 post['effort'] = [None]
237 self.check_post(post, url, 400)
238 post['effort'] = [3.3]
239 # check illegal old_todo inputs: unequal list lengths
241 self.check_post(post, url, 400)
242 post['comment'] = ['foo', 'foo']
243 self.check_post(post, url, 400)
244 post['comment'] = ['foo']
246 self.check_post(post, url, 400)
247 post['effort'] = [3.3, 3.3]
248 self.check_post(post, url, 400)
249 post['effort'] = [3.3]
250 post['todo_id'] = [1, 1]
251 self.check_post(post, url, 400)
252 post['todo_id'] = [1]
253 # # check valid POST payload on bad paths
254 self.check_post(post, '/day', 400)
255 self.check_post(post, '/day?date=', 400)
256 self.check_post(post, '/day?date=foo', 400)
258 def test_basic_POST_day(self) -> None:
259 """Test basic (no Processes/Conditions/Todos) POST /day.
261 Check POST requests properly parse 'today', 'tomorrow', 'yesterday',
262 and actual date strings;
263 preserve 'make_type' setting in redirect even if nonsensical;
264 and store 'day_comment'.
266 for name, dist, test_str in [('2024-01-01', None, 'a'),
268 ('yesterday', -1, 'c'),
269 ('tomorrow', +1, 'd')]:
270 date = name if dist is None else self._testing_date_in_n_days(dist)
271 post = {'day_comment': test_str, 'make_type': f'x:{test_str}'}
272 post_url = f'/day?date={name}'
273 redir_url = f'{post_url}&make_type={post["make_type"]}'
274 self.check_post(post, post_url, 302, redir_url)
275 expected = self.GET_day_dict(date)
276 assert isinstance(expected['_library'], dict)
277 expected['_library']['Day'][date]['comment'] = test_str
278 self.check_json_get(post_url, expected)
280 def test_GET_day_with_processes_and_todos(self) -> None:
281 """Test GET /day displaying Processes and Todos (no trees)."""
283 # check Processes get displayed in ['processes'] and ['_library'],
284 # even without any Todos referencing them
285 procs_data = [[1, 'foo', 'oof', 1.1], # id, title, desc, effort
286 [2, 'bar', 'rab', 0.9]]
288 for p_data in procs_data:
289 procs_expected += [self._post_args_return_expectation(
290 p_data, [], ['title', 'description', 'effort'],
291 self.proc_as_dict, self.post_process)]
292 expected = self.GET_day_dict(date)
293 assert isinstance(expected['_library'], dict)
294 expected['processes'] = self.as_id_list(procs_expected)
295 expected['_library']['Process'] = self.as_refs(procs_expected)
296 self.check_json_get(f'/day?date={date}', expected)
297 # post Todos of either process and check their display
298 post_day: dict[str, object]
299 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
300 todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
301 expected['_library']['Todo'] = self.as_refs(todos)
302 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
303 nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
304 expected['top_nodes'] = nodes
305 self._post_day(f'date={date}', post_day)
306 self.check_json_get(f'/day?date={date}', expected)
307 # add a comment to one Todo and set the other's doneness and effort
308 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [],
309 'todo_id': [1, 2], 'done': [2], 'comment': ['FOO', ''],
311 expected['_library']['Todo']['1']['comment'] = 'FOO'
312 expected['_library']['Todo']['1']['effort'] = 2.3
313 expected['_library']['Todo']['2']['is_done'] = True
314 self._post_day(f'date={date}', post_day)
315 self.check_json_get(f'/day?date={date}', expected)
317 def test_GET_day_with_conditions(self) -> None:
318 """Test GET /day displaying Conditions and their relations."""
320 # add Process with Conditions and their Todos, check display
321 conds_data = [[1, False, ['A'], ['a']], # id, is_active, title, desc
322 [2, True, ['B'], ['b']]]
324 for c_data in conds_data:
325 conds_expected += [self._post_args_return_expectation(
326 c_data, ['is_active'], ['title', 'description'],
328 lambda x, y: self.check_post(y, f'/condition?id={x}'))]
329 procs_data = [ # id, title, desc, effort,
330 # conditions, disables, blockers, enables
331 [1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
332 [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
334 for p_data in procs_data:
335 procs_expected += [self._post_args_return_expectation(
337 ['conditions', 'disables', 'blockers', 'enables'],
338 ['title', 'description', 'effort'],
339 self.proc_as_dict, self.post_process)]
340 expected = self.GET_day_dict(date)
341 assert isinstance(expected['_library'], dict)
342 expected['processes'] = self.as_id_list(procs_expected)
343 expected['_library']['Process'] = self.as_refs(procs_expected)
344 expected['_library']['Condition'] = self.as_refs(conds_expected)
345 self._post_day(f'date={date}')
346 self.check_json_get(f'/day?date={date}', expected)
347 # add Todos in relation to Conditions, check consequences
348 post_day: dict[str, object]
349 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
350 todos = [ # id, process_id, date, conds, disables, blockers, enables
351 self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
352 self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
353 expected['_library']['Todo'] = self.as_refs(todos)
354 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
355 nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
356 expected['top_nodes'] = nodes
357 expected['disablers_for'] = {'1': [1], '2': [2]}
358 expected['enablers_for'] = {'1': [2], '2': [1]}
359 expected['conditions_present'] = self.as_id_list(conds_expected)
360 self._post_day(f'date={date}', post_day)
361 self.check_json_get(f'/day?date={date}', expected)
363 def test_GET_calendar(self) -> None:
364 """Test GET /calendar responses based on various inputs, DB states."""
365 # check illegal date range delimiters
366 self.check_get('/calendar?start=foo', 400)
367 self.check_get('/calendar?end=foo', 400)
368 # check default range for expected selection/order without saved days
369 expected = self.GET_calendar_dict(-1, 366)
370 self.check_json_get('/calendar', expected)
371 self.check_json_get('/calendar?start=&end=', expected)
372 # check with named days as delimiters
373 expected = self.GET_calendar_dict(-1, +1)
374 self.check_json_get('/calendar?start=yesterday&end=tomorrow', expected)
375 # check zero-element range
376 expected = self.GET_calendar_dict(+1, 0)
377 self.check_json_get('/calendar?start=tomorrow&end=today', expected)
378 # check saved day shows up in results, proven by its comment
379 post_day: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
380 date = self._testing_date_in_n_days(-2)
381 self._post_day(f'date={date}', post_day)
382 start_date = self._testing_date_in_n_days(-5)
383 end_date = self._testing_date_in_n_days(+5)
384 url = f'/calendar?start={start_date}&end={end_date}'
385 expected = self.GET_calendar_dict(-5, +5)
386 assert isinstance(expected['_library'], dict)
387 expected['_library']['Day'][date]['comment'] = post_day['day_comment']
388 self.check_json_get(url, expected)