[Python] How to unit test import error of a module that is actually available at testime?

Discussão em 'Python' iniciado por Stack, Dezembro 6, 2024.

  1. Stack

    Stack Membro Participativo

    How can I mock an import error of the module foo in the unit test?

    # file: bla.py
    try:
    import foo

    except ImportError:
    print("error")
    sys.exit(1)


    Baseline for the unit test:

    import bla
    import unittest

    class MyTest(unittest.TestCase):
    # what to mock (or so) here in order to raise the 'ImportError' that then raises the `sys.exit(1)`
    def test_1(self):
    with self.assertRaises(SystemExit) as err:
    importlib.reload(bla) # force reload, but fails as 'foo' is not importable
    self.assertEqual(rt.exception.code,1)

    Continue reading...

Compartilhe esta Página