Exemple #1
0
def mock_get_provisioner(factory, name) -> EntryPoint:
    if name == 'new-test-provisioner':
        return EntryPoint(
            'new-test-provisioner', 'jupyter_client.tests.test_provisioning', 'NewTestProvisioner'
        )

    if name in initial_provisioner_map:
        return EntryPoint(name, initial_provisioner_map[name][0], initial_provisioner_map[name][1])

    raise NoSuchEntryPoint(KernelProvisionerFactory.GROUP_NAME, name)
Exemple #2
0
    def __init__(self, entry_point: str, *,
                 timeout: int=5,
                 args: Optional[Iterable[Any]]=None,
                 kwargs: Optional[Dict[str, Any]]=None) -> None:

        try:
            self._entry_point = EntryPoint.from_string(entry_point, "task")
        except BadEntryPoint:
            raise TaskMisconfigured("Incorrectly defined entry point.")

        if self._entry_point.object_name is None:
            raise TaskMisconfigured("Task entry point must be an object, not a module.")

        try:
            self._timeout = int(timeout)

            if self._timeout < 1:
                raise ValueError
        except ValueError:
            raise TaskMisconfigured("Provided timeout could not be converted to int.")

        try:
            self._args = list(args or [])
            self._kwargs = dict(kwargs or {})
        except (TypeError, ValueError):
            raise TaskMisconfigured("Provided arguments cannot be converted to list or dict.")

        if not all([isinstance(x, str) for x in self._kwargs.keys()]):
            raise TaskMisconfigured("Keywords must be strings")

        try:
            assert isinstance(self.json, str)
        except (AssertionError, ValueError):
            raise TaskMisconfigured("Provided arguments are not JSON-serializable") from None
Exemple #3
0
def mock_get_schemas_providers(ep_map: Optional[dict] = None) -> List[EntryPoint]:
    result = []
    if ep_map is None:
        ep_map = schemas_provider_map
    for name, epstr in ep_map.items():
        result.append(EntryPoint(name, epstr[0], epstr[1]))
    return result
Exemple #4
0
 def _get_provisioner(self, name: str) -> EntryPoint:
     """Wrapper around entrypoints.get_single() - primarily to facilitate testing."""
     try:
         ep = get_single(KernelProvisionerFactory.GROUP_NAME, name)
     except NoSuchEntryPoint:
         # Check if the entrypoint name is 'local-provisioner'.  Although this should never
         # happen, we have seen cases where the previous distribution of jupyter_client has
         # remained which doesn't include kernel-provisioner entrypoints (so 'local-provisioner'
         # is deemed not found even though its definition is in THIS package).  In such cass,
         # the entrypoints package uses what it first finds - which is the older distribution
         # resulting in a violation of a supposed invariant condition.  To address this scenario,
         # we will log a warning message indicating this situation, then build the entrypoint
         # instance ourselves - since we have that information.
         if name == 'local-provisioner':
             distros = glob.glob(
                 f"{path.dirname(path.dirname(__file__))}-*")
             self.log.warning(
                 f"Kernel Provisioning: The 'local-provisioner' is not found.  This is likely "
                 f"due to the presence of multiple jupyter_client distributions and a previous "
                 f"distribution is being used as the source for entrypoints - which does not "
                 f"include 'local-provisioner'.  That distribution should be removed such that "
                 f"only the version-appropriate distribution remains (version >= 7).  Until "
                 f"then, a 'local-provisioner' entrypoint will be automatically constructed "
                 f"and used.\nThe candidate distribution locations are: {distros}"
             )
             ep = EntryPoint('local-provisioner',
                             'jupyter_client.provisioning',
                             'LocalProvisioner')
         else:
             raise
     return ep
Exemple #5
0
    def _load_plugin(self, type_name, entrypoint: entrypoints.EntryPoint):
        # if the entrypoint was already loaded into cache and queued, do nothing
        if self._load_cache[type_name].get(entrypoint.name, None):
            return

        try:
            # Load the entrypoint (unless already cached), cache it, and put it on the instantiate queue
            msg.logMessage(
                f'Loading entrypoint {entrypoint.name} from module: {entrypoint.module_name}'
            )
            with load_timer() as elapsed:
                plugin_class = self._load_cache[type_name][entrypoint.name] = \
                    self._load_cache[type_name].get(entrypoint.name, None) or entrypoint.load()
        except (Exception, SystemError) as ex:
            msg.logMessage(
                f"Unable to load {entrypoint.name} plugin from module: {entrypoint.module_name}",
                msg.ERROR)
            msg.logError(ex)
            msg.notifyMessage(
                repr(ex),
                title=
                f'An error occurred while starting the "{entrypoint.name}" plugin.',
                level=msg.CRITICAL)

        else:
            msg.logMessage(
                f"{int(elapsed() * 1000)} ms elapsed while loading {entrypoint.name}",
                level=msg.INFO)
            self._instantiate_queue.put((type_name, entrypoint, plugin_class))
Exemple #6
0
def test_create_poetry_with_plugins(mocker):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[EntryPoint("my-plugin", "tests.test_factory", "MyPlugin")],
    )

    poetry = Factory().create_poetry(fixtures_dir / "sample_project")

    assert "9.9.9" == poetry.package.version.text
Exemple #7
0
    def _load_plugin_entrypoint(self, entrypoint: entrypoints.EntryPoint) -> None:
        logger.debug(f"Loading the {entrypoint.name} plugin")

        plugin = entrypoint.load()

        if not issubclass(plugin, (Plugin, ApplicationPlugin)):
            raise ValueError(
                "The Poetry plugin must be an instance of Plugin or ApplicationPlugin"
            )

        self.add_plugin(plugin())
Exemple #8
0
def test_create_poetry_with_plugins(mocker: MockerFixture):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.test_factory", "MyPlugin")
        ],
    )

    poetry = Factory().create_poetry(fixtures_dir / "sample_project")

    assert poetry.package.readmes == ("README.md", )
def test_load_plugins_with_invalid_plugin(manager_factory, poetry, io, mocker):
    manager = manager_factory()

    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.plugins.test_plugin_manager",
                       "InvalidPlugin")
        ],
    )

    with pytest.raises(ValueError):
        manager.load_plugins()
def test_load_plugins_with_plugins_disabled(no_plugin_manager, poetry, io,
                                            mocker):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.plugins.test_plugin_manager",
                       "MyPlugin")
        ],
    )

    no_plugin_manager.load_plugins()

    assert "1.2.3" == poetry.package.version.text
    assert "" == io.fetch_output()
def test_application_with_plugins_disabled(mocker: MockerFixture):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.console.test_application",
                       "AddCommandPlugin")
        ],
    )

    app = Application()

    tester = ApplicationTester(app)
    tester.execute("--no-plugins")

    assert re.search(r"\s+foo\s+Foo Command", tester.io.fetch_output()) is None
    assert tester.status_code == 0
def test_application_execute_plugin_command(mocker: MockerFixture):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.console.test_application",
                       "AddCommandPlugin")
        ],
    )

    app = Application()

    tester = ApplicationTester(app)
    tester.execute("foo")

    assert tester.io.fetch_output() == "foo called\n"
    assert tester.status_code == 0
def test_load_plugins_and_activate(manager_factory, poetry, io, mocker):
    manager = manager_factory()

    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.plugins.test_plugin_manager",
                       "MyPlugin")
        ],
    )

    manager.load_plugins()
    manager.activate(poetry, io)

    assert "9.9.9" == poetry.package.version.text
    assert "Updating version\n" == io.fetch_output()
def test_load_plugins_with_plugins_disabled(
    no_plugin_manager: PluginManager,
    poetry: Poetry,
    io: BufferedIO,
    mocker: MockerFixture,
):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.plugins.test_plugin_manager", "MyPlugin")
        ],
    )

    no_plugin_manager.load_plugins()

    assert poetry.package.version.text == "1.2.3"
    assert io.fetch_output() == ""
def test_application_execute_plugin_command_with_plugins_disabled(mocker):
    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.console.test_application",
                       "AddCommandPlugin")
        ],
    )

    app = Application()

    tester = ApplicationTester(app)
    tester.execute("foo --no-plugins")

    assert "" == tester.io.fetch_output()
    assert '\nThe command "foo" does not exist.\n' == tester.io.fetch_error()
    assert 1 == tester.status_code
def test_load_plugins_and_activate(
    manager_factory: ManagerFactory,
    poetry: Poetry,
    io: BufferedIO,
    mocker: MockerFixture,
):
    manager = manager_factory()

    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.plugins.test_plugin_manager", "MyPlugin")
        ],
    )

    manager.load_plugins()
    manager.activate(poetry, io)

    assert poetry.package.readmes == ("README.md",)
    assert io.fetch_output() == "Setting readmes\n"
Exemple #17
0
def test_load_plugins_and_activate(
    manager_factory: ManagerFactory,
    poetry: Poetry,
    io: BufferedIO,
    mocker: "MockerFixture",
):
    manager = manager_factory()

    mocker.patch(
        "entrypoints.get_group_all",
        return_value=[
            EntryPoint("my-plugin", "tests.plugins.test_plugin_manager",
                       "MyPlugin")
        ],
    )

    manager.load_plugins()
    manager.activate(poetry, io)

    assert poetry.package.version.text == "9.9.9"
    assert io.fetch_output() == "Updating version\n"
Exemple #18
0
    def load(cls, entry_point: EntryPoint) -> "SectionPlugin":
        """
        Load a plugin from a pre-parsed entry point

        Parses the following options:

        ``required``
            If present implies ``required=True``.

        ``before=other``
            This plugin must be processed before ``other``.

        ``after=other``
            This plugin must be processed after ``other``.
        """
        digest = entry_point.load()
        requirements = getattr(digest, "__requirements__", PluginRequirements())
        if entry_point.extras:
            raise ValueError(
                f"SectionPlugin entry point '{entry_point.name}':"
                f" extras are no longer supported"
            )
        return cls(section=entry_point.name, digest=digest, requirements=requirements)
Exemple #19
0
def mock_get_all_provisioners() -> List[EntryPoint]:
    result = []
    for name, epstr in initial_provisioner_map.items():
        result.append(EntryPoint(name, epstr[0], epstr[1]))
    return result