1

Suppose I have a module that does something like this:

try:
    from foo import bar
except ImportError:
    def bar():
        pass

How do I test the except ImportError block with pytest?

Brandon Dube
  • 428
  • 1
  • 10
  • 26
  • @Mangohero1 the snippet would be at the top of a module, not part of some function. There is no way for the importerror to "bubble" up into pytest. – Brandon Dube Dec 27 '17 at 18:49
  • May I ask why you want to test that? Just curious. – dvnguyen Dec 27 '17 at 18:52
  • Sorry, misread it. Wouldn't it be the same way? Prepending `test_`? – Mangohero1 Dec 27 '17 at 18:54
  • @dvnguyen I write a module that can use numba to provide a jit. If numba isn't installed, I define a jit decorator that returns the function passed to it unchanged. I know it works, but I would like to avoid the coverage penalty for not having test(s) that cover it. – Brandon Dube Dec 27 '17 at 18:59
  • @Mangohero1 -- it is part of a module, not the module's tests. There is no way to my knowledge to write a test that is `def test_when_the_module_was_imported_an_importerror_was_raised_and_handled,_test_the_importerror_catching_block():` – Brandon Dube Dec 27 '17 at 19:00

1 Answers1

0

you can mock the behavior of bar to raise an ImportError on import within your test. I would take a look at this

Alex
  • 1,432
  • 14
  • 26
  • I don't want to mock the module though, I want to test code that handles an importerror within the module. – Brandon Dube Dec 27 '17 at 19:19
  • Right, you mock the import call to reach the exception case. – Alex Dec 28 '17 at 18:34
  • Would that not require putting the test code inside the module? – Brandon Dube Dec 28 '17 at 19:09
  • No. In your test, before it executes, you need to mock the import to raise an exception. Here's a great [blog post](https://medium.com/python-pandemonium/how-to-test-your-imports-1461c1113be1) describing exactly what you need to do. – Alex Dec 28 '17 at 21:20
  • that works inside the module. In a unittest with a test runner, things are considerably more complicated. – Brandon Dube Dec 28 '17 at 21:26
  • What do you mean more complicated? Have you tried it? It shouldn't matter if it's in a test runner or not. – Alex Dec 28 '17 at 21:32
  • Yes, I've tried it. All test runners import the module under test, which will trigger the "can import" block. If a module has C extensions, then there may be a large number of references to it created by importing (for numba, there are 57). If you try to "hide" the module you want to cause an `ImportError` in this case, you will find it is very difficult to do so. The only solution that _may_ work as you describe is to have an entirely separate test suite that only tests ImportError catching blocks where you monkeypatch the module you want to fail to Import. But there must be a better way – Brandon Dube Dec 28 '17 at 21:35