pytorch/test/torch_np/test_function_base.py
Evgeni Burovski 92c49e2168 MAINT/TST: pytorch-ify torch._numpy tests (added tests only, not vendored) (#109593)
1. Inherit from TestCase
2. Use pytorch parametrization
3. Use unittest.expectedFailure to mark xfails

All this to make pytest-less invocation work:

$ python test/torch_np/test_basic.py

Furthermor, tests can now be run under dynamo, and we see first errors:

```
$ PYTORCH_TEST_WITH_DYNAMO=1 python test/torch_np/test_basic.py -k test_toscalar_list_func
.E.
======================================================================
ERROR: test_toscalar_list_func_<function shape at 0x7f9b83a4fc10>_np_func_<function shape at 0x7f9a8dd38af0> (__main__.TestOneArrToScalar)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/ev-br/repos/pytorch/torch/testing/_internal/common_utils.py", line 356, in instantiated_test
    test(self, **param_kwargs)
  File "test/torch_np/test_basic.py", line 232, in test_toscalar_list
    @parametrize("func, np_func", one_arg_scalar_funcs)
  File "/home/ev-br/repos/pytorch/torch/nn/modules/module.py", line 1519, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/ev-br/repos/pytorch/torch/nn/modules/module.py", line 1528, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/ev-br/repos/pytorch/torch/_dynamo/eval_frame.py", line 406, in _fn
    return fn(*args, **kwargs)
  File "/home/ev-br/repos/pytorch/torch/fx/graph_module.py", line 726, in call_wrapped
    return self._wrapped_call(self, *args, **kwargs)
  File "/home/ev-br/repos/pytorch/torch/fx/graph_module.py", line 305, in __call__
    raise e
  File "/home/ev-br/repos/pytorch/torch/fx/graph_module.py", line 292, in __call__
    return super(self.cls, obj).__call__(*args, **kwargs)  # type: ignore[misc]
  File "/home/ev-br/repos/pytorch/torch/nn/modules/module.py", line 1519, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/ev-br/repos/pytorch/torch/nn/modules/module.py", line 1528, in _call_impl
    return forward_call(*args, **kwargs)
  File "<eval_with_key>.2", line 5, in forward
    shape = torch._numpy._funcs_impl.shape([[1, 2, 3], [4, 5, 6]])
  File "/home/ev-br/repos/pytorch/torch/_numpy/_funcs_impl.py", line 655, in shape
    return tuple(a.shape)
AttributeError: 'list' object has no attribute 'shape'

----------------------------------------------------------------------
Ran 3 tests in 0.915s

FAILED (errors=1)
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/109593
Approved by: https://github.com/lezcano
2023-09-23 18:18:50 +00:00

108 lines
3.6 KiB
Python

# Owner(s): ["module: dynamo"]
from unittest import expectedFailure as xfail
import pytest
import torch._numpy as np
from pytest import raises as assert_raises
from torch._numpy.testing import assert_array_equal, assert_equal
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
parametrize,
run_tests,
TestCase,
)
@instantiate_parametrized_tests
class TestArange(TestCase):
def test_infinite(self):
assert_raises(
(RuntimeError, ValueError), np.arange, 0, np.inf
) # "size exceeded",
def test_nan_step(self):
assert_raises(
(RuntimeError, ValueError), np.arange, 0, 1, np.nan
) # "cannot compute length",
def test_zero_step(self):
assert_raises(ZeroDivisionError, np.arange, 0, 10, 0)
assert_raises(ZeroDivisionError, np.arange, 0.0, 10.0, 0.0)
# empty range
assert_raises(ZeroDivisionError, np.arange, 0, 0, 0)
assert_raises(ZeroDivisionError, np.arange, 0.0, 0.0, 0.0)
def test_require_range(self):
assert_raises(TypeError, np.arange)
assert_raises(TypeError, np.arange, step=3)
assert_raises(TypeError, np.arange, dtype="int64")
@xfail # (reason="XXX: arange(start=0, stop, step=1)")
def test_require_range_2(self):
assert_raises(TypeError, np.arange, start=4)
def test_start_stop_kwarg(self):
keyword_stop = np.arange(stop=3)
keyword_zerotostop = np.arange(start=0, stop=3)
keyword_start_stop = np.arange(start=3, stop=9)
assert len(keyword_stop) == 3
assert len(keyword_zerotostop) == 3
assert len(keyword_start_stop) == 6
assert_array_equal(keyword_stop, keyword_zerotostop)
@xfail # (reason="XXX: arange(..., dtype=bool)")
def test_arange_booleans(self):
# Arange makes some sense for booleans and works up to length 2.
# But it is weird since `arange(2, 4, dtype=bool)` works.
# Arguably, much or all of this could be deprecated/removed.
res = np.arange(False, dtype=bool)
assert_array_equal(res, np.array([], dtype="bool"))
res = np.arange(True, dtype="bool")
assert_array_equal(res, [False])
res = np.arange(2, dtype="bool")
assert_array_equal(res, [False, True])
# This case is especially weird, but drops out without special case:
res = np.arange(6, 8, dtype="bool")
assert_array_equal(res, [True, True])
with pytest.raises(TypeError):
np.arange(3, dtype="bool")
@parametrize("which", [0, 1, 2])
def test_error_paths_and_promotion(self, which):
args = [0, 10, 2] # start, stop, and step
args[which] = np.float64(2.0) # should ensure float64 output
assert np.arange(*args).dtype == np.float64
# Cover stranger error path, test only to achieve code coverage!
args[which] = [None, []]
with pytest.raises((ValueError, RuntimeError)):
# Fails discovering start dtype
np.arange(*args)
class TestAppend(TestCase):
# tests taken from np.append docstring
def test_basic(self):
result = np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
assert_equal(result, np.arange(1, 10, dtype=int))
# When `axis` is specified, `values` must have the correct shape.
result = np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
assert_equal(result, np.arange(1, 10, dtype=int).reshape((3, 3)))
with pytest.raises((RuntimeError, ValueError)):
np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
if __name__ == "__main__":
run_tests()