1# Copyright 2020 Huawei Technologies Co., Ltd 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15import mindspore.context as context 16from mindspore import Tensor, ms_function 17from mindspore.common import dtype as mstype 18import pytest 19 20ZERO = Tensor([0], mstype.int32) 21ONE = Tensor([1], mstype.int32) 22 23 24@ms_function 25def f(x): 26 y = ZERO 27 if x < 0: 28 y = f(x - 3) 29 elif x < 3: 30 y = x * f(x - 1) 31 elif x < 5: 32 y = x * f(x - 2) 33 else: 34 y = f(x - 4) 35 z = y + 1 36 return z 37 38 39@ms_function 40def fr(x): 41 y = ZERO 42 if x < 0: 43 y = ONE 44 elif x < 3: 45 y = x * fr(x - 1) 46 elif x < 5: 47 y = x * fr(x - 2) 48 else: 49 y = fr(x - 4) 50 z = y + 1 51 return z 52 53 54@ms_function 55def f_pythonerr(x): 56 if x > 0: 57 return f_pythonerr(x - 1) 58 return NOT_DEF 59 60 61def test_python_error(): 62 context.set_context(mode=context.GRAPH_MODE) 63 x = Tensor([5], mstype.int32) 64 try: 65 f_pythonerr(x) 66 except NameError as e: 67 assert 'not defined' in str(e) 68 69 70@ms_function 71def f_recrusive_endless(x): 72 if x > 0: 73 return f_recrusive_endless(x - 1) 74 return f_recrusive_endless(x + 1) 75 76 77def test_recrusive_endless(): 78 context.set_context(mode=context.GRAPH_MODE) 79 x = Tensor([5], mstype.int32) 80 try: 81 f_recrusive_endless(x) 82 except RuntimeError as e: 83 assert 'endless loop' in str(e) 84 85 86def test_endless(): 87 context.set_context(mode=context.GRAPH_MODE) 88 x = Tensor([5], mstype.int32) 89 try: 90 f(x) 91 except RuntimeError as e: 92 assert 'endless loop' in str(e) 93 94 95@ms_function 96def f_ok(x): 97 if x > 0: 98 return f_ok(x - 1) + 1 99 return ONE 100 101 102@pytest.mark.skip(reason="backend is not supported yet") 103def test_f_ok(): 104 context.set_context(mode=context.GRAPH_MODE) 105 x = Tensor([3], mstype.int32) 106 ret = f_ok(x) 107 expect = Tensor([4], mstype.int32) 108 assert ret == expect 109 110 111@pytest.mark.skip(reason="backend is not supported yet") 112def test_recrusive_fun(): 113 context.set_context(mode=context.GRAPH_MODE) 114 x = Tensor([5], mstype.int32) 115 ret = fr(x) 116 expect = Tensor([3], mstype.int32) 117 assert ret == expect 118 119 120if __name__ == "__main__": 121 test_endless() 122