Coverage for tests/unit/json_serialize/test_util.py: 96%

49 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-04 03:33 -0600

1from collections import namedtuple 

2from typing import NamedTuple 

3 

4import pytest 

5 

6# Module code assumed to be imported from my_module 

7from muutils.json_serialize.util import ( 

8 UniversalContainer, 

9 _recursive_hashify, 

10 isinstance_namedtuple, 

11 safe_getsource, 

12 string_as_lines, 

13 try_catch, 

14) 

15 

16 

17def test_universal_container(): 

18 uc = UniversalContainer() 

19 assert "anything" in uc 

20 assert 123 in uc 

21 assert None in uc 

22 

23 

24def test_isinstance_namedtuple(): 

25 Point = namedtuple("Point", ["x", "y"]) 

26 p = Point(1, 2) 

27 assert isinstance_namedtuple(p) 

28 assert not isinstance_namedtuple((1, 2)) 

29 

30 class Point2(NamedTuple): 

31 x: int 

32 y: int 

33 

34 p2 = Point2(1, 2) 

35 assert isinstance_namedtuple(p2) 

36 

37 

38def test_try_catch(): 

39 @try_catch 

40 def raises_value_error(): 

41 raise ValueError("test error") 

42 

43 @try_catch 

44 def normal_func(x): 

45 return x 

46 

47 assert raises_value_error() == "ValueError: test error" 

48 assert normal_func(10) == 10 

49 

50 

51def test_recursive_hashify(): 

52 assert _recursive_hashify({"a": [1, 2, 3]}) == (("a", (1, 2, 3)),) 

53 assert _recursive_hashify([1, 2, 3]) == (1, 2, 3) 

54 assert _recursive_hashify(123) == 123 

55 with pytest.raises(ValueError): 

56 _recursive_hashify(object(), force=False) 

57 

58 

59def test_string_as_lines(): 

60 assert string_as_lines("line1\nline2\nline3") == ["line1", "line2", "line3"] 

61 assert string_as_lines(None) == [] 

62 

63 

64def test_safe_getsource(): 

65 def sample_func(): 

66 pass 

67 

68 source = safe_getsource(sample_func) 

69 print(f"Source of sample_func: {source}") 

70 assert "def sample_func():" in source[0] 

71 

72 def raises_error(): 

73 raise Exception("test error") 

74 

75 wrapped_func = try_catch(raises_error) 

76 error_source = safe_getsource(wrapped_func) 

77 print(f"Source of wrapped_func: {error_source}") 

78 # Check for the original function's source since the decorator doesn't change this 

79 assert any("def raises_error():" in line for line in error_source)