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 assert isinstance(expected['_library'], dict)
160 self.check_json_get(f'/day?date={date}', expected)
162 post: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
163 self.post_day(f'date={date}', post)
164 expected['_library']['Day'][date]['comment'] = post['day_comment']
165 self.check_json_get(f'/day?date={date}', expected)
166 # check GET parameter to GET requests affects immediate reply, but …
167 expected['make_type'] = 'bar'
168 self.check_json_get(f'/day?date={date}&make_type=bar', expected)
169 # … not any following, …
170 expected['make_type'] = ''
171 self.check_json_get(f'/day?date={date}', expected)
172 # … not even when part of a POST request
173 post['make_type'] = 'foo'
174 self.post_day(f'date={date}', post)
175 self.check_json_get(f'/day?date={date}', expected)
178 def post_batch(list_of_args: list[list[object]],
179 names_of_simples: list[str],
180 names_of_versioneds: list[str],
181 f_as_dict: Callable[..., dict[str, object]],
182 f_to_post: Callable[..., None | dict[str, object]]
183 ) -> list[dict[str, object]]:
184 """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
186 for args in list_of_args:
187 expecteds += [f_as_dict(*args)]
188 for expected in expecteds:
189 assert isinstance(expected['_versioned'], dict)
191 for name in names_of_simples:
192 post[name] = expected[name]
193 for name in names_of_versioneds:
194 post[name] = expected['_versioned'][name][0]
195 f_to_post(expected['id'], post)
198 def post_cond(self, id_: int, form_data: dict[str, object]) -> None:
199 """POST Condition of id_ with form_data."""
200 self.check_post(form_data, f'/condition?id={id_}', 302)
202 def test_do_GET_day_with_processes_and_todos(self) -> None:
203 """Test GET /day displaying Processes and Todos."""
205 # check Processes get displayed in ['processes'] and ['_library']
206 procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
207 procs_expected = self.post_batch(procs_data, [],
208 ['title', 'description', 'effort'],
209 self.proc_as_dict, self.post_process)
210 expected = self.get_day_dict(date)
211 assert isinstance(expected['_library'], dict)
212 expected['processes'] = self.as_id_list(procs_expected)
213 expected['_library']['Process'] = self.as_refs(procs_expected)
214 self.post_day(f'date={date}')
215 self.check_json_get(f'/day?date={date}', expected)
216 # post Todos of either process and check their display
217 post_day: dict[str, object]
218 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
219 todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
220 expected['_library']['Todo'] = self.as_refs(todos)
221 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
222 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
223 expected['top_nodes'] = nodes
224 self.post_day(f'date={date}', post_day)
225 self.check_json_get(f'/day?date={date}', expected)
226 # add a comment to one Todo and set the other's doneness and effort
227 post_day['new_todo'] = []
228 post_day['todo_id'] = [1, 2]
229 post_day['done'] = [2]
230 post_day['comment'] = ['FOO', '']
231 post_day['effort'] = ['2.3', '']
232 expected['_library']['Todo']['1']['comment'] = 'FOO'
233 expected['_library']['Todo']['1']['effort'] = 2.3
234 expected['_library']['Todo']['2']['is_done'] = True
235 self.post_day(f'date={date}', post_day)
236 self.check_json_get(f'/day?date={date}', expected)
238 def test_do_GET_day_with_conditions(self) -> None:
239 """Test GET /day displaying Conditions and their relations."""
240 # add Process with Conditions and their Todos, check display
241 conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
242 conds_expected = self.post_batch(conds_data, ['is_active'],
243 ['title', 'description'],
244 self.cond_as_dict, self.post_cond)
245 cond_names = ['conditions', 'disables', 'blockers', 'enables']
246 procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
247 [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
248 procs_expected = self.post_batch(procs_data, cond_names,
249 ['title', 'description', 'effort'],
250 self.proc_as_dict, self.post_process)
252 expected = self.get_day_dict(date)
253 assert isinstance(expected['_library'], dict)
254 expected['processes'] = self.as_id_list(procs_expected)
255 expected['_library']['Process'] = self.as_refs(procs_expected)
256 expected['_library']['Condition'] = self.as_refs(conds_expected)
257 self.post_day(f'date={date}')
258 self.check_json_get(f'/day?date={date}', expected)
259 # add Todos in relation to Conditions, check consequences
260 post_day: dict[str, object]
261 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
262 todos = [self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
263 self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
264 expected['_library']['Todo'] = self.as_refs(todos)
265 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
266 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
267 expected['top_nodes'] = nodes
268 expected['disablers_for'] = {'1': [1], '2': [2]}
269 expected['enablers_for'] = {'1': [2], '2': [1]}
270 expected['conditions_present'] = self.as_id_list(conds_expected)
271 self.post_day(f'date={date}', post_day)
272 self.check_json_get(f'/day?date={date}', expected)
274 def test_do_GET(self) -> None:
275 """Test /day and /calendar response codes, and / redirect."""
276 self.check_get('/calendar', 200)
277 self.check_get('/calendar?start=&end=', 200)
278 self.check_get('/calendar?start=today&end=today', 200)
279 self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
280 self.check_get('/calendar?start=foo', 400)
282 def test_do_POST_day(self) -> None:
283 """Test POST /day."""
284 form_data = {'day_comment': '', 'make_type': 'full'}
285 self.check_post(form_data, '/day', 400)
286 self.check_post(form_data, '/day?date=foo', 400)
287 self.check_post(form_data, '/day?date=2024-01-01&make_type=full', 302)
288 self.check_post({'foo': ''}, '/day?date=2024-01-01', 400)