import pkg_resources
import importlib

import pytest

from rhodecode.lib.dbmigrate.migrate.versioning.util import load_dotted


class TestPkgResourcesLibMigrations:
    """
    when pkg_resources is removed, these tests can be safely removed
    """

    @pytest.mark.parametrize(
        "module, resource",
        [
            ("rc_chat", "static"),
            ("deform", "templates"),
            ("rhodecode", "templates/forms"),
        ],
    )
    def test_pkg_resources_resource_filename_lib_migration(self, module, resource):
        res = pkg_resources.resource_filename(module, resource)

        with importlib.resources.as_file(importlib.resources.files(module).joinpath(resource)) as static_path:
            migrated_res = str(static_path)

        assert res == migrated_res

    def test_pkg_resources_EntryPoint_lib_migration(self):
        package_class = "rhodecode.lib.dbmigrate.migrate.versioning.util.keyedinstance:KeyedInstance"
        loaded_class = pkg_resources.EntryPoint.parse(f"x={package_class}").resolve()
        loaded_class_migrated = load_dotted(package_class)
        assert loaded_class == loaded_class_migrated

    def test_pkg_resources_resource_string_lib_migration(self):
        module = "rhodecode"
        path = "config/licenses.json"
        res = pkg_resources.resource_string(module, path)

        migrated_res = importlib.resources.files(module).joinpath(path).read_bytes()

        assert res == migrated_res
