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
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']
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)
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])
32 class TestsWithDB(TestCaseWithDB):
33 """Tests requiring DB, but not server setup."""
35 default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
37 def test_Day_by_date_range_filled(self) -> None:
38 """Test Day.by_date_range_filled."""
39 date1, date2, date3 = self.default_ids
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),
48 # check first date range value excludes what's earlier
49 self.assertEqual(Day.by_date_range_filled(self.db_conn, date2, date3),
51 # check second date range value excludes what's later
52 self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date2),
54 # check swapped (impossible) date range returns emptiness
55 self.assertEqual(Day.by_date_range_filled(self.db_conn, date3, date1),
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),
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,
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])
79 class TestsWithServer(TestCaseWithServer):
80 """Tests against our HTTP server/handler (and database)."""
83 def todo_as_dict(id_: int = 1,
85 date: str = '2024-01-01',
86 conditions: None | list[int] = None,
87 disables: None | list[int] = None,
88 blockers: None | list[int] = None,
89 enables: None | list[int] = None
90 ) -> dict[str, object]:
91 """Return JSON of Process to expect."""
92 # pylint: disable=too-many-arguments
95 'process_id': process_id,
102 'conditions': conditions if conditions else [],
103 'disables': disables if disables else [],
104 'blockers': blockers if blockers else [],
105 'enables': enables if enables else []}
109 def todo_node_as_dict(todo_id: int) -> dict[str, object]:
110 """Return JSON of TodoNode to expect."""
111 return {'children': [], 'seen': False, 'todo': todo_id}
114 def get_day_dict(date: str) -> dict[str, object]:
115 """Return JSON of GET /day to expect."""
116 day: dict[str, object] = {'id': date, 'comment': '', 'todos': []}
123 'conditions_present': [],
125 '_library': {'Day': TestsWithServer.as_refs([day])}}
128 def post_day(self, params: str = '',
129 form_data: None | dict[str, object] = None,
133 """POST /day?{params} with form_data."""
135 form_data = {'day_comment': '', 'make_type': ''}
136 target = f'/day?{params}'
138 redir_to = f'{target}&make_type={form_data["make_type"]}'
139 self.check_post(form_data, target, status, redir_to)
141 def test_do_GET_day_basics(self) -> None:
142 """Test GET /day basics (no Todos)."""
143 # check undefined day
144 date = date_in_n_days(0)
145 expected = self.get_day_dict(date)
146 self.check_json_get('/day', expected)
147 # check "today", "yesterday", "tomorrow" days
148 self.check_json_get('/day?date=today', expected)
149 expected = self.get_day_dict(date_in_n_days(1))
150 self.check_json_get('/day?date=tomorrow', expected)
151 expected = self.get_day_dict(date_in_n_days(-1))
152 self.check_json_get('/day?date=yesterday', expected)
153 # check wrong day strings
154 self.check_get('/day?date=foo', 400)
155 self.check_get('/day?date=2024-02-30', 400)
158 expected = self.get_day_dict(date)
159 self.check_json_get(f'/day?date={date}', expected)
161 post: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
162 self.post_day(f'date={date}', post)
163 assert isinstance(expected['_library'], dict)
164 day = expected['_library']['Day'][date]
165 day['comment'] = post['day_comment']
166 self.check_json_get(f'/day?date={date}', expected)
167 # check GET parameter to GET requests affects immediate reply, but …
168 expected['make_type'] = 'bar'
169 self.check_json_get(f'/day?date={date}&make_type=bar', expected)
170 # … not any following, …
171 expected['make_type'] = ''
172 self.check_json_get(f'/day?date={date}', expected)
173 # … not even when part of a POST request
174 post['make_type'] = 'foo'
175 self.post_day(f'date={date}', post)
176 self.check_json_get(f'/day?date={date}', expected)
179 def post_batch(list_of_args: list[list[object]],
180 names_of_simples: list[str],
181 names_of_versioneds: list[str],
182 f_as_dict: Callable[..., dict[str, object]],
183 f_to_post: Callable[..., None | dict[str, object]]
184 ) -> list[dict[str, object]]:
185 """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
187 for args in list_of_args:
188 expecteds += [f_as_dict(*args)]
189 for expected in expecteds:
190 assert isinstance(expected['_versioned'], dict)
192 for name in names_of_simples:
193 post[name] = expected[name]
194 for name in names_of_versioneds:
195 post[name] = expected['_versioned'][name][0]
196 f_to_post(expected['id'], post)
199 def post_cond(self, id_: int, form_data: dict[str, object]) -> None:
200 """POST Condition of id_ with form_data."""
201 self.check_post(form_data, f'/condition?id={id_}', 302)
203 def test_do_GET_day_with_processes_and_todos(self) -> None:
204 """Test GET /day displaying Processes and Todos."""
206 # check Processes get displayed in ['processes'] and ['_library']
207 procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
208 procs_expected = self.post_batch(procs_data, [],
209 ['title', 'description', 'effort'],
210 self.proc_as_dict, self.post_process)
211 self.post_day(f'date={date}')
212 expected = self.get_day_dict(date)
213 assert isinstance(expected['_library'], dict)
214 expected['processes'] = self.as_id_list(procs_expected)
215 expected['_library']['Process'] = self.as_refs(procs_expected)
216 self.check_json_get(f'/day?date={date}', expected)
217 # post Todos of either process and check their display
218 post_day: dict[str, object]
219 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
220 self.post_day(f'date={date}', post_day)
221 todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
222 expected['_library']['Todo'] = self.as_refs(todos)
223 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
224 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
225 expected['top_nodes'] = nodes
226 self.check_json_get(f'/day?date={date}', expected)
227 # add a comment to one Todo and set the other's doneness and effort
228 post_day['new_todo'] = []
229 post_day['todo_id'] = [1, 2]
230 post_day['done'] = [2]
231 post_day['comment'] = ['FOO', '']
232 post_day['effort'] = ['2.3', '']
233 self.post_day(f'date={date}', post_day)
234 expected['_library']['Todo']['1']['comment'] = 'FOO'
235 expected['_library']['Todo']['1']['effort'] = 2.3
236 expected['_library']['Todo']['2']['is_done'] = True
237 self.check_json_get(f'/day?date={date}', expected)
239 def test_do_GET_day_with_conditions(self) -> None:
240 """Test GET /day displaying Conditions and their relations."""
241 # add Process with Conditions and their Todos, check display
242 conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
243 conds_expected = self.post_batch(conds_data, ['is_active'],
244 ['title', 'description'],
245 self.cond_as_dict, self.post_cond)
246 cond_names = ['conditions', 'disables', 'blockers', 'enables']
247 procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
248 [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
249 procs_expected = self.post_batch(procs_data, cond_names,
250 ['title', 'description', 'effort'],
251 self.proc_as_dict, self.post_process)
253 expected = self.get_day_dict(date)
254 assert isinstance(expected['_library'], dict)
255 expected['processes'] = self.as_id_list(procs_expected)
256 expected['_library']['Process'] = self.as_refs(procs_expected)
257 expected['_library']['Condition'] = self.as_refs(conds_expected)
258 self.post_day(f'date={date}')
259 self.check_json_get(f'/day?date={date}', expected)
260 # add Todos in relation to Conditions, check consequences
261 post_day: dict[str, object]
262 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
263 self.post_day(f'date={date}', post_day)
264 todos = [self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
265 self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
266 expected['_library']['Todo'] = self.as_refs(todos)
267 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
268 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
269 expected['top_nodes'] = nodes
270 expected['disablers_for'] = {'1': [1], '2': [2]}
271 expected['enablers_for'] = {'1': [2], '2': [1]}
272 expected['conditions_present'] = self.as_id_list(conds_expected)
273 self.check_json_get(f'/day?date={date}', expected)
275 def test_do_GET(self) -> None:
276 """Test /day and /calendar response codes, and / redirect."""
277 self.check_get('/calendar', 200)
278 self.check_get('/calendar?start=&end=', 200)
279 self.check_get('/calendar?start=today&end=today', 200)
280 self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
281 self.check_get('/calendar?start=foo', 400)
283 def test_do_POST_day(self) -> None:
284 """Test POST /day."""
285 form_data = {'day_comment': '', 'make_type': 'full'}
286 self.check_post(form_data, '/day', 400)
287 self.check_post(form_data, '/day?date=foo', 400)
288 self.check_post(form_data, '/day?date=2024-01-01&make_type=full', 302)
289 self.check_post({'foo': ''}, '/day?date=2024-01-01', 400)