Skip to content

Support testing np and tnp on the same test #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 51 additions & 4 deletions torch_np/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import pytest

import torch_np as tnp


def pytest_configure(config):
config.addinivalue_line("markers", "slow: very slow tests")
Expand All @@ -12,14 +14,59 @@ def pytest_addoption(parser):
parser.addoption("--nonp", action="store_true", help="error when NumPy is accessed")


class Inaccessible:
def __getattribute__(self, attr):
raise RuntimeError(f"Using --nonp but accessed np.{attr}")


def pytest_sessionstart(session):
if session.config.getoption("--nonp"):
sys.modules["numpy"] = Inaccessible()

class Inaccessible:
def __getattribute__(self, attr):
raise RuntimeError(f"Using --nonp but accessed np.{attr}")

sys.modules["numpy"] = Inaccessible()
def pytest_generate_tests(metafunc):
"""
Hook to parametrize test cases
See https://docs.pytest.org/en/6.2.x/parametrize.html#pytest-generate-tests

The logic here allows us to test with both NumPy-proper and torch_np.
Normally we'd just test torch_np, e.g.

import torch_np as np
...
def test_foo():
np.array([42])
...

but this hook allows us to test NumPy-proper as well, e.g.

def test_foo(np):
np.array([42])
...

np is a pytest parameter, which is either NumPy-proper or torch_np. This
allows us to sanity check our own tests, so that tested behaviour is
consistent with NumPy-proper.

pytest will have test names respective to the library being tested, e.g.

$ pytest --collect-only
test_foo[torch_np]
test_foo[numpy]

"""
np_params = [tnp]

try:
import numpy as np
except ImportError:
pass
else:
if not isinstance(np, Inaccessible): # i.e. --nonp was used
np_params.append(np)

if "np" in metafunc.fixturenames:
metafunc.parametrize("np", np_params)


def pytest_collection_modifyitems(config, items):
Expand Down