1 """Test Conditions module."""
2 from tests.utils import TestCaseWithDB, TestCaseWithServer, TestCaseSansDB
3 from plomtask.conditions import Condition
4 from plomtask.processes import Process
5 from plomtask.todos import Todo
6 from plomtask.exceptions import HandledException
9 class TestsSansDB(TestCaseSansDB):
10 """Tests requiring no DB setup."""
11 checked_class = Condition
12 versioned_defaults_to_test = {'title': 'UNNAMED', 'description': ''}
15 class TestsWithDB(TestCaseWithDB):
16 """Tests requiring DB, but not server setup."""
17 checked_class = Condition
18 default_init_kwargs = {'is_active': False}
19 test_versioneds = {'title': str, 'description': str}
21 def test_remove(self) -> None:
22 """Test .remove() effects on DB and cache."""
25 proc.save(self.db_conn)
26 todo = Todo(None, proc, False, '2024-01-01')
27 for depender in (proc, todo):
28 assert hasattr(depender, 'save')
29 assert hasattr(depender, 'set_conditions')
32 depender.save(self.db_conn)
33 depender.set_conditions(self.db_conn, [c.id_], 'conditions')
34 depender.save(self.db_conn)
35 with self.assertRaises(HandledException):
36 c.remove(self.db_conn)
37 depender.set_conditions(self.db_conn, [], 'conditions')
38 depender.save(self.db_conn)
39 c.remove(self.db_conn)
42 class TestsWithServer(TestCaseWithServer):
43 """Module tests against our HTTP server/handler (and database)."""
46 def GET_condition_dict(cls, cond: dict[str, object]) -> dict[str, object]:
47 """Return JSON of GET /condition to expect."""
48 return {'is_new': False,
49 'enabled_processes': [],
50 'disabled_processes': [],
51 'enabling_processes': [],
52 'disabling_processes': [],
53 'condition': cond['id'],
54 '_library': {'Condition': cls.as_refs([cond])}}
57 def GET_conditions_dict(cls, conds: list[dict[str, object]]
58 ) -> dict[str, object]:
59 """Return JSON of GET /conditions to expect."""
60 library = {'Condition': cls.as_refs(conds)} if conds else {}
61 d: dict[str, object] = {'conditions': cls.as_id_list(conds),
67 def test_fail_POST_condition(self) -> None:
68 """Test malformed/illegal POST /condition requests."""
69 # check invalid POST payloads
71 self.check_post({}, url, 400)
72 self.check_post({'title': ''}, url, 400)
73 self.check_post({'title': '', 'description': ''}, url, 400)
74 self.check_post({'title': '', 'is_active': False}, url, 400)
75 self.check_post({'description': '', 'is_active': False}, url, 400)
76 # check valid POST payload on bad paths
77 valid_payload = {'title': '', 'description': '', 'is_active': False}
78 self.check_post(valid_payload, '/condition?id=foo', 400)
80 def test_do_POST_condition(self) -> None:
81 """Test (valid) POST /condition and its effect on GET /condition[s]."""
82 # test valid POST's effect on …
83 post = {'title': 'foo', 'description': 'oof', 'is_active': False}
84 self.check_post(post, '/condition', 302, '/condition?id=1')
86 cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
87 assert isinstance(cond['_versioned'], dict)
88 expected_single = self.GET_condition_dict(cond)
89 self.check_json_get('/condition?id=1', expected_single)
91 expected_all = self.GET_conditions_dict([cond])
92 self.check_json_get('/conditions', expected_all)
93 # test (no) effect of invalid POST to existing Condition on /condition
94 self.check_post({}, '/condition?id=1', 400)
95 self.check_json_get('/condition?id=1', expected_single)
96 # test effect of POST changing title and activeness
97 post = {'title': 'bar', 'description': 'oof', 'is_active': True}
98 self.check_post(post, '/condition?id=1', 302)
99 cond['_versioned']['title'][1] = 'bar'
100 cond['is_active'] = True
101 self.check_json_get('/condition?id=1', expected_single)
102 # test deletion POST's effect on …
103 self.check_post({'delete': ''}, '/condition?id=1', 302, '/conditions')
104 cond = self.cond_as_dict()
105 assert isinstance(expected_single['_library'], dict)
106 expected_single['_library']['Condition'] = self.as_refs([cond])
107 self.check_json_get('/condition?id=1', expected_single)
109 expected_all['conditions'] = []
110 expected_all['_library'] = {}
111 self.check_json_get('/conditions', expected_all)
113 def test_do_GET_condition(self) -> None:
114 """More GET /condition testing, especially for Process relations."""
115 # check expected default status codes
116 self.check_get_defaults('/condition')
117 # make Condition and two Processes that among them establish all
118 # possible ConditionsRelations to it, …
119 cond_post = {'title': 'foo', 'description': 'oof', 'is_active': False}
120 self.check_post(cond_post, '/condition', 302, '/condition?id=1')
121 proc1_post = {'title': 'A', 'description': '', 'effort': 1.0,
122 'conditions': [1], 'disables': [1]}
123 proc2_post = {'title': 'B', 'description': '', 'effort': 1.0,
124 'enables': [1], 'blockers': [1]}
125 self.post_process(1, proc1_post)
126 self.post_process(2, proc2_post)
127 # … then check /condition displays all these properly.
128 cond = self.cond_as_dict(titles=['foo'], descriptions=['oof'])
129 assert isinstance(cond['id'], int)
130 proc1 = self.proc_as_dict(conditions=[cond['id']],
131 disables=[cond['id']])
132 proc2 = self.proc_as_dict(2, 'B',
133 blockers=[cond['id']],
134 enables=[cond['id']])
135 expected = self.GET_condition_dict(cond)
136 assert isinstance(expected['_library'], dict)
137 expected['enabled_processes'] = self.as_id_list([proc1])
138 expected['disabled_processes'] = self.as_id_list([proc2])
139 expected['enabling_processes'] = self.as_id_list([proc2])
140 expected['disabling_processes'] = self.as_id_list([proc1])
141 expected['_library']['Process'] = self.as_refs([proc1, proc2])
142 self.check_json_get('/condition?id=1', expected)
144 def test_do_GET_conditions(self) -> None:
145 """Test GET /conditions."""
146 # test empty result on empty DB, default-settings on empty params
147 expected = self.GET_conditions_dict([])
148 self.check_json_get('/conditions', expected)
149 # test on meaningless non-empty params (incl. entirely un-used key),
150 # that 'sort_by' default to 'title' (even if set to something else, as
151 # long as without handler) and 'pattern' get preserved
152 expected['pattern'] = 'bar' # preserved despite zero effect!
153 url = '/conditions?sort_by=foo&pattern=bar&foo=x'
154 self.check_json_get(url, expected)
155 # test non-empty result, automatic (positive) sorting by title
156 post1 = {'is_active': False, 'title': 'foo', 'description': 'oof'}
157 post2 = {'is_active': False, 'title': 'bar', 'description': 'rab'}
158 post3 = {'is_active': True, 'title': 'baz', 'description': 'zab'}
159 self.check_post(post1, '/condition', 302, '/condition?id=1')
160 self.check_post(post2, '/condition', 302, '/condition?id=2')
161 self.check_post(post3, '/condition', 302, '/condition?id=3')
162 cond1 = self.cond_as_dict(1, False, ['foo'], ['oof'])
163 cond2 = self.cond_as_dict(2, False, ['bar'], ['rab'])
164 cond3 = self.cond_as_dict(3, True, ['baz'], ['zab'])
165 expected = self.GET_conditions_dict([cond2, cond3, cond1])
166 self.check_json_get('/conditions', expected)
167 # test other sortings
168 # (NB: by .is_active has two items of =False, their order currently
169 # is not explicitly made predictable, so mail fail until we do)
170 expected['conditions'] = self.as_id_list([cond1, cond3, cond2])
171 expected['sort_by'] = '-title'
172 self.check_json_get('/conditions?sort_by=-title', expected)
173 expected['conditions'] = self.as_id_list([cond1, cond2, cond3])
174 expected['sort_by'] = 'is_active'
175 self.check_json_get('/conditions?sort_by=is_active', expected)
176 expected['conditions'] = self.as_id_list([cond3, cond1, cond2])
177 expected['sort_by'] = '-is_active'
178 self.check_json_get('/conditions?sort_by=-is_active', expected)
179 # test pattern matching on title
180 expected = self.GET_conditions_dict([cond2, cond3])
181 expected['pattern'] = 'ba'
182 self.check_json_get('/conditions?pattern=ba', expected)
183 # test pattern matching on description
184 assert isinstance(expected['_library'], dict)
185 expected['conditions'] = self.as_id_list([cond1])
186 expected['_library']['Condition'] = self.as_refs([cond1])
187 expected['pattern'] = 'oo'
188 self.check_json_get('/conditions?pattern=oo', expected)