import math
import sys
from importlib import metadata

import pytest


@pytest.fixture(autouse=True)
def cleanup():
    modules = dict(sys.modules)
    meta_path = list(sys.meta_path)
    try:
        yield
    finally:
        sys.modules.clear()
        sys.modules.update(modules)
        sys.meta_path[:] = meta_path


class FakeDistribution(metadata.Distribution):
    def __init__(self, name, *entry_points):
        self._name = name
        self._entry_points = metadata.EntryPoints(entry_points)

    @property
    def name(self):
        return self._name

    @property
    def entry_points(self):
        return self._entry_points

    def read_text(self, filename):
        raise NotImplementedError

    def locate_file(self, path):
        raise NotImplementedError


class FakeDistributionFinder(metadata.DistributionFinder):
    def __init__(self, **kwargs):
        self.distributions = [
            FakeDistribution(name, *entry_points)
            for name, entry_points in kwargs.items()
        ]

    def find_distributions(self, ctx):
        return self.distributions

    def setup(self):
        sys.meta_path.append(self)


def test_entrypoints():
    FakeDistributionFinder(test=[metadata.EntryPoint('test-math', 'math', 'testgroup')]).setup()

    entry_point, = metadata.entry_points(group='testgroup')
    assert entry_point.name == 'test-math'
    assert entry_point.load() is math