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 of a POST does not affect reply to param-free GET
167 post['make_type'] = 'foo'
168 self.post_day(f'date={date}', post)
169 self.check_json_get(f'/day?date={date}', expected)
170 expected['make_type'] = 'bar'
171 self.check_json_get(f'/day?date={date}&make_type=bar', expected)
173 def test_do_GET_day_with_todos_flat(self) -> None:
174 """Test GET /day displaying posted Todos (no tree structure)."""
175 # post two Todos of differing processes and check their display
177 self.post_day(f'date={date}')
178 expected = self.get_day_dict(date)
179 post_proc1 = {'title': 'foo', 'description': 'oof', 'effort': 1.1}
180 post_proc2 = {'title': 'bar', 'description': 'rab', 'effort': 0.9}
181 procs: list[dict[str, object]] = [{}, {}]
182 for i, post in enumerate([post_proc1, post_proc2]):
183 self.post_process(i+1, post)
184 assert isinstance(post['title'], str)
185 assert isinstance(post['description'], str)
186 assert isinstance(post['effort'], float)
187 procs[i] = self.proc_as_dict(i+1, post['title'],
188 post['description'], post['effort'])
189 post_day: dict[str, object]
190 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
191 self.post_day(f'date={date}', post_day)
192 assert isinstance(expected['_library'], dict)
193 expected['_library']['Process'] = self.as_refs(procs)
194 expected['processes'] = self.as_id_list(procs)
195 todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
196 expected['_library']['Todo'] = self.as_refs(todos)
197 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
198 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
199 expected['top_nodes'] = nodes
200 self.check_json_get(f'/day?date={date}', expected)
201 # add a comment to one Todo and set the other's doneness and effort
202 post_day['new_todo'] = []
203 post_day['todo_id'] = [1, 2]
204 post_day['done'] = [2]
205 post_day['comment'] = ['FOO', '']
206 post_day['effort'] = ['2.3', '']
207 self.post_day(f'date={date}', post_day)
208 expected['_library']['Todo']['1']['comment'] = 'FOO'
209 expected['_library']['Todo']['1']['effort'] = 2.3
210 expected['_library']['Todo']['2']['is_done'] = True
211 self.check_json_get(f'/day?date={date}', expected)
213 def test_do_GET_day_with_conditions(self) -> None:
214 """Test GET /day displaying Conditions and their relations."""
215 # add Process with Conditions and their Todos, check display
216 # pylint: disable=too-many-locals
217 post_cond1 = {'title': 'A', 'description': '', 'is_active': False}
218 post_cond2 = {'title': 'B', 'description': '', 'is_active': True}
219 conds: list[dict[str, object]] = [{}, {}]
220 for i, post in enumerate([post_cond1, post_cond2]):
221 self.check_post(post, f'/condition?id={i+1}', 302)
222 assert isinstance(post['is_active'], bool)
223 assert isinstance(post['title'], str)
224 assert isinstance(post['description'], str)
225 conds[i] = self.cond_as_dict(i+1, post['is_active'],
227 [post['description']])
228 post_proc1 = {'title': 'foo', 'description': 'oof', 'effort': 1.1}
229 post_proc2 = {'title': 'bar', 'description': 'rab', 'effort': 0.9}
230 procs: list[dict[str, object]] = [{}, {}]
231 names_input = ('condition', 'disables', 'blocker', 'enables')
232 names_output = ('conditions', 'disables', 'blockers', 'enables')
233 cond_vals = ((1, 1, 2, 2), (2, 2, 1, 1))
234 for i, post in enumerate([post_proc1, post_proc2]):
235 assert isinstance(post['title'], str)
236 assert isinstance(post['description'], str)
237 assert isinstance(post['effort'], float)
238 procs[i] = self.proc_as_dict(i+1, post['title'],
239 post['description'], post['effort'])
240 for j, name_input in enumerate(names_input):
241 post[name_input] = [cond_vals[i][j]]
242 procs[i][names_output[j]] = [cond_vals[i][j]]
243 self.post_process(i+1, post)
245 expected = self.get_day_dict(date)
246 expected['processes'] = self.as_id_list(procs)
247 assert isinstance(expected['_library'], dict)
248 expected['_library']['Process'] = self.as_refs(procs)
249 expected['_library']['Condition'] = self.as_refs(conds)
250 self.post_day(f'date={date}')
251 self.check_json_get(f'/day?date={date}', expected)
252 # add Todos in relation to Conditions, check consequences
253 post_day: dict[str, object]
254 post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
255 self.post_day(f'date={date}', post_day)
256 todos = [self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
257 self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
258 expected['_library']['Todo'] = self.as_refs(todos)
259 expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
260 nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
261 expected['top_nodes'] = nodes
262 expected['disablers_for'] = {'1': [1], '2': [2]}
263 expected['enablers_for'] = {'1': [2], '2': [1]}
264 expected['conditions_present'] = self.as_id_list(conds)
265 self.check_json_get(f'/day?date={date}', expected)
267 def test_do_GET(self) -> None:
268 """Test /day and /calendar response codes, and / redirect."""
269 self.check_get('/calendar', 200)
270 self.check_get('/calendar?start=&end=', 200)
271 self.check_get('/calendar?start=today&end=today', 200)
272 self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
273 self.check_get('/calendar?start=foo', 400)
275 def test_do_POST_day(self) -> None:
276 """Test POST /day."""
277 form_data = {'day_comment': '', 'make_type': 'full'}
278 self.check_post(form_data, '/day', 400)
279 self.check_post(form_data, '/day?date=foo', 400)
280 self.check_post(form_data, '/day?date=2024-01-01&make_type=full', 302)
281 self.check_post({'foo': ''}, '/day?date=2024-01-01', 400)