Make pytest ignore gathering a file if a module is not installed

Viewed 13

I am in as situation where I am using a module as an optional package. My goal is to make the test succeed even if I do not have that optional package installed.

The problem is I need to inherit some classes from that module. Even if I skip the tests, pytest gathers all the files and throws an error while gathering the file that is inheriting the class.

Is there a way to ask pytest to ignore this file if a certain module does not exist?

For example,

if have_tf and have_tfa:
    from tensorflow.keras.models import Model
    from tensorflow.keras.layers import Layer

This I can do, but

class UNet3D(Layer):

Throws an error because it fails to find Layer if tensorflow is not installed while gathering the files.

Could there be a way? I could lose all the inheritence, but that would make the code super messy.

Thank you!

1 Answers

You could create fake Model and Layer classes if the imports fail. E.g:

import pytest

try:
    from tensorflow.keras.models import Model
    from tensorflow.keras.layers import Layer
except ImportError:
    have_tf = False

    class Model:
        pass

    class Layer:
        pass


class UNet3D(Layer):
    def __init__(self):
        self.do_something()


@pytest.mark.skipif(not have_tf, reason="tensorflow is not installed")
def test_unet3d():
    assert True

Running pytest -v on a system without Tensorflow yields:

============================= test session starts ==============================
platform linux -- Python 3.10.6, pytest-7.1.3, pluggy-1.0.0 -- /home/lars/.local/share/virtualenvs/python-LD_ZK5QN/bin/python
cachedir: .pytest_cache
rootdir: /home/lars/tmp/python
collecting ... collected 1 item

test_example.py::test_unet3d SKIPPED (tensorflow is not installed)       [100%]

============================== 1 skipped in 0.01s ==============================
Related