[Python] How can I test that Python package entrypoints are correctly discovered and loaded?

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am currently writing a package that seeks to load entrypoint contributions from other installed packages using importlib.metadata.entry_points, but am unsure how I can test this properly. I am using Pytest for my package's testing.

    I'm essentially trying to solve the opposite problem of this post, where they want to ensure that their package is loaded by another installed package.

    I cannot simply have example plugin packages as development dependencies, as I want to be able to test different cases with different plugins:

    • What happens if a plugin fails to import?
    • What happens if a plugin raises an exception?
    • Does a correctly-written plugin behave well with my application?

    I want to test each of these cases in different tests, and so I need a way of dynamically registering and unregistering mock plugins for Python's entrypoint system.

    Here's what my ideal code would look like:

    def test_bad_plugin_class():
    class MyBadPlugin(MyPluginInterface):
    def do_something(self):
    # This code is broken
    raise RuntimeError("No.")

    with importlib.metadata.add_mock_entrypoint( # function does not exist :(
    'my_package.plugins',
    'bad_plugin_lib:MyBadPlugin',
    # Give the class that should be returned when calling EntryPoint.load
    # to avoid needing to create a file to import from
    MyBadPlugin,
    ):
    # Would check for actual error handling here
    with pytest.raises(ImportError):
    my_library.load_plugins()


    I could just mock the entire entrypoint system, but this feels excessive and tedious, and so I am looking for a better solution.

    How can I accomplish this?

    Continue reading...

Compartilhe esta Página