Coverage for pyquickhelper/pycode/unittest_assert.py: 100%

39 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-03 02:21 +0200

1""" 

2@file 

3@brief Helpers for unit tests. 

4""" 

5import numpy 

6import pandas 

7 

8 

9def getstate(obj, recursive=True, type_stop=None, type_stack=None, done=None): 

10 """ 

11 Returns the state of an objects. It cannot be used 

12 to restore the object. 

13 

14 :param obj: object 

15 :param recursive: unfold every object 

16 :param type_stop: stop recursion when type is in this list 

17 :param type_stack: list of types if an exception is raised 

18 :param done: already processed objects (avoids infinite recursion) 

19 :return: state (always as dictionay) 

20 """ 

21 if done is not None and id(obj) in done: 

22 return id(obj) 

23 if obj is None: 

24 return None 

25 if type_stop is None: 

26 type_stop = ( 

27 int, float, str, bytes, 

28 numpy.ndarray, pandas.DataFrame) 

29 if numpy.isscalar(obj): 

30 return obj 

31 if isinstance(obj, type_stop): 

32 return obj # pragma: no cover 

33 

34 if type_stack is None: 

35 type_stack = [type(obj)] 

36 else: 

37 type_stack = type_stack.copy() 

38 type_stack.append(type(obj)) 

39 

40 if done is None: 

41 done = set() 

42 done.add(id(obj)) 

43 

44 if type(obj) == list: 

45 state = [getstate(o, recursive=recursive, type_stop=type_stop, 

46 type_stack=type_stack, done=done) 

47 for o in obj] 

48 return state 

49 if type(obj) == set: 

50 state = set(getstate(o, recursive=recursive, type_stop=type_stop, 

51 type_stack=type_stack, done=done) 

52 for o in obj) 

53 return state 

54 if type(obj) == tuple: 

55 state = tuple(getstate(o, recursive=recursive, type_stop=type_stop, 

56 type_stack=type_stack, done=done) 

57 for o in obj) 

58 return state 

59 if type(obj) == dict: 

60 state = {a: getstate(o, recursive=recursive, type_stop=type_stop, 

61 type_stack=type_stack, done=done) 

62 for a, o in obj.items()} 

63 return state 

64 

65 try: 

66 state = obj.__getstate__() 

67 except AttributeError: 

68 try: 

69 state = obj.__dict__.copy() 

70 except AttributeError as eee: # pragma: no cover 

71 raise NotImplementedError( 

72 "Unable to retrieve state of object %r, type_stack=%r." 

73 "" % (type(obj), ", ".join(map(str, type_stack)))) from eee 

74 except Exception as ee: # pragma: no cover 

75 raise NotImplementedError( 

76 "Unable to retrieve state of object %r, type_stack=%r." 

77 "" % (type(obj), ", ".join(map(str, type_stack)))) from ee 

78 except Exception as eeee: 

79 raise NotImplementedError( 

80 "Unable to retrieve state of object %r, type_stack=%r." 

81 "" % (type(obj), ", ".join(map(str, type_stack)))) from eeee 

82 

83 if not recursive: 

84 return state # pragma: no cover 

85 return getstate(state, recursive=True, type_stop=type_stop, 

86 type_stack=type_stack, done=done)