Coverage for tdom/utils_test.py: 100%

54 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-17 19:54 +0000

1from string.templatelib import Interpolation 

2 

3from .utils import convert, format_interpolation 

4 

5 

6class Convertible: 

7 def __str__(self) -> str: 

8 return "Convertible str" 

9 

10 def __repr__(self) -> str: 

11 return "Convertible repr" 

12 

13 

14def test_convert_none(): 

15 value = Convertible() 

16 assert convert(value, None) is value 

17 

18 

19def test_convert_a(): 

20 value = Convertible() 

21 assert convert(value, "a") == "Convertible repr" 

22 assert convert("Café", "a") == "'Caf\\xe9'" 

23 

24 

25def test_convert_r(): 

26 value = Convertible() 

27 assert convert(value, "r") == "Convertible repr" 

28 

29 

30def test_convert_s(): 

31 value = Convertible() 

32 assert convert(value, "s") == "Convertible str" 

33 

34 

35def test_format_interpolation_no_formatting(): 

36 value = Convertible() 

37 interp = Interpolation(value, expression="", conversion=None, format_spec="") 

38 assert format_interpolation(interp) is value 

39 

40 

41def test_format_interpolation_a(): 

42 value = Convertible() 

43 interp = Interpolation(value, expression="", conversion="a", format_spec="") 

44 assert format_interpolation(interp) == "Convertible repr" 

45 

46 

47def test_format_interpolation_r(): 

48 value = Convertible() 

49 interp = Interpolation(value, expression="", conversion="r", format_spec="") 

50 assert format_interpolation(interp) == "Convertible repr" 

51 

52 

53def test_format_interpolation_s(): 

54 value = Convertible() 

55 interp = Interpolation(value, expression="", conversion="s", format_spec="") 

56 assert format_interpolation(interp) == "Convertible str" 

57 

58 

59def test_format_interpolation_default_formatting(): 

60 value = 42 

61 interp = Interpolation(value, expression="", conversion=None, format_spec="5d") 

62 assert format_interpolation(interp) == " 42" 

63 

64 

65def test_format_interpolation_custom_formatter_match_exact(): 

66 value = 42 

67 interp = Interpolation(value, expression="", conversion=None, format_spec="custom") 

68 

69 def formatter(val: object, spec: str) -> str: 

70 return f"formatted-{val}-{spec}" 

71 

72 assert ( 

73 format_interpolation(interp, formatters=[("custom", formatter)]) 

74 == "formatted-42-custom" 

75 ) 

76 

77 

78def test_format_interpolation_custom_formatter_match_predicate(): 

79 value = 42 

80 interp = Interpolation( 

81 value, expression="", conversion=None, format_spec="custom123" 

82 ) 

83 

84 def matcher(spec: str) -> bool: 

85 return spec.startswith("custom") 

86 

87 def formatter(val: object, spec: str) -> str: 

88 return f"formatted-{val}-{spec}" 

89 

90 assert ( 

91 format_interpolation(interp, formatters=[(matcher, formatter)]) 

92 == "formatted-42-custom123" 

93 )