Skip to content

Patching imports with monkeypatch #945

Closed

Description

@The-Compiler

I have some tests where I need to patch importing of modules, to test e.g. if a module behaves properly when some optional dependency couldn't be imported.

I already have something to monkeypatch builtins.__import__ and importlib.import_module, in my testsuite, but I thought it might be a good addition to pytest as it's not trivial to get right, and there are differences between Python 2 and 3.

Proposed API:

  • New monkeypatch.import(name, obj, module=None) method
    • name: The name of the modified import
    • obj: The object which should get imported instead, or ImportError to raise an ImportError on import
    • module: If given (as a dotted string path), importlib.import_module and maybe others are patched as well for this module.

Caveats:

  • import is patched globally for the duration of the test, not only in the given module - the module parameter is only for importlib.import_module and similar things.
  • Making ImportError for obj special cased might be weird? But I can't think of a better API.

What do you think? Would this be something which is generally useful or should I keep it in my own testsuite?

Activity

  1. added
    type: proposalproposal for a new feature, often to gather opinions or design the API around the new feature
    on Aug 18, 2015
  2. self-assigned this
    on Aug 18, 2015
  3. RonnyPfannschmidt commented on Aug 19, 2015

    @RonnyPfannschmidt
    Member

    this one is tricky

  4. RonnyPfannschmidt commented on Jan 1, 2016

    @RonnyPfannschmidt
    Member

    This should be a plugin

  5. RonnyPfannschmidt commented on Jun 23, 2017

    @RonnyPfannschmidt
    Member

    @The-Compiler how about

    monkeypatch.repalce_module(name, obj)
    monkepatch.inhibit_module(name, exception)
    
  6. Zac-HD commented on Dec 7, 2018

    @Zac-HD
    Member

    Closing as "inactive and should probably be a plugin".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions