1 """Test Days module."""
2 from unittest import TestCase
3 from datetime import datetime
4 from tests.utils import TestCaseWithDB, TestCaseWithServer
5 from plomtask.dating import date_in_n_days
6 from plomtask.days import Day
9 class TestsSansDB(TestCase):
10 """Days module tests not requiring DB setup."""
11 legal_ids = ['2024-01-01']
12 illegal_ids = ['foo', '2024-02-30', '2024-02-01 23:00:00']
14 def test_Day_datetime_weekday_neighbor_dates(self) -> None:
15 """Test Day's date parsing."""
16 self.assertEqual(datetime(2024, 5, 1), Day('2024-05-01').datetime)
17 self.assertEqual('Sunday', Day('2024-03-17').weekday)
18 self.assertEqual('March', Day('2024-03-17').month_name)
19 self.assertEqual('2023-12-31', Day('2024-01-01').prev_date)
20 self.assertEqual('2023-03-01', Day('2023-02-28').next_date)
22 def test_Day_sorting(self) -> None:
23 """Test sorting by .__lt__ and Day.__eq__."""
24 day1 = Day('2024-01-01')
25 day2 = Day('2024-01-02')
26 day3 = Day('2024-01-03')
27 days = [day3, day1, day2]
28 self.assertEqual(sorted(days), [day1, day2, day3])
31 class TestsWithDB(TestCaseWithDB):
32 """Tests requiring DB, but not server setup."""
34 default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
36 def test_Day_by_date_range_filled(self) -> None:
37 """Test Day.by_date_range_filled."""
38 date1, date2, date3 = self.default_ids
42 for day in [day1, day2, day3]:
43 day.save(self.db_conn)
44 # check date range includes limiter days
45 self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date3),
47 # check first date range value excludes what's earlier
48 self.assertEqual(Day.by_date_range_filled(self.db_conn, date2, date3),
50 # check second date range value excludes what's later
51 self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date2),
53 # check swapped (impossible) date range returns emptiness
54 self.assertEqual(Day.by_date_range_filled(self.db_conn, date3, date1),
56 # check fill_gaps= instantiates unsaved dates within date range
57 # (but does not store them)
58 day5 = Day('2024-01-05')
59 day6 = Day('2024-01-06')
60 day6.save(self.db_conn)
61 day7 = Day('2024-01-07')
62 self.assertEqual(Day.by_date_range_filled(self.db_conn,
63 day5.date, day7.date),
65 self.check_identity_with_cache_and_db([day1, day2, day3, day6])
66 # check 'today' is interpreted as today's date
67 today = Day(date_in_n_days(0))
68 self.assertEqual(Day.by_date_range_filled(self.db_conn,
71 prev_day = Day(date_in_n_days(-1))
72 next_day = Day(date_in_n_days(1))
73 self.assertEqual(Day.by_date_range_filled(self.db_conn,
74 'yesterday', 'tomorrow'),
75 [prev_day, today, next_day])
78 class TestsWithServer(TestCaseWithServer):
79 """Tests against our HTTP server/handler (and database)."""
82 def todo_as_dict(id_: int = 1,
84 date: str = '2024-01-01',
85 conditions: None | list[int] = None,
86 disables: None | list[int] = None,
87 blockers: None | list[int] = None,
88 enables: None | list[int] = None
89 ) -> dict[str, object]:
90 """Return JSON of Process to expect."""
91 # pylint: disable=too-many-arguments
94 'process_id': process_id,
101 'conditions': conditions if conditions else [],
102 'disables': disables if disables else [],
103 'blockers': blockers if blockers else [],
104 'enables': enables if enables else []}
108 def todo_node_as_dict(todo_id: int) -> dict[str, object]:
109 """Return JSON of TodoNode to expect."""
110 return {'children': [], 'seen': False, 'todo': todo_id}
113 def get_day_dict(date: str) -> dict[str, object]:
114 """Return JSON of GET /day to expect."""
115 day: dict[str, object] = {'id': date, 'comment': '', 'todos': []}
122 'conditions_present': [],
124 '_library': {'Day': TestsWithServer.as_refs([day])}}
127 def post_day(self, params: str = '',
128 form_data: None | dict[str, object] = None,
132 """POST /day?{params} with form_data."""
134 form_data = {'day_comment': '', 'make_type': ''}
135 target = f'/day?{params}'
137 redir_to = f'{target}&make_type={form_data["make_type"]}'
138 self.check_post(form_data, target, status, redir_to)
140 def test_do_GET_day_basics(self) -> None:
141 """Test GET /day basics (no Todos)."""
142 # check undefined day
143 date = date_in_n_days(0)
144 expected = self.get_day_dict(date)
145 self.check_json_get('/day', expected)
146 # check "today", "yesterday", "tomorrow" days
147 self.check_json_get('/day?date=today', expected)
148 expected = self.get_day_dict(date_in_n_days(1))
149 self.check_json_get('/day?date=tomorrow', expected)
150 expected = self.get_day_dict(date_in_n_days(-1))
151 self.check_json_get('/day?date=yesterday', expected)
152 # check wrong day strings
153 self.check_get('/day?date=foo', 400)
154 self.check_get('/day?date=2024-02-30', 400)
157 expected = self.get_day_dict(date)
158 self.check_json_get(f'/day?date={date}', expected)
160 post: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
161 self.post_day(f'date={date}', post)
162 assert isinstance(expected['_library'], dict)
163 day = expected['_library']['Day'][date]
164 day['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)
177 def test_do_GET_day_with_processes_and_todos(self) -> None:
178 """Test GET /day displaying Processes and Todos."""
180 # check Processes get displayed in ['processes'] and ['_library']
181 post_proc1 = {'title': 'foo', 'description': 'oof', 'effort': 1.1}
182 post_proc2 = {'title': 'bar', 'description': 'rab', 'effort': 0.9}
183 procs_expected: list[dict[str, object]] = [{}, {}]
184 for i, post in enumerate([post_proc1, post_proc2]):
185 self.post_process(i+1, post)
186 assert isinstance(post['title'], str)
187 assert isinstance(post['description'], str)
188 assert isinstance(post['effort'], float)
189 procs_expected[i] = self.proc_as_dict(i+1, post['title'],
192 self.post_day(f'date={date}')
193 expected = self.get_day_dict(date)
194 expected['processes'] = self.as_id_list(procs_expected)
195 assert isinstance(expected['_library'], dict)
196 expected['_library']['Process'] = self.as_refs(procs_expected)
197 self.check_json_get(f'/day?date={date}', expected)
198 # post Todos of either process and check their display
199 post_day: dict[str, object]
200 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
201 self.post_day(f'date={date}', post_day)
202 todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
203 expected['_library']['Todo'] = self.as_refs(todos)
204 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
205 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
206 expected['top_nodes'] = nodes
207 self.check_json_get(f'/day?date={date}', expected)
208 # add a comment to one Todo and set the other's doneness and effort
209 post_day['new_todo'] = []
210 post_day['todo_id'] = [1, 2]
211 post_day['done'] = [2]
212 post_day['comment'] = ['FOO', '']
213 post_day['effort'] = ['2.3', '']
214 self.post_day(f'date={date}', post_day)
215 expected['_library']['Todo']['1']['comment'] = 'FOO'
216 expected['_library']['Todo']['1']['effort'] = 2.3
217 expected['_library']['Todo']['2']['is_done'] = True
218 self.check_json_get(f'/day?date={date}', expected)
220 def test_do_GET_day_with_conditions(self) -> None:
221 """Test GET /day displaying Conditions and their relations."""
222 # add Process with Conditions and their Todos, check display
223 # pylint: disable=too-many-locals
224 post_cond1 = {'title': 'A', 'description': '', 'is_active': False}
225 post_cond2 = {'title': 'B', 'description': '', 'is_active': True}
226 conds: list[dict[str, object]] = [{}, {}]
227 for i, post in enumerate([post_cond1, post_cond2]):
228 self.check_post(post, f'/condition?id={i+1}', 302)
229 assert isinstance(post['is_active'], bool)
230 assert isinstance(post['title'], str)
231 assert isinstance(post['description'], str)
232 conds[i] = self.cond_as_dict(i+1, post['is_active'],
234 [post['description']])
235 post_proc1 = {'title': 'foo', 'description': 'oof', 'effort': 1.1}
236 post_proc2 = {'title': 'bar', 'description': 'rab', 'effort': 0.9}
237 procs: list[dict[str, object]] = [{}, {}]
238 cond_names = ('conditions', 'disables', 'blockers', 'enables')
239 cond_vals = ((1, 1, 2, 2), (2, 2, 1, 1))
240 for i, post in enumerate([post_proc1, post_proc2]):
241 assert isinstance(post['title'], str)
242 assert isinstance(post['description'], str)
243 assert isinstance(post['effort'], float)
244 procs[i] = self.proc_as_dict(i+1, post['title'],
245 post['description'], post['effort'])
246 for j, cond_name in enumerate(cond_names):
247 post[cond_name] = [cond_vals[i][j]]
248 procs[i][cond_name] = [cond_vals[i][j]]
249 self.post_process(i+1, post)
251 expected = self.get_day_dict(date)
252 expected['processes'] = self.as_id_list(procs)
253 assert isinstance(expected['_library'], dict)
254 expected['_library']['Process'] = self.as_refs(procs)
255 expected['_library']['Condition'] = self.as_refs(conds)
256 self.post_day(f'date={date}')
257 self.check_json_get(f'/day?date={date}', expected)
258 # add Todos in relation to Conditions, check consequences
259 post_day: dict[str, object]
260 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
261 self.post_day(f'date={date}', post_day)
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)
271 self.check_json_get(f'/day?date={date}', expected)
273 def test_do_GET(self) -> None:
274 """Test /day and /calendar response codes, and / redirect."""
275 self.check_get('/calendar', 200)
276 self.check_get('/calendar?start=&end=', 200)
277 self.check_get('/calendar?start=today&end=today', 200)
278 self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
279 self.check_get('/calendar?start=foo', 400)
281 def test_do_POST_day(self) -> None:
282 """Test POST /day."""
283 form_data = {'day_comment': '', 'make_type': 'full'}
284 self.check_post(form_data, '/day', 400)
285 self.check_post(form_data, '/day?date=foo', 400)
286 self.check_post(form_data, '/day?date=2024-01-01&make_type=full', 302)
287 self.check_post({'foo': ''}, '/day?date=2024-01-01', 400)