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# ============================================================================ 15""" test_backend """ 16import os 17import shutil 18import pytest 19 20import mindspore.nn as nn 21from mindspore import context, ms_function 22from mindspore._checkparam import args_type_check 23from mindspore.common.initializer import initializer 24from mindspore.common.parameter import Parameter 25from mindspore.ops import operations as P 26from tests.security_utils import security_off_wrap 27 28 29def setup_module(): 30 context.set_context(mode=context.PYNATIVE_MODE) 31 32 33class Net(nn.Cell): 34 """ Net definition """ 35 36 def __init__(self): 37 super(Net, self).__init__() 38 self.add = P.Add() 39 self.x = Parameter(initializer('normal', [1, 3, 3, 4]), name='x') 40 self.y = Parameter(initializer('normal', [1, 3, 3, 4]), name='y') 41 42 @ms_function 43 def construct(self): 44 return self.add(self.x, self.y) 45 46 47def test_vm_backend(): 48 """ test_vm_backend """ 49 context.set_context(mode=context.PYNATIVE_MODE) 50 add = Net() 51 output = add() 52 assert output.asnumpy().shape == (1, 3, 3, 4) 53 54@security_off_wrap 55def test_vm_set_context(): 56 """ test_vm_set_context """ 57 context.set_context(save_graphs=True, save_graphs_path="mindspore_ir_path", mode=context.GRAPH_MODE) 58 assert context.get_context("save_graphs") 59 assert context.get_context("mode") == context.GRAPH_MODE 60 assert os.path.exists("mindspore_ir_path") 61 assert context.get_context("save_graphs_path").find("mindspore_ir_path") > 0 62 context.set_context(mode=context.PYNATIVE_MODE) 63 64 65@args_type_check(v_str=str, v_int=int, v_tuple=tuple) 66def check_input(v_str, v_int, v_tuple): 67 """ check_input """ 68 print("v_str:", v_str) 69 print("v_int:", v_int) 70 print("v_tuple:", v_tuple) 71 72 73def test_args_type_check(): 74 """ test_args_type_check """ 75 with pytest.raises(TypeError): 76 check_input(100, 100, (10, 10)) 77 with pytest.raises(TypeError): 78 check_input("name", "age", (10, 10)) 79 with pytest.raises(TypeError): 80 check_input("name", 100, "age") 81 check_input("name", 100, (10, 10)) 82 83 84def teardown_module(): 85 dirs = ['mindspore_ir_path'] 86 for item in dirs: 87 item_name = './' + item 88 if not os.path.exists(item_name): 89 continue 90 if os.path.isdir(item_name): 91 shutil.rmtree(item_name) 92 elif os.path.isfile(item_name): 93 os.remove(item_name) 94