1package changes
2
3import (
4	"testing"
5
6	"github.com/google/go-cmp/cmp"
7)
8
9func TestModuleGraph(t *testing.T) {
10	var cases = map[string]struct {
11		dependencies map[string][]string
12		modules      []string
13		wantGraph    ModuleGraph
14	}{
15		"simple": {
16			map[string][]string{
17				"a": {"b"},
18			},
19			[]string{"a", "b"},
20			ModuleGraph{
21				"b": []string{"a"},
22			},
23		},
24		"cyclical": {
25			map[string][]string{
26				"a": {"b"},
27				"b": {"a"},
28			},
29			[]string{"a", "b"},
30			ModuleGraph{
31				"a": []string{"b"},
32				"b": []string{"a"},
33			},
34		},
35		"chain": {
36			map[string][]string{
37				"a": {"b"},
38				"b": {"c"},
39				"c": {"d"},
40			},
41			[]string{"a", "b", "c", "d"},
42			ModuleGraph{
43				"d": []string{"c"},
44				"c": []string{"b"},
45				"b": []string{"a"},
46			},
47		},
48		"two groups": {
49			map[string][]string{
50				"a": {"b"},
51				"c": {"d"},
52			},
53			[]string{"a", "b", "c", "d"},
54			ModuleGraph{
55				"b": []string{"a"},
56				"d": []string{"c"},
57			},
58		},
59	}
60
61	for id, tt := range cases {
62		t.Run(id, func(t *testing.T) {
63			goClient := mockGolist{dependencies: tt.dependencies}
64
65			graph, err := moduleGraph(&goClient, tt.modules)
66			if err != nil {
67				t.Fatal(err)
68			}
69
70			if diff := cmp.Diff(tt.wantGraph, graph); diff != "" {
71				t.Errorf("expect dependencies to match (-want, +got):\n%v", diff)
72			}
73		})
74	}
75}
76
77func TestModuleGraph_DependencyUpdates(t *testing.T) {
78	var cases = map[string]struct {
79		modGraph       ModuleGraph
80		updatedModules []string
81		wantUpdates    map[string][]string
82	}{
83		"no dependencies": {
84			ModuleGraph{},
85			[]string{"a", "b"},
86			map[string][]string{},
87		},
88		"two modules": {
89			ModuleGraph{
90				"a": []string{"b"},
91			},
92			[]string{"a"},
93			map[string][]string{
94				"b": {"a"},
95			},
96		},
97		"four module chain": {
98			ModuleGraph{
99				"a": []string{"b"},
100				"b": []string{"c"},
101				"c": []string{"d"},
102			},
103			[]string{"a"},
104			map[string][]string{
105				"b": {"a"},
106				"c": {"b"},
107				"d": {"c"},
108			},
109		},
110		"cyclic dependency": {
111			ModuleGraph{
112				"a": []string{"b"},
113				"b": []string{"a"},
114			},
115			[]string{"a"},
116			map[string][]string{
117				"a": {"b"},
118				"b": {"a"},
119			},
120		},
121		"multiple dependency updates": {
122			ModuleGraph{
123				"a": []string{"c"}, // c depends on both a and b
124				"b": []string{"c"},
125			},
126			[]string{"a", "b"},
127			map[string][]string{
128				"c": {"a", "b"},
129			},
130		},
131	}
132
133	for id, tt := range cases {
134		t.Run(id, func(t *testing.T) {
135			updates := tt.modGraph.dependencyUpdates(tt.updatedModules)
136
137			if diff := cmp.Diff(tt.wantUpdates, updates); diff != "" {
138				t.Errorf("expect dependencies to match (-want, +got):\n%v", diff)
139			}
140		})
141	}
142}
143