Debian Codegraph @

tests/unit/test_rundb.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import contextlib
18 from pathlib import Path
19 import sqlite3
20 from types import SimpleNamespace
21 from typing import (
22 List,
23 Optional,
24 Tuple,
25 )
26 import unittest
27 from unittest import mock
28 import sys
29
30 import pytest
31
32 from cylc.flow.exceptions import PlatformLookupError
33 from cylc.flow.flow_mgr import FlowNums
34 from cylc.flow.rundb import CylcWorkflowDAO
35 from cylc.flow.util import serialise_set
36
37
38 GLOBAL_CONFIG = """
39 [platforms]
40 [[desktop[0-9]{2}|laptop[0-9]{2}]]
41 # hosts = platform name (default)
42 # Note: "desktop01" and "desktop02" are both valid and distinct
43 # platforms
44 [[sugar]]
45 hosts = localhost
46 job runner = slurm
47 [[hpc]]
48 hosts = hpcl1, hpcl2
49 retrieve job logs = True
50 job runner = pbs
51 [[hpcl1-bg]]
52 hosts = hpcl1
53 retrieve job logs = True
54 job runner = background
55 [[hpcl2-bg]]
56 hosts = hpcl2
57 retrieve job logs = True
58 job runner = background
59 """
60
61
62 class TestRunDb(unittest.TestCase):
63
64 def setUp(self):
65 self.dao = CylcWorkflowDAO(':memory:')
66 self.mocked_connection = mock.Mock()
67 self.dao.connect = mock.MagicMock(return_value=self.mocked_connection)
68
69 get_select_task_job = [
70 ["cycle", "name", "NN"],
71 ["cycle", "name", None],
72 ["cycle", "name", "02"],
73 ]
74
75 def test_select_task_job(self):
76 """Test the rundb CylcWorkflowDAO select_task_job method"""
77 columns = self.dao.tables[CylcWorkflowDAO.TABLE_TASK_JOBS].columns[3:]
78 expected_values = [[2 for _ in columns]]
79
80 self.mocked_connection.execute.return_value = expected_values
81
82 # parameterized test
83 for cycle, name, submit_num in self.get_select_task_job:
84 returned_values = self.dao.select_task_job(cycle, name, submit_num)
85
86 for column in columns:
87 self.assertEqual(2, returned_values[column.name])
88
89 def test_select_task_job_sqlite_error(self):
90 """Test when the rundb CylcWorkflowDAO select_task_job method raises
91 a SQLite exception, the method returns None"""
92
93 self.mocked_connection.execute.side_effect = sqlite3.DatabaseError
94
95 r = self.dao.select_task_job("it'll", "raise", "an error!")
96 self.assertIsNone(r)
97
98
99 @contextlib.contextmanager
100 def create_temp_db():
101 """Create and tidy a temporary database for testing purposes."""
102 conn = sqlite3.connect(':memory:')
103 yield conn
104 conn.close() # doesn't raise error on re-invocation
105
106
107 def test_operational_error(tmp_path, caplog):
108 """Test logging on operational error."""
109 # create a db object
110 db_file = tmp_path / 'db'
111 with CylcWorkflowDAO(db_file) as dao:
112 # stage some stuff
113 dao.add_delete_item(CylcWorkflowDAO.TABLE_TASK_JOBS)
114 dao.add_insert_item(CylcWorkflowDAO.TABLE_TASK_JOBS, ['pub'])
115 dao.add_update_item(
116 CylcWorkflowDAO.TABLE_TASK_JOBS, ({'pub': None}, {})
117 )
118
119 # connect the to DB
120 dao.connect()
121
122 # then delete the file - this will result in an OperationalError
123 db_file.unlink()
124
125 # execute & commit the staged items
126 with pytest.raises(sqlite3.OperationalError):
127 dao.execute_queued_items()
128
129 # ensure that the failed transaction is logged for debug purposes
130 assert len(caplog.messages) == 1
131 message = caplog.messages[0]
132 assert 'An error occurred when writing to the database' in message
133 assert 'DELETE FROM task_jobs' in message
134 assert 'INSERT OR REPLACE INTO task_jobs' in message
135 assert 'UPDATE task_jobs' in message
136 assert 'The error was: no such table: task_jobs' in message
137 if sys.version_info.major == 3 and sys.version_info.minor >= 11:
138 assert 'SQLite error code: 1' in message
139 assert 'SQLite error name: SQLITE_ERROR' in message
140 else:
141 assert 'SQLite error code: Not available' in message
142 assert 'SQLite error name: Not available' in message
143
144
145 def test_table_creation(tmp_path: Path):
146 """Test tables are NOT created by default."""
147 db_file = tmp_path / 'db'
148 stmt = "SELECT name FROM sqlite_master WHERE type='table'"
149 with CylcWorkflowDAO(db_file) as dao:
150 tables = list(dao.connect().execute(stmt))
151 assert tables == []
152 with CylcWorkflowDAO(db_file, create_tables=True) as dao:
153 tables = [i[0] for i in dao.connect().execute(stmt)]
154 assert CylcWorkflowDAO.TABLE_WORKFLOW_PARAMS in tables
155
156
157 def test_context_manager_exit(
158 monkeypatch: pytest.MonkeyPatch, tmp_path: Path
159 ):
160 """Test connection is closed even if an exception occurs somewhere."""
161 db_file = tmp_path / 'db'
162 mock_close = mock.Mock()
163 with monkeypatch.context() as mp:
164 mp.setattr(CylcWorkflowDAO, 'close', mock_close)
165 with CylcWorkflowDAO(db_file) as dao, pytest.raises(RuntimeError):
166 mock_close.assert_not_called()
167 raise RuntimeError('mock err')
168 mock_close.assert_called_once()
169 # Close connection for real:
170 dao.close()
171
172
173 def test_select_task_pool_for_restart_if_not_platforms(tmp_path):
174 """Returns error if platform error or errors raised by callback.
175 """
176 # Setup a fake callback function which returns the fake "platform_name":
177 def callback(index, row):
178 return ''.join(row)
179
180 db_file = tmp_path / 'db'
181 dao = CylcWorkflowDAO(db_file, create_tables=True)
182 # Fiddle the connect method to return a list of fake "platform_names":
183 dao.connect = lambda: SimpleNamespace(execute=lambda _: ['foo', 'bar'])
184
185 # Assert that an error is raised and that it mentions both fake platforms:
186 with pytest.raises(
187 PlatformLookupError,
188 match='not defined.*\n.*foo.*\n.*bar'
189 ):
190 dao.select_task_pool_for_restart(callback)
191
192
193 @pytest.mark.parametrize(
194 'values, expected',
195 [
196 pytest.param(
197 [
198 ({1, 2}, '2021-01-01T00:00:00'),
199 ({3, 4}, '2021-01-01T00:00:02'),
200 ({5, 6}, '2021-01-01T00:00:01'),
201 ],
202 {3, 4},
203 id="basic"
204 ),
205 pytest.param(
206 [
207 ({2}, '2021-01-01T00:00:00'),
208 (set(), '2021-01-01T00:00:01'),
209 (set(), '2021-01-01T00:00:02'),
210 ],
211 {2},
212 id="ignore flow=none"
213 ),
214 pytest.param(
215 [
216 (set(), '2021-01-01T00:00:01'),
217 (set(), '2021-01-01T00:00:02'),
218 ],
219 None,
220 id="all flow=none"
221 ),
222 ],
223 )
224 def test_select_latest_flow_nums(
225 values: List[Tuple[FlowNums, str]], expected: Optional[FlowNums]
226 ):
227 with CylcWorkflowDAO(':memory:') as dao:
228 conn = dao.connect()
229 conn.execute(
230 "CREATE TABLE task_states (flow_nums TEXT, time_created TEXT)"
231 )
232 for (fnums, timestamp) in values:
233 conn.execute(
234 'INSERT INTO task_states VALUES (?, ?)',
235 (serialise_set(fnums), timestamp)
236 )
237 conn.commit()
238
239 assert dao.select_latest_flow_nums() == expected