|
1 | 1 | from click.testing import CliRunner |
2 | 2 | import click |
3 | 3 | import importlib |
4 | | -from sqlite_utils import cli, hookimpl, plugins |
| 4 | +from sqlite_utils import cli, Database, hookimpl, plugins |
5 | 5 |
|
6 | 6 |
|
7 | 7 | def test_register_commands(): |
@@ -35,3 +35,45 @@ def hello_world(): |
35 | 35 | plugins.pm.unregister(name="HelloWorldPlugin") |
36 | 36 | importlib.reload(cli) |
37 | 37 | assert plugins.get_plugins() == [] |
| 38 | + |
| 39 | + |
| 40 | +def test_prepare_connection(): |
| 41 | + importlib.reload(cli) |
| 42 | + assert plugins.get_plugins() == [] |
| 43 | + |
| 44 | + class HelloFunctionPlugin: |
| 45 | + __name__ = "HelloFunctionPlugin" |
| 46 | + |
| 47 | + @hookimpl |
| 48 | + def prepare_connection(self, conn): |
| 49 | + conn.create_function("hello", 1, lambda name: f"Hello, {name}!") |
| 50 | + |
| 51 | + db = Database(memory=True) |
| 52 | + functions = db.execute( |
| 53 | + "select distinct name from pragma_function_list order by 1" |
| 54 | + ).fetchall() |
| 55 | + assert "hello" not in functions |
| 56 | + |
| 57 | + try: |
| 58 | + plugins.pm.register(HelloFunctionPlugin(), name="HelloFunctionPlugin") |
| 59 | + |
| 60 | + assert plugins.get_plugins() == [ |
| 61 | + {"name": "HelloFunctionPlugin", "hooks": ["prepare_connection"]} |
| 62 | + ] |
| 63 | + |
| 64 | + db = Database(memory=True) |
| 65 | + |
| 66 | + functions = [ |
| 67 | + row[0] |
| 68 | + for row in db.execute( |
| 69 | + "select distinct name from pragma_function_list order by 1" |
| 70 | + ).fetchall() |
| 71 | + ] |
| 72 | + assert "hello" in functions |
| 73 | + |
| 74 | + result = db.execute('select hello("world")').fetchone()[0] |
| 75 | + assert result == "Hello, world!" |
| 76 | + |
| 77 | + finally: |
| 78 | + plugins.pm.unregister(name="HelloFunctionPlugin") |
| 79 | + assert plugins.get_plugins() == [] |
0 commit comments