home · contact · privacy
856ce9978dc1d12cb0f8fc1040f02257b21ddedb
[plomtask] / tests / days.py
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
7
8
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']
13
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)
21
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])
29
30
31 class TestsWithDB(TestCaseWithDB):
32     """Tests requiring DB, but not server setup."""
33     checked_class = Day
34     default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
35
36     def test_Day_by_date_range_filled(self) -> None:
37         """Test Day.by_date_range_filled."""
38         date1, date2, date3 = self.default_ids
39         day1 = Day(date1)
40         day2 = Day(date2)
41         day3 = Day(date3)
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),
46                          [day1, day2, day3])
47         # check first date range value excludes what's earlier
48         self.assertEqual(Day.by_date_range_filled(self.db_conn, date2, date3),
49                          [day2, day3])
50         # check second date range value excludes what's later
51         self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date2),
52                          [day1, day2])
53         # check swapped (impossible) date range returns emptiness
54         self.assertEqual(Day.by_date_range_filled(self.db_conn, date3, date1),
55                          [])
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),
64                          [day5, day6, day7])
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,
69                                                   'today', 'today'),
70                          [today])
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])
76
77
78 class TestsWithServer(TestCaseWithServer):
79     """Tests against our HTTP server/handler (and database)."""
80
81     @staticmethod
82     def todo_as_dict(id_: int = 1,
83                      process_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
92         d = {'id': id_,
93              'date': date,
94              'process_id': process_id,
95              'is_done': False,
96              'calendarize': False,
97              'comment': '',
98              'children': [],
99              'parents': [],
100              'effort': None,
101              'conditions': conditions if conditions else [],
102              'disables': disables if disables else [],
103              'blockers': blockers if blockers else [],
104              'enables': enables if enables else []}
105         return d
106
107     @staticmethod
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}
111
112     @staticmethod
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': []}
116         d: dict[str, object]
117         d = {'day': date,
118              'top_nodes': [],
119              'make_type': '',
120              'enablers_for': {},
121              'disablers_for': {},
122              'conditions_present': [],
123              'processes': [],
124              '_library': {'Day': TestsWithServer.as_refs([day])}}
125         return d
126
127     def post_day(self, params: str = '',
128                  form_data: None | dict[str, object] = None,
129                  redir_to: str = '',
130                  status: int = 302,
131                  ) -> None:
132         """POST /day?{params} with form_data."""
133         if not form_data:
134             form_data = {'day_comment': '', 'make_type': ''}
135         target = f'/day?{params}'
136         if not redir_to:
137             redir_to = f'{target}&make_type={form_data["make_type"]}'
138         self.check_post(form_data, target, status, redir_to)
139
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)
155         # check defined day
156         date = '2024-01-01'
157         expected = self.get_day_dict(date)
158         self.check_json_get(f'/day?date={date}', expected)
159         # check saved day
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)
176
177     def test_do_GET_day_with_processes_and_todos(self) -> None:
178         """Test GET /day displaying Processes and Todos."""
179         date = '2024-01-01'
180         # check Processes get displayed in ['processes'] and ['_library']
181         procs_expected = [self.proc_as_dict(1, 'foo', 'oof', 1.1),
182                           self.proc_as_dict(2, 'bar', 'rab', 0.9)]
183         for proc in procs_expected:
184             post = {}
185             assert isinstance(proc['_versioned'], dict)
186             for k in ('title', 'description', 'effort'):
187                 post[k] = proc['_versioned'][k][0]
188             assert isinstance(proc['id'], int)
189             self.post_process(proc['id'], post)
190         self.post_day(f'date={date}')
191         expected = self.get_day_dict(date)
192         expected['processes'] = self.as_id_list(procs_expected)
193         assert isinstance(expected['_library'], dict)
194         expected['_library']['Process'] = self.as_refs(procs_expected)
195         self.check_json_get(f'/day?date={date}', expected)
196         # post Todos of either process and check their display
197         post_day: dict[str, object]
198         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
199         self.post_day(f'date={date}', post_day)
200         todos = [self.todo_as_dict(1, 1, date), self.todo_as_dict(2, 2, date)]
201         expected['_library']['Todo'] = self.as_refs(todos)
202         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
203         nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
204         expected['top_nodes'] = nodes
205         self.check_json_get(f'/day?date={date}', expected)
206         # add a comment to one Todo and set the other's doneness and effort
207         post_day['new_todo'] = []
208         post_day['todo_id'] = [1, 2]
209         post_day['done'] = [2]
210         post_day['comment'] = ['FOO', '']
211         post_day['effort'] = ['2.3', '']
212         self.post_day(f'date={date}', post_day)
213         expected['_library']['Todo']['1']['comment'] = 'FOO'
214         expected['_library']['Todo']['1']['effort'] = 2.3
215         expected['_library']['Todo']['2']['is_done'] = True
216         self.check_json_get(f'/day?date={date}', expected)
217
218     def test_do_GET_day_with_conditions(self) -> None:
219         """Test GET /day displaying Conditions and their relations."""
220         # add Process with Conditions and their Todos, check display
221         # pylint: disable=too-many-locals
222         conds_expected = [self.cond_as_dict(1, False, ['A'], ['a']),
223                           self.cond_as_dict(2, True, ['B'], ['b'])]
224         for i, cond in enumerate(conds_expected):
225             post = {'is_active': cond['is_active']}
226             assert isinstance(cond['_versioned'], dict)
227             for k in ('title', 'description'):
228                 post[k] = cond['_versioned'][k][0]
229             self.check_post(post, f'/condition?id={i+1}', 302)
230         procs_expected = [self.proc_as_dict(1, 'foo', 'oof', 1.1),
231                           self.proc_as_dict(2, 'bar', 'rab', 0.9)]
232         cond_names = ('conditions', 'disables', 'blockers', 'enables')
233         cond_vals = ((1, 1, 2, 2), (2, 2, 1, 1))
234         for i, proc in enumerate(procs_expected):
235             post = {}
236             assert isinstance(proc['_versioned'], dict)
237             for k in ('title', 'description', 'effort'):
238                 post[k] = proc['_versioned'][k][0]
239             for j, cond_name in enumerate(cond_names):
240                 post[cond_name] = proc[cond_name] = [cond_vals[i][j]]
241             assert isinstance(proc['id'], int)
242             self.post_process(proc['id'], post)
243         date = '2024-01-01'
244         expected = self.get_day_dict(date)
245         expected['processes'] = self.as_id_list(procs_expected)
246         assert isinstance(expected['_library'], dict)
247         expected['_library']['Process'] = self.as_refs(procs_expected)
248         expected['_library']['Condition'] = self.as_refs(conds_expected)
249         self.post_day(f'date={date}')
250         self.check_json_get(f'/day?date={date}', expected)
251         # add Todos in relation to Conditions, check consequences
252         post_day: dict[str, object]
253         post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
254         self.post_day(f'date={date}', post_day)
255         todos = [self.todo_as_dict(1, 1, date, [1], [1], [2], [2]),
256                  self.todo_as_dict(2, 2, date, [2], [2], [1], [1])]
257         expected['_library']['Todo'] = self.as_refs(todos)
258         expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
259         nodes = [self.todo_node_as_dict(1), self.todo_node_as_dict(2)]
260         expected['top_nodes'] = nodes
261         expected['disablers_for'] = {'1': [1], '2': [2]}
262         expected['enablers_for'] = {'1': [2], '2': [1]}
263         expected['conditions_present'] = self.as_id_list(conds_expected)
264         self.check_json_get(f'/day?date={date}', expected)
265
266     def test_do_GET(self) -> None:
267         """Test /day and /calendar response codes, and / redirect."""
268         self.check_get('/calendar', 200)
269         self.check_get('/calendar?start=&end=', 200)
270         self.check_get('/calendar?start=today&end=today', 200)
271         self.check_get('/calendar?start=2024-01-01&end=2025-01-01', 200)
272         self.check_get('/calendar?start=foo', 400)
273
274     def test_do_POST_day(self) -> None:
275         """Test POST /day."""
276         form_data = {'day_comment': '', 'make_type': 'full'}
277         self.check_post(form_data, '/day', 400)
278         self.check_post(form_data, '/day?date=foo', 400)
279         self.check_post(form_data, '/day?date=2024-01-01&make_type=full', 302)
280         self.check_post({'foo': ''}, '/day?date=2024-01-01', 400)