|
20 | 20 | # misrepresented as being the original software.
|
21 | 21 | # 3. This notice may not be removed or altered from any source distribution.
|
22 | 22 |
|
23 |
| -import threading |
24 |
| -import unittest |
| 23 | +import contextlib |
25 | 24 | import sqlite3 as sqlite
|
26 | 25 | import sys
|
| 26 | +import threading |
| 27 | +import unittest |
27 | 28 |
|
28 | 29 | from test.support.os_helper import TESTFN, unlink
|
29 | 30 |
|
30 | 31 |
|
| 32 | +# Helper for tests using TESTFN |
| 33 | +@contextlib.contextmanager |
| 34 | +def managed_connect(*args, **kwargs): |
| 35 | + cx = sqlite.connect(*args, **kwargs) |
| 36 | + try: |
| 37 | + yield cx |
| 38 | + finally: |
| 39 | + cx.close() |
| 40 | + unlink(TESTFN) |
| 41 | + |
| 42 | + |
31 | 43 | class ModuleTests(unittest.TestCase):
|
32 | 44 | def test_api_level(self):
|
33 | 45 | self.assertEqual(sqlite.apilevel, "2.0",
|
@@ -190,26 +202,27 @@ def test_in_transaction_ro(self):
|
190 | 202 | with self.assertRaises(AttributeError):
|
191 | 203 | self.cx.in_transaction = True
|
192 | 204 |
|
| 205 | +class OpenTests(unittest.TestCase): |
| 206 | + _sql = "create table test(id integer)" |
| 207 | + |
193 | 208 | def test_open_with_path_like_object(self):
|
194 | 209 | """ Checks that we can successfully connect to a database using an object that
|
195 | 210 | is PathLike, i.e. has __fspath__(). """
|
196 |
| - self.addCleanup(unlink, TESTFN) |
197 | 211 | class Path:
|
198 | 212 | def __fspath__(self):
|
199 | 213 | return TESTFN
|
200 | 214 | path = Path()
|
201 |
| - with sqlite.connect(path) as cx: |
202 |
| - cx.execute('create table test(id integer)') |
| 215 | + with managed_connect(path) as cx: |
| 216 | + cx.execute(self._sql) |
203 | 217 |
|
204 | 218 | def test_open_uri(self):
|
205 |
| - self.addCleanup(unlink, TESTFN) |
206 |
| - with sqlite.connect(TESTFN) as cx: |
207 |
| - cx.execute('create table test(id integer)') |
208 |
| - with sqlite.connect('file:' + TESTFN, uri=True) as cx: |
209 |
| - cx.execute('insert into test(id) values(0)') |
210 |
| - with sqlite.connect('file:' + TESTFN + '?mode=ro', uri=True) as cx: |
211 |
| - with self.assertRaises(sqlite.OperationalError): |
212 |
| - cx.execute('insert into test(id) values(1)') |
| 219 | + with managed_connect(TESTFN) as cx: |
| 220 | + cx.execute(self._sql) |
| 221 | + with managed_connect(f"file:{TESTFN}", uri=True) as cx: |
| 222 | + cx.execute(self._sql) |
| 223 | + with self.assertRaises(sqlite.OperationalError): |
| 224 | + with managed_connect(f"file:{TESTFN}?mode=ro", uri=True) as cx: |
| 225 | + cx.execute(self._sql) |
213 | 226 |
|
214 | 227 |
|
215 | 228 | class CursorTests(unittest.TestCase):
|
|
0 commit comments