"""Test Days module."""
from unittest import TestCase
from datetime import datetime
+from typing import Callable
from tests.utils import TestCaseWithDB, TestCaseWithServer
-from plomtask.days import Day, todays_date
-from plomtask.exceptions import BadFormatException, NotFoundException
+from plomtask.dating import date_in_n_days
+from plomtask.days import Day
class TestsSansDB(TestCase):
"""Days module tests not requiring DB setup."""
+ legal_ids = ['2024-01-01']
+ illegal_ids = ['foo', '2024-02-30', '2024-02-01 23:00:00']
- def test_Day_dates(self) -> None:
- """Test Day's date format."""
- with self.assertRaises(BadFormatException):
- Day('foo')
- with self.assertRaises(BadFormatException):
- Day('2024-02-30')
- with self.assertRaises(BadFormatException):
- Day('2024-02-01 23:00:00')
- self.assertEqual(datetime(2024, 1, 1), Day('2024-01-01').datetime)
+ def test_Day_datetime_weekday_neighbor_dates(self) -> None:
+ """Test Day's date parsing."""
+ self.assertEqual(datetime(2024, 5, 1), Day('2024-05-01').datetime)
+ self.assertEqual('Sunday', Day('2024-03-17').weekday)
+ self.assertEqual('March', Day('2024-03-17').month_name)
+ self.assertEqual('2023-12-31', Day('2024-01-01').prev_date)
+ self.assertEqual('2023-03-01', Day('2023-02-28').next_date)
def test_Day_sorting(self) -> None:
- """Test Day.__lt__."""
+ """Test sorting by .__lt__ and Day.__eq__."""
day1 = Day('2024-01-01')
day2 = Day('2024-01-02')
day3 = Day('2024-01-03')
days = [day3, day1, day2]
self.assertEqual(sorted(days), [day1, day2, day3])
- def test_Day_weekday(self) -> None:
- """Test Day.weekday."""
- self.assertEqual(Day('2024-03-17').weekday, 'Sunday')
-
class TestsWithDB(TestCaseWithDB):
- """Days module tests not requiring DB setup."""
+ """Tests requiring DB, but not server setup."""
+ checked_class = Day
+ default_ids = ('2024-01-01', '2024-01-02', '2024-01-03')
- def test_Day_by_date(self) -> None:
- """Test Day.by_date()."""
- with self.assertRaises(NotFoundException):
- Day.by_date(self.db_conn, '2024-01-01')
- Day('2024-01-01').save(self.db_conn)
- self.assertEqual(Day('2024-01-01'),
- Day.by_date(self.db_conn, '2024-01-01'))
- with self.assertRaises(NotFoundException):
- Day.by_date(self.db_conn, '2024-01-02')
- self.assertEqual(Day('2024-01-02'),
- Day.by_date(self.db_conn, '2024-01-02', create=True))
-
- def test_Day_all(self) -> None:
- """Test Day.all(), especially in regards to date range filtering."""
- day1 = Day('2024-01-01')
- day2 = Day('2024-01-02')
- day3 = Day('2024-01-03')
- day1.save(self.db_conn)
- day2.save(self.db_conn)
- day3.save(self.db_conn)
- self.assertEqual(Day.all(self.db_conn), [day1, day2, day3])
- self.assertEqual(Day.all(self.db_conn, ('', '')),
- [day1, day2, day3])
- self.assertEqual(Day.all(self.db_conn, ('2024-01-01', '2024-01-03')),
+ def test_Day_by_date_range_filled(self) -> None:
+ """Test Day.by_date_range_filled."""
+ date1, date2, date3 = self.default_ids
+ day1 = Day(date1)
+ day2 = Day(date2)
+ day3 = Day(date3)
+ for day in [day1, day2, day3]:
+ day.save(self.db_conn)
+ # check date range includes limiter days
+ self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date3),
[day1, day2, day3])
- self.assertEqual(Day.all(self.db_conn, ('2024-01-02', '2024-01-03')),
+ # check first date range value excludes what's earlier
+ self.assertEqual(Day.by_date_range_filled(self.db_conn, date2, date3),
[day2, day3])
- self.assertEqual(Day.all(self.db_conn, ('2024-01-03', '')),
- [day3])
- self.assertEqual(Day.all(self.db_conn, ('2024-01-01', '')),
- [day1, day2, day3])
- self.assertEqual(Day.all(self.db_conn, ('', '2024-01-02')),
+ # check second date range value excludes what's later
+ self.assertEqual(Day.by_date_range_filled(self.db_conn, date1, date2),
[day1, day2])
- self.assertEqual(Day.all(self.db_conn, ('2024-01-03', '2024-01-01')),
+ # check swapped (impossible) date range returns emptiness
+ self.assertEqual(Day.by_date_range_filled(self.db_conn, date3, date1),
[])
- day4 = Day('2024-01-04')
+ # check fill_gaps= instantiates unsaved dates within date range
+ # (but does not store them)
day5 = Day('2024-01-05')
day6 = Day('2024-01-06')
day6.save(self.db_conn)
- self.assertEqual(Day.all(self.db_conn, ('2024-01-02', '2024-01-07'),
- fill_gaps=True),
- [day2, day3, day4, day5, day6])
- today = Day(todays_date())
- today.save(self.db_conn)
- self.assertEqual(Day.all(self.db_conn, ('today', 'today')), [today])
-
- def test_Day_neighbor_dates(self) -> None:
- """Test Day.prev_date and Day.next_date."""
- self.assertEqual(Day('2024-01-01').prev_date, '2023-12-31')
- self.assertEqual(Day('2023-02-28').next_date, '2023-03-01')
+ day7 = Day('2024-01-07')
+ self.assertEqual(Day.by_date_range_filled(self.db_conn,
+ day5.date, day7.date),
+ [day5, day6, day7])
+ self.check_identity_with_cache_and_db([day1, day2, day3, day6])
+ # check 'today' is interpreted as today's date
+ today = Day(date_in_n_days(0))
+ self.assertEqual(Day.by_date_range_filled(self.db_conn,
+ 'today', 'today'),
+ [today])
+ prev_day = Day(date_in_n_days(-1))
+ next_day = Day(date_in_n_days(1))
+ self.assertEqual(Day.by_date_range_filled(self.db_conn,
+ 'yesterday', 'tomorrow'),
+ [prev_day, today, next_day])
class TestsWithServer(TestCaseWithServer):
"""Tests against our HTTP server/handler (and database)."""
- def test_do_GET(self) -> None:
- """Test /day and /calendar response codes, and / redirect."""
- self.conn.request('GET', '/day')
- self.assertEqual(self.conn.getresponse().status, 200)
- self.conn.request('GET', '/day?date=3000-01-01')
- self.assertEqual(self.conn.getresponse().status, 200)
- self.conn.request('GET', '/day?date=FOO')
- self.assertEqual(self.conn.getresponse().status, 400)
- self.conn.request('GET', '/calendar')
- self.assertEqual(self.conn.getresponse().status, 200)
- self.conn.request('GET', '/calendar?start=&end=')
- self.assertEqual(self.conn.getresponse().status, 200)
- self.conn.request('GET', '/calendar?start=today&end=today')
- self.assertEqual(self.conn.getresponse().status, 200)
- self.conn.request('GET', '/calendar?start=2024-01-01&end=2025-01-01')
- self.assertEqual(self.conn.getresponse().status, 200)
- self.conn.request('GET', '/calendar?start=foo')
- self.assertEqual(self.conn.getresponse().status, 400)
- self.conn.request('GET', '/')
- response = self.conn.getresponse()
- self.assertEqual(response.status, 302)
- self.assertEqual(response.getheader('Location'), '/day')
- self.conn.request('GET', '/foo')
- self.assertEqual(self.conn.getresponse().status, 404)
-
- def test_do_POST_day(self) -> None:
- """Test POST /day."""
- headers = {'Content-type': 'application/x-www-form-urlencoded'}
- form_data = 'comment='
- self.conn.request('POST', '/day', form_data, headers)
- self.assertEqual(self.conn.getresponse().status, 400)
- self.conn.request('POST', '/day?date=foo', form_data, headers)
- self.assertEqual(self.conn.getresponse().status, 400)
- self.conn.request('POST', '/day?date=2024-01-01', form_data, headers)
- self.check_redirect('/')
- form_data = 'foo='
- self.conn.request('POST', '/day?date=2024-01-01', form_data, headers)
- self.assertEqual(self.conn.getresponse().status, 400)
+ @classmethod
+ def GET_day_dict(cls, date: str) -> dict[str, object]:
+ """Return JSON of GET /day to expect."""
+ # day: dict[str, object] = {'id': date, 'comment': '', 'todos': []}
+ day = cls._day_as_dict(date)
+ d: dict[str, object] = {'day': date,
+ 'top_nodes': [],
+ 'make_type': '',
+ 'enablers_for': {},
+ 'disablers_for': {},
+ 'conditions_present': [],
+ 'processes': [],
+ '_library': {'Day': cls.as_refs([day])}}
+ return d
+
+ @classmethod
+ def GET_calendar_dict(cls, start: int, end: int) -> dict[str, object]:
+ """Return JSON of GET /calendar to expect."""
+ today_date = date_in_n_days(0)
+ start_date = date_in_n_days(start)
+ end_date = date_in_n_days(end)
+ dates = [date_in_n_days(i) for i in range(start, end+1)]
+ days = [cls._day_as_dict(d) for d in dates]
+ library = {'Day': cls.as_refs(days)} if len(days) > 0 else {}
+ return {'today': today_date, 'start': start_date, 'end': end_date,
+ 'days': dates, '_library': library}
+
+ @staticmethod
+ def _todo_as_dict(id_: int = 1,
+ process_id: int = 1,
+ date: str = '2024-01-01',
+ conditions: None | list[int] = None,
+ disables: None | list[int] = None,
+ blockers: None | list[int] = None,
+ enables: None | list[int] = None
+ ) -> dict[str, object]:
+ """Return JSON of Todo to expect."""
+ # pylint: disable=too-many-arguments
+ d = {'id': id_,
+ 'date': date,
+ 'process_id': process_id,
+ 'is_done': False,
+ 'calendarize': False,
+ 'comment': '',
+ 'children': [],
+ 'parents': [],
+ 'effort': None,
+ 'conditions': conditions if conditions else [],
+ 'disables': disables if disables else [],
+ 'blockers': blockers if blockers else [],
+ 'enables': enables if enables else []}
+ return d
+
+ @staticmethod
+ def _todo_node_as_dict(todo_id: int) -> dict[str, object]:
+ """Return JSON of TodoNode to expect."""
+ return {'children': [], 'seen': False, 'todo': todo_id}
+
+ @staticmethod
+ def _day_as_dict(date: str) -> dict[str, object]:
+ return {'id': date, 'comment': '', 'todos': []}
+
+ @staticmethod
+ def _post_batch(list_of_args: list[list[object]],
+ names_of_simples: list[str],
+ names_of_versioneds: list[str],
+ f_as_dict: Callable[..., dict[str, object]],
+ f_to_post: Callable[..., None | dict[str, object]]
+ ) -> list[dict[str, object]]:
+ """Post expected=f_as_dict(*args) as input to f_to_post, for many."""
+ expecteds = []
+ for args in list_of_args:
+ expecteds += [f_as_dict(*args)]
+ for expected in expecteds:
+ assert isinstance(expected['_versioned'], dict)
+ post = {}
+ for name in names_of_simples:
+ post[name] = expected[name]
+ for name in names_of_versioneds:
+ post[name] = expected['_versioned'][name][0]
+ f_to_post(expected['id'], post)
+ return expecteds
+
+ def _post_day(self, params: str = '',
+ form_data: None | dict[str, object] = None,
+ redir_to: str = '',
+ status: int = 302,
+ ) -> None:
+ """POST /day?{params} with form_data."""
+ if not form_data:
+ form_data = {'day_comment': '', 'make_type': ''}
+ target = f'/day?{params}'
+ if not redir_to:
+ redir_to = f'{target}&make_type={form_data["make_type"]}'
+ self.check_post(form_data, target, status, redir_to)
+
+ def test_basic_GET_day(self) -> None:
+ """Test basic (no Processes/Conditions/Todos) GET /day basics."""
+ # check illegal date parameters
+ self.check_get('/day?date=foo', 400)
+ self.check_get('/day?date=2024-02-30', 400)
+ # check undefined day
+ date = date_in_n_days(0)
+ expected = self.GET_day_dict(date)
+ self.check_json_get('/day', expected)
+ # NB: GET ?date="today"/"yesterday"/"tomorrow" in test_basic_POST_day
+ # check 'make_type' GET parameter affects immediate reply, but …
+ date = '2024-01-01'
+ expected = self.GET_day_dict(date)
+ expected['make_type'] = 'bar'
+ self.check_json_get(f'/day?date={date}&make_type=bar', expected)
+ # … not any following, …
+ expected['make_type'] = ''
+ self.check_json_get(f'/day?date={date}', expected)
+ # … not even when part of a POST request
+ post: dict[str, object] = {'day_comment': '', 'make_type': 'foo'}
+ self._post_day(f'date={date}', post)
+ self.check_json_get(f'/day?date={date}', expected)
+
+ def test_fail_POST_day(self) -> None:
+ """Test malformed/illegal POST /day requests."""
+ # check payloads lacking minimum expecteds
+ url = '/day?date=2024-01-01'
+ self.check_post({}, url, 400)
+ self.check_post({'day_comment': ''}, url, 400)
+ self.check_post({'make_type': ''}, url, 400)
+ # to next check illegal new_todo values, we need an actual Process
+ self.post_process(1)
+ # check illegal new_todo values
+ post: dict[str, object]
+ post = {'make_type': '', 'day_comment': '', 'new_todo': ['foo']}
+ self.check_post(post, url, 400)
+ post['new_todo'] = [1, 2] # no Process of .id_=2 exists
+ # to next check illegal old_todo inputs, we need to first post Todo
+ post['new_todo'] = [1]
+ self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
+ # check illegal old_todo inputs (equal list lengths though)
+ post = {'make_type': '', 'day_comment': '', 'comment': ['foo'],
+ 'effort': [3.3], 'done': [], 'todo_id': [1]}
+ self.check_post(post, url, 302, '/day?date=2024-01-01&make_type=')
+ post['todo_id'] = [2] # reference to non-existant Process
+ self.check_post(post, url, 404)
+ post['todo_id'] = ['a']
+ self.check_post(post, url, 400)
+ post['todo_id'] = [1]
+ post['done'] = ['foo']
+ self.check_post(post, url, 400)
+ post['done'] = [2] # reference to non-posted todo_id
+ self.check_post(post, url, 400)
+ post['done'] = []
+ post['effort'] = ['foo']
+ self.check_post(post, url, 400)
+ post['effort'] = [None]
+ self.check_post(post, url, 400)
+ post['effort'] = [3.3]
+ # check illegal old_todo inputs: unequal list lengths
+ post['comment'] = []
+ self.check_post(post, url, 400)
+ post['comment'] = ['foo', 'foo']
+ self.check_post(post, url, 400)
+ post['comment'] = ['foo']
+ post['effort'] = []
+ self.check_post(post, url, 400)
+ post['effort'] = [3.3, 3.3]
+ self.check_post(post, url, 400)
+ post['effort'] = [3.3]
+ post['todo_id'] = [1, 1]
+ self.check_post(post, url, 400)
+ post['todo_id'] = [1]
+ # # check valid POST payload on bad paths
+ self.check_post(post, '/day', 400)
+ self.check_post(post, '/day?date=', 400)
+ self.check_post(post, '/day?date=foo', 400)
+
+ def test_basic_POST_day(self) -> None:
+ """Test basic (no Todos) POST /day.
+
+ Check POST (& GET!) requests properly parse 'today', 'tomorrow',
+ 'yesterday', and actual date strings;
+ preserve 'make_type' setting in redirect even if nonsensical;
+ and store 'day_comment'
+ """
+ for name, dist, test_str in [('2024-01-01', None, 'a'),
+ ('today', 0, 'b'),
+ ('yesterday', -1, 'c'),
+ ('tomorrow', +1, 'd')]:
+ date = name if dist is None else date_in_n_days(dist)
+ post = {'day_comment': test_str, 'make_type': f'x:{test_str}'}
+ post_url = f'/day?date={name}'
+ redir_url = f'{post_url}&make_type={post["make_type"]}'
+ self.check_post(post, post_url, 302, redir_url)
+ expected = self.GET_day_dict(date)
+ assert isinstance(expected['_library'], dict)
+ expected['_library']['Day'][date]['comment'] = test_str
+ self.check_json_get(post_url, expected)
+
+ def test_GET_day_with_processes_and_todos(self) -> None:
+ """Test GET /day displaying Processes and Todos (no trees)."""
+ date = '2024-01-01'
+ # check Processes get displayed in ['processes'] and ['_library']
+ procs_data = [[1, 'foo', 'oof', 1.1], [2, 'bar', 'rab', 0.9]]
+ procs_expected = self._post_batch(procs_data, [],
+ ['title', 'description', 'effort'],
+ self.proc_as_dict, self.post_process)
+ expected = self.GET_day_dict(date)
+ assert isinstance(expected['_library'], dict)
+ expected['processes'] = self.as_id_list(procs_expected)
+ expected['_library']['Process'] = self.as_refs(procs_expected)
+ self._post_day(f'date={date}')
+ self.check_json_get(f'/day?date={date}', expected)
+ # post Todos of either process and check their display
+ post_day: dict[str, object]
+ post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
+ todos = [self._todo_as_dict(1, 1, date),
+ self._todo_as_dict(2, 2, date)]
+ expected['_library']['Todo'] = self.as_refs(todos)
+ expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
+ nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
+ expected['top_nodes'] = nodes
+ self._post_day(f'date={date}', post_day)
+ self.check_json_get(f'/day?date={date}', expected)
+ # add a comment to one Todo and set the other's doneness and effort
+ post_day = {'day_comment': '', 'make_type': '', 'new_todo': [],
+ 'todo_id': [1, 2], 'done': [2], 'comment': ['FOO', ''],
+ 'effort': [2.3, '']}
+ expected['_library']['Todo']['1']['comment'] = 'FOO'
+ expected['_library']['Todo']['1']['effort'] = 2.3
+ expected['_library']['Todo']['2']['is_done'] = True
+ self._post_day(f'date={date}', post_day)
+ self.check_json_get(f'/day?date={date}', expected)
+
+ def test_GET_day_with_conditions(self) -> None:
+ """Test GET /day displaying Conditions and their relations."""
+ date = '2024-01-01'
+ # add Process with Conditions and their Todos, check display
+ conds_data = [[1, False, ['A'], ['a']], [2, True, ['B'], ['b']]]
+ conds_expected = self._post_batch(
+ conds_data, ['is_active'], ['title', 'description'],
+ self.cond_as_dict,
+ lambda x, y: self.check_post(y, f'/condition?id={x}', 302))
+ cond_names = ['conditions', 'disables', 'blockers', 'enables']
+ procs_data = [[1, 'foo', 'oof', 1.1, [1], [1], [2], [2]],
+ [2, 'bar', 'rab', 0.9, [2], [2], [1], [1]]]
+ procs_expected = self._post_batch(procs_data, cond_names,
+ ['title', 'description', 'effort'],
+ self.proc_as_dict, self.post_process)
+ expected = self.GET_day_dict(date)
+ assert isinstance(expected['_library'], dict)
+ expected['processes'] = self.as_id_list(procs_expected)
+ expected['_library']['Process'] = self.as_refs(procs_expected)
+ expected['_library']['Condition'] = self.as_refs(conds_expected)
+ self._post_day(f'date={date}')
+ self.check_json_get(f'/day?date={date}', expected)
+ # add Todos in relation to Conditions, check consequences
+ post_day: dict[str, object]
+ post_day = {'day_comment': '', 'make_type': '', 'new_todo': [1, 2]}
+ todos = [self._todo_as_dict(1, 1, date, [1], [1], [2], [2]),
+ self._todo_as_dict(2, 2, date, [2], [2], [1], [1])]
+ expected['_library']['Todo'] = self.as_refs(todos)
+ expected['_library']['Day'][date]['todos'] = self.as_id_list(todos)
+ nodes = [self._todo_node_as_dict(1), self._todo_node_as_dict(2)]
+ expected['top_nodes'] = nodes
+ expected['disablers_for'] = {'1': [1], '2': [2]}
+ expected['enablers_for'] = {'1': [2], '2': [1]}
+ expected['conditions_present'] = self.as_id_list(conds_expected)
+ self._post_day(f'date={date}', post_day)
+ self.check_json_get(f'/day?date={date}', expected)
+
+ def test_GET_calendar(self) -> None:
+ """Test GET /calendar responses based on various inputs, DB states."""
+ # check illegal date range delimiters
+ self.check_get('/calendar?start=foo', 400)
+ self.check_get('/calendar?end=foo', 400)
+ # check default range without saved days
+ expected = self.GET_calendar_dict(-1, 366)
+ self.check_json_get('/calendar', expected)
+ self.check_json_get('/calendar?start=&end=', expected)
+ # check named days as delimiters
+ expected = self.GET_calendar_dict(-1, +1)
+ self.check_json_get('/calendar?start=yesterday&end=tomorrow', expected)
+ # check zero-element range
+ expected = self.GET_calendar_dict(+1, 0)
+ self.check_json_get('/calendar?start=tomorrow&end=today', expected)
+ # check saved day shows up in results with proven by its comment
+ post_day: dict[str, object] = {'day_comment': 'foo', 'make_type': ''}
+ date1 = date_in_n_days(-2)
+ self._post_day(f'date={date1}', post_day)
+ start_date = date_in_n_days(-5)
+ end_date = date_in_n_days(+5)
+ url = f'/calendar?start={start_date}&end={end_date}'
+ expected = self.GET_calendar_dict(-5, +5)
+ assert isinstance(expected['_library'], dict)
+ expected['_library']['Day'][date1]['comment'] = post_day['day_comment']
+ self.check_json_get(url, expected)