Coverage for tests / test_dtd / test_go.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-08 15:04 -0800

1"""Tests for Data Transformation Density (Go).""" 

2 

3from analyzers.go import analyze_source 

4 

5 

6def _dtd(code: str) -> int: 

7 """Return DTD of the first function in code.""" 

8 result = analyze_source(code) 

9 assert result.functions, f"No functions found in:\n{code}" 

10 return result.functions[0].dtd 

11 

12 

13def _dtds(code: str) -> dict[str, int]: 

14 """Return {name: dtd} for all functions in code.""" 

15 result = analyze_source(code) 

16 return {f.name: f.dtd for f in result.functions} 

17 

18 

19# --- Empty --- 

20 

21def test_empty_function(): 

22 code = "package main\nfunc f() {}" 

23 assert _dtd(code) == 0 

24 

25 

26# --- Struct literal --- 

27 

28def test_struct_literal(): 

29 code = """ 

30package main 

31 

32type Point struct { 

33 X int 

34 Y int 

35} 

36 

37func f() Point { 

38 return Point{X: 1, Y: 2} 

39} 

40""" 

41 # composite_literal at depth 1, 2 keyed_elements x 1 = 2 

42 assert _dtd(code) == 2 

43 

44 

45# --- Slice literal --- 

46 

47def test_slice_literal(): 

48 code = """ 

49package main 

50 

51func f() []int { 

52 return []int{1, 2, 3} 

53} 

54""" 

55 # composite_literal at depth 1, 3 literal_elements x 1 = 3 

56 assert _dtd(code) == 3 

57 

58 

59# --- Map literal --- 

60 

61def test_map_literal(): 

62 code = """ 

63package main 

64 

65func f() map[string]int { 

66 return map[string]int{"a": 1, "b": 2} 

67} 

68""" 

69 # composite_literal at depth 1, 2 keyed_elements x 1 = 2 

70 assert _dtd(code) == 2 

71 

72 

73# --- Nested composite --- 

74 

75def test_nested_composite(): 

76 code = """ 

77package main 

78 

79type Inner struct { 

80 Value int 

81} 

82 

83type Outer struct { 

84 Items []Inner 

85} 

86 

87func f() Outer { 

88 return Outer{ 

89 Items: []Inner{ 

90 Inner{Value: 1}, 

91 Inner{Value: 2}, 

92 }, 

93 } 

94} 

95""" 

96 # Outer composite at depth 1: keyed_element "Items: ..." -> 1 

97 # []Inner{} composite at depth 2 (nested in the value of the keyed_element) 

98 # 2 literal_elements at depth 2 -> 4 

99 # Each Inner{} composite at depth 3: keyed_element at depth 3 -> 3 each -> 6 

100 # total = 1 + 4 + 6 = 11 

101 assert _dtd(code) == 11 

102 

103 

104# --- Nested named closure --- 

105 

106def test_nested_named_closure(): 

107 code = """ 

108package main 

109 

110func outer() { 

111 x := map[string]int{"a": 1} 

112 inner := func() { 

113 y := []int{1, 2, 3} 

114 } 

115 _ = inner 

116 _ = x 

117} 

118""" 

119 dtds = _dtds(code) 

120 assert dtds["outer"] == 1 # only map[string]int{"a": 1} -> 1 keyed_element x 1 

121 assert dtds["inner"] == 3 # []int{1, 2, 3} -> 3 literal_elements x 1