已合并
test: add torch.__getattribute__ API validation #41414
test: add torch.__getattribute__ API validation #41414
已合并
zhouzirui1234创建于 7月12日
1 个文件变更+49-0
Atest/test_torch_getattribute_api.py+49-0
@@ -0,0 +1,49 @@
1+"""
2+Add validation cases for torch.__getattribute__ API:
3+1. PyTorch community does not provide a direct standalone test for this API.
4+2. This file validates normal attribute lookup, dynamically added module
5+ attributes, and the AttributeError path for missing attributes.
6+"""
7+ 
8+import types
9+ 
10+import torch
11+from torch.testing._internal.common_utils import TestCase, run_tests
12+ 
13+ 
14+class TestTorchGetattributeApi(TestCase):
15+ def _torch_module_dict(self):
16+ return types.ModuleType.__getattribute__(torch, "__dict__")
17+ 
18+ def test_get_existing_attributes(self):
19+ module_dict = self._torch_module_dict()
20+ attrs = ("__config__", "Tensor", "nn", "empty")
21+ for name in attrs:
22+ # Use the module dict as the oracle instead of getattr, which shares
23+ # the same module attribute access path as torch.__getattribute__.
24+ self.assertIn(name, module_dict)
25+ self.assertIs(torch.__getattribute__(name), module_dict[name])
26+ 
27+ def test_get_dynamic_attribute(self):
28+ module_dict = self._torch_module_dict()
29+ attr_name = "_torch_npu_getattribute_test_value"
30+ attr_value = object()
31+ self.assertNotIn(attr_name, module_dict)
32+ try:
33+ setattr(torch, attr_name, attr_value)
34+ # The dynamically added module attribute should be returned directly.
35+ self.assertIn(attr_name, module_dict)
36+ self.assertIs(torch.__getattribute__(attr_name), module_dict[attr_name])
37+ finally:
38+ module_dict.pop(attr_name, None)
39+ 
40+ def test_get_missing_attribute_raises(self):
41+ module_dict = self._torch_module_dict()
42+ attr_name = "_torch_npu_missing_getattribute_test_value"
43+ self.assertNotIn(attr_name, module_dict)
44+ with self.assertRaisesRegex(AttributeError, attr_name):
45+ torch.__getattribute__(attr_name)
46+ 
47+ 
48+if __name__ == "__main__":
49+ run_tests()