1 """Test Days module."""
2 from datetime import datetime, timedelta
4 from tests.utils import (TestCaseSansDB, TestCaseWithDB, TestCaseWithServer,
6 from plomtask.dating import date_in_n_days as tested_date_in_n_days
7 from plomtask.days import Day
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'
14 def _testing_date_in_n_days(n: int) -> str:
15 """Return in TEST_DATE_FORMAT date from today + n days.
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.
21 date = datetime.now() + timedelta(days=n)
22 return date.strftime(TESTING_DATE_FORMAT)
25 class TestsSansDB(TestCaseSansDB):
26 """Days module tests not requiring DB setup."""
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']
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))
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)
47 class TestsWithDB(TestCaseWithDB):
48 """Tests requiring DB, but not server setup."""
50 default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
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)
56 def test_Day_with_filled_gaps(self) -> None:
57 """Test .with_filled_gaps."""
59 def test(range_indexes: tuple[int, int], indexes_to_provide: list[int]
61 start_i, end_i = range_indexes
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,
72 self.assertEqual(days_result, days_expected)
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
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
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)]
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')
104 result = self.checked_class.with_filled_gaps([today], 'yesterday',
106 self.assertEqual(result, [yesterday, today, tomorrow])
109 class ExpectedGetCalendar(Expected):
110 """Builder of expectations for GET /calendar."""
112 def __init__(self, start: int, end: int, *args: Any, **kwargs: Any
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)])
124 class ExpectedGetDay(Expected):
125 """Builder of expectations for GET /day."""
126 _default_dict = {'make_type': 'full'}
127 _on_empty_make_temp = ('Day', 'day_as_dict')
129 def __init__(self, date: str, *args: Any, **kwargs: Any) -> None:
130 self._fields = {'day': date}
131 super().__init__(*args, **kwargs)
133 def recalc(self) -> None:
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': 0, 'todo': todo['id']}
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()
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']:
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'))
160 class TestsWithServer(TestCaseWithServer):
161 """Tests against our HTTP server/handler (and database)."""
164 def test_basic_GET_day(self) -> None:
165 """Test basic (no Processes/Conditions/Todos) GET /day basics."""
166 # check illegal date parameters
167 self.check_get_defaults('/day', '2024-01-01', 'date')
168 self.check_get('/day?date=2024-02-30', 400)
169 # check undefined day
170 date = _testing_date_in_n_days(0)
171 exp = ExpectedGetDay(date)
172 self.check_json_get('/day', exp)
173 # check defined day, with and without make_type parameter
175 exp = ExpectedGetDay(date)
176 exp.set('make_type', 'bar')
177 self.check_json_get(f'/day?date={date}&make_type=bar', exp)
178 # check parsing of 'yesterday', 'today', 'tomorrow'
179 for name, dist in [('yesterday', -1), ('today', 0), ('tomorrow', +1)]:
180 date = _testing_date_in_n_days(dist)
181 exp = ExpectedGetDay(date)
182 self.check_json_get(f'/day?date={name}', exp)
184 def test_fail_POST_day(self) -> None:
185 """Test malformed/illegal POST /day requests."""
186 # check payloads lacking minimum expecteds
187 url = '/day?date=2024-01-01'
188 self.check_post({}, url, 400)
189 self.check_post({'day_comment': ''}, url, 400)
190 self.check_post({'make_type': ''}, url, 400)
191 # to next check illegal new_todo values, we need an actual Process
192 self.post_exp_process([], {}, 1)
193 # check illegal new_todo values
194 post: dict[str, object]
195 post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
196 self.check_post(post, url, 400)
197 post['new_todo'] = [1, 2] # no Process of .id_=2 exists
198 # to next check illegal old_todo inputs, we need to first post Todo
199 post['new_todo'] = [1]
200 self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
201 # check illegal old_todo inputs (equal list lengths though)
202 post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
203 'effort': [3.3], 'done': [], 'todo_id': [1]}
204 self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
205 post['todo_id'] = [2] # reference to non-existant Process
206 self.check_post(post, url, 404)
207 post['todo_id'] = ['a']
208 self.check_post(post, url, 400)
209 post['todo_id'] = [1]
210 post['done'] = ['foo']
211 self.check_post(post, url, 400)
212 post['done'] = [2] # reference to non-posted todo_id
213 self.check_post(post, url, 400)
215 post['effort'] = ['foo']
216 self.check_post(post, url, 400)
217 post['effort'] = [None]
218 self.check_post(post, url, 400)
219 post['effort'] = [3.3]
220 # check illegal old_todo inputs: unequal list lengths
222 self.check_post(post, url, 400)
223 post['comment'] = ['foo', 'foo']
224 self.check_post(post, url, 400)
225 post['comment'] = ['foo']
227 self.check_post(post, url, 400)
228 post['effort'] = [3.3, 3.3]
229 self.check_post(post, url, 400)
230 post['effort'] = [3.3]
231 post['todo_id'] = [1, 1]
232 self.check_post(post, url, 400)
233 post['todo_id'] = [1]
234 # # check valid POST payload on bad paths
235 self.check_post(post, '/day', 400)
236 self.check_post(post, '/day?date=', 400)
237 self.check_post(post, '/day?date=foo', 400)
239 def test_basic_POST_day(self) -> None:
240 """Test basic (no Processes/Conditions/Todos) POST /day.
242 Check POST requests properly parse 'today', 'tomorrow', 'yesterday',
243 and actual date strings; store 'day_comment'; preserve 'make_type'
244 setting in redirect even if nonsensical; and allow '' as 'new_todo'.
246 for name, dist, test_str in [('2024-01-01', None, 'a'),
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 'new_todo': ['', '']}
253 post_url = f'/day?date={name}'
254 redir_url = f'{post_url}&make_type={post["make_type"]}'
255 self.check_post(post, post_url, 302, redir_url)
256 exp = ExpectedGetDay(date)
257 exp.set_day_from_post(date, post)
258 self.check_json_get(post_url, exp)
260 def test_GET_day_with_processes_and_todos(self) -> None:
261 """Test GET /day displaying Processes and Todos (no trees)."""
263 exp = ExpectedGetDay(date)
264 # check Processes get displayed in ['processes'] and ['_library'],
265 # even without any Todos referencing them
266 proc_posts = [{'title': 'foo', 'description': 'oof', 'effort': 1.1},
267 {'title': 'bar', 'description': 'rab', 'effort': 0.9}]
268 for i, proc_post in enumerate(proc_posts):
269 self.post_exp_process([exp], proc_post, i+1)
270 self.check_json_get(f'/day?date={date}', exp)
271 # post Todos of either process and check their display
272 self.post_exp_day([exp], {'new_todo': [1, 2]})
273 self.check_json_get(f'/day?date={date}', exp)
274 # test malformed Todo manipulation posts
275 post_day = {'day_comment': '', 'make_type': '', 'comment': [''],
276 'new_todo': [], 'done': [1], 'effort': [2.3]}
277 self.check_post(post_day, f'/day?date={date}', 400) # no todo_id
278 post_day['todo_id'] = [2] # not identifying Todo refered by done
279 self.check_post(post_day, f'/day?date={date}', 400)
280 post_day['todo_id'] = [1, 2] # imply range beyond that of effort etc.
281 self.check_post(post_day, f'/day?date={date}', 400)
282 post_day['comment'] = ['FOO', '']
283 self.check_post(post_day, f'/day?date={date}', 400)
284 post_day['effort'] = [2.3, '']
285 post_day['comment'] = ['']
286 self.check_post(post_day, f'/day?date={date}', 400)
287 # add a comment to one Todo and set the other's doneness and effort
288 post_day['comment'] = ['FOO', '']
289 self.post_exp_day([exp], post_day)
290 self.check_json_get(f'/day?date={date}', exp)
291 # invert effort and comment between both Todos
292 # (cannot invert doneness, /day only collects positive setting)
293 post_day['comment'] = ['', 'FOO']
294 post_day['effort'] = ['', 2.3]
295 self.post_exp_day([exp], post_day)
296 self.check_json_get(f'/day?date={date}', exp)
298 def test_POST_day_todo_make_types(self) -> None:
299 """Test behavior of POST /todo on 'make_type'='full' and 'empty'."""
301 exp = ExpectedGetDay(date)
302 # create two Processes, with second one step of first one
303 self.post_exp_process([exp], {}, 2)
304 self.post_exp_process([exp], {'new_top_step': 2}, 1)
305 exp.lib_set('ProcessStep', [exp.procstep_as_dict(1, 1, 2, None)])
306 self.check_json_get(f'/day?date={date}', exp)
307 # post Todo of adopting Process, with make_type=full
308 self.post_exp_day([exp], {'make_type': 'full', 'new_todo': [1]})
309 exp.lib_get('Todo', 1)['children'] = [2]
310 exp.lib_set('Todo', [exp.todo_as_dict(2, 2)])
311 top_nodes = [{'todo': 1,
313 'children': [{'todo': 2,
316 exp.force('top_nodes', top_nodes)
317 self.check_json_get(f'/day?date={date}', exp)
318 # post another Todo of adopting Process, expect to adopt existing
319 self.post_exp_day([exp], {'make_type': 'full', 'new_todo': [1]})
320 exp.lib_set('Todo', [exp.todo_as_dict(3, 1, children=[2])])
321 top_nodes += [{'todo': 3,
323 'children': [{'todo': 2,
326 exp.force('top_nodes', top_nodes)
327 self.check_json_get(f'/day?date={date}', exp)
328 # post another Todo of adopting Process, make_type=empty
329 self.post_exp_day([exp], {'make_type': 'empty', 'new_todo': [1]})
330 exp.lib_set('Todo', [exp.todo_as_dict(4, 1)])
331 top_nodes += [{'todo': 4,
334 exp.force('top_nodes', top_nodes)
335 self.check_json_get(f'/day?date={date}', exp)
337 def test_POST_day_new_todo_order_commutative(self) -> None:
338 """Check that order of 'new_todo' values in POST /day don't matter."""
340 exp = ExpectedGetDay(date)
341 self.post_exp_process([exp], {}, 2)
342 self.post_exp_process([exp], {'new_top_step': 2}, 1)
343 exp.lib_set('ProcessStep', [exp.procstep_as_dict(1, 1, 2, None)])
344 # make-full-day-post batch of Todos of both Processes in one order …,
345 self.post_exp_day([exp], {'make_type': 'full', 'new_todo': [1, 2]})
346 top_nodes: list[dict[str, Any]] = [{'todo': 1,
348 'children': [{'todo': 2,
351 exp.force('top_nodes', top_nodes)
352 exp.lib_get('Todo', 1)['children'] = [2]
353 self.check_json_get(f'/day?date={date}', exp)
354 # … and then in the other, expecting same node tree / relations
355 exp.lib_del('Day', date)
358 day_post = {'make_type': 'full', 'new_todo': [2, 1]}
359 self.post_exp_day([exp], day_post, date)
360 exp.lib_del('Todo', 1)
361 exp.lib_del('Todo', 2)
362 top_nodes[0]['todo'] = 3 # was: 1
363 top_nodes[0]['children'][0]['todo'] = 4 # was: 2
364 exp.lib_get('Todo', 3)['children'] = [4]
365 self.check_json_get(f'/day?date={date}', exp)
367 def test_GET_day_with_conditions(self) -> None:
368 """Test GET /day displaying Conditions and their relations."""
370 exp = ExpectedGetDay(date)
371 # check non-referenced Conditions not shown
372 cond_posts = [{'is_active': 0, 'title': 'A', 'description': 'a'},
373 {'is_active': 1, 'title': 'B', 'description': 'b'}]
374 for i, cond_post in enumerate(cond_posts):
375 self.check_post(cond_post, f'/condition?id={i+1}')
376 self.check_json_get(f'/day?date={date}', exp)
377 # add Processes with Conditions, check Conditions now shown
378 for i, (c1, c2) in enumerate([(1, 2), (2, 1)]):
379 post = {'conditions': [c1], 'disables': [c1],
380 'blockers': [c2], 'enables': [c2]}
381 self.post_exp_process([exp], post, i+1)
382 for i, cond_post in enumerate(cond_posts):
383 exp.set_cond_from_post(i+1, cond_post)
384 self.check_json_get(f'/day?date={date}', exp)
385 # add Todos in relation to Conditions, check consequence relations
386 self.post_exp_day([exp], {'new_todo': [1, 2]})
387 self.check_json_get(f'/day?date={date}', exp)
389 def test_GET_calendar(self) -> None:
390 """Test GET /calendar responses based on various inputs, DB states."""
391 # check illegal date range delimiters
392 self.check_get('/calendar?start=foo', 400)
393 self.check_get('/calendar?end=foo', 400)
394 # check default range for expected selection/order without saved days
395 exp = ExpectedGetCalendar(-1, 366)
396 self.check_json_get('/calendar', exp)
397 self.check_json_get('/calendar?start=&end=', exp)
398 # check with named days as delimiters
399 exp = ExpectedGetCalendar(-1, +1)
400 self.check_json_get('/calendar?start=yesterday&end=tomorrow', exp)
401 # check zero-element range
402 exp = ExpectedGetCalendar(+1, 0)
403 self.check_json_get('/calendar?start=tomorrow&end=today', exp)
404 # check saved day shows up in results, proven by its comment
405 start_date = _testing_date_in_n_days(-5)
406 date = _testing_date_in_n_days(-2)
407 end_date = _testing_date_in_n_days(+5)
408 exp = ExpectedGetCalendar(-5, +5)
409 self.post_exp_day([exp], {'day_comment': 'foo'}, date)
410 url = f'/calendar?start={start_date}&end={end_date}'
411 self.check_json_get(url, exp)