You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_ast_finder.py 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright 2022 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. import ast
  16. import inspect
  17. from mindspore import nn
  18. from mindspore.ops import functional as F
  19. from mindspore.rewrite.ast_helpers import AstFinder
  20. class SimpleNet(nn.Cell):
  21. def __init__(self):
  22. super(SimpleNet, self).__init__()
  23. self.aaa = 1
  24. self.bbb = F.add(1, 1)
  25. def construct(self, x):
  26. x = self.aaa + x
  27. x = self.bbb + x
  28. return x
  29. def test_finder_single_type():
  30. """
  31. Feature: Class AstFinder in Package rewrite.
  32. Description: Use AstFinder to find all Assign ast node.
  33. Expectation: AstFinder can find all Assign ast node.
  34. """
  35. ast_root = ast.parse(inspect.getsource(SimpleNet))
  36. finder = AstFinder(ast_root)
  37. results = finder.find_all(ast.Assign)
  38. assert len(results) == 4
  39. for result in results:
  40. assert isinstance(result, ast.Assign)
  41. def test_finder_multi_type():
  42. """
  43. Feature: Class AstFinder in Package rewrite.
  44. Description: Use AstFinder to find all Assign and Attribute ast node.
  45. Expectation: AstFinder can find all Assign and Attribute ast node.
  46. """
  47. ast_root = ast.parse(inspect.getsource(SimpleNet))
  48. finder = AstFinder(ast_root)
  49. results = finder.find_all((ast.Assign, ast.Attribute))
  50. assert len(results) == 11
  51. assign_num = 0
  52. attribute_num = 0
  53. for result in results:
  54. if isinstance(result, ast.Assign):
  55. assign_num += 1
  56. continue
  57. if isinstance(result, ast.Attribute):
  58. attribute_num += 1
  59. continue
  60. assert False
  61. assert assign_num == 4
  62. assert attribute_num == 7