Changeset View
Changeset View
Standalone View
Standalone View
swh/core/db/tests/conftest.py
Show All 29 Lines | |||||
def mock_import_swhmodule(mocker, datadir): | def mock_import_swhmodule(mocker, datadir): | ||||
"""This bypasses the module manipulation to make import_swhmodule return a mock | """This bypasses the module manipulation to make import_swhmodule return a mock | ||||
object suitable for data test files listing via get_sql_for_package. | object suitable for data test files listing via get_sql_for_package. | ||||
For a given module `test.<mod>`, return a MagicMock object with a __name__ | For a given module `test.<mod>`, return a MagicMock object with a __name__ | ||||
set to `<mod>` and __file__ pointing to `data/<mod>/__init__.py`. | set to `<mod>` and __file__ pointing to `data/<mod>/__init__.py`. | ||||
The Mock object also defines a `get_datastore()` attribute on which the | The Mock object also defines a `get_datastore()` attribute on which the | ||||
`current_version` attribute is set to 42. | `get_current_version()` exists and will return 42. | ||||
Typical usage:: | Typical usage:: | ||||
def test_xxx(cli_runner, mock_import_swhmodule): | def test_xxx(cli_runner, mock_import_swhmodule): | ||||
conninfo = craft_conninfo(test_db, "new-db") | conninfo = craft_conninfo(test_db, "new-db") | ||||
module_name = "test.cli" | module_name = "test.cli" | ||||
# the command below will use sql scripts from | # the command below will use sql scripts from | ||||
# swh/core/db/tests/data/cli/sql/*.sql | # swh/core/db/tests/data/cli/sql/*.sql | ||||
cli_runner.invoke(swhdb, ["init", module_name, "--dbname", conninfo]) | cli_runner.invoke(swhdb, ["init", module_name, "--dbname", conninfo]) | ||||
""" | """ | ||||
mock = mocker.MagicMock | mock = mocker.MagicMock | ||||
def import_swhmodule_mock(modname): | def import_swhmodule_mock(modname): | ||||
if modname.startswith("test."): | if modname.startswith("test."): | ||||
dirname = modname.split(".", 1)[1] | dirname = modname.split(".", 1)[1] | ||||
def get_datastore(*args, **kw): | def get_datastore(*args, **kw): | ||||
return mock(current_version=42) | return mock(get_current_version=lambda: 42) | ||||
return mock( | return mock( | ||||
__name__=modname, | __name__=modname, | ||||
__file__=os.path.join(datadir, dirname, "__init__.py"), | __file__=os.path.join(datadir, dirname, "__init__.py"), | ||||
get_datastore=get_datastore, | get_datastore=get_datastore, | ||||
) | ) | ||||
else: | else: | ||||
return import_swhmodule(modname) | return import_swhmodule(modname) | ||||
return mocker.patch("swh.core.db.db_utils.import_swhmodule", import_swhmodule_mock) | return mocker.patch("swh.core.db.db_utils.import_swhmodule", import_swhmodule_mock) |