@@ -33,10 +33,12 @@ func ctxAndLogger(t *testing.T) (context.Context, slog.Logger) {
3333return context .Background (),testutil .Logger (t )
3434}
3535
36- //TestConvertStateGoldenFiles compares the output of ConvertState to a golden
36+ //TestConvertStateGolden compares the output of ConvertState to a golden
3737// file to prevent regressions. If the logic changes, update the golden files
3838// accordingly.
39- func TestConvertStateGoldenFiles (t * testing.T ) {
39+ //
40+ // This was created to aid in refactoring `ConvertState`.
41+ func TestConvertStateGolden (t * testing.T ) {
4042t .Parallel ()
4143
4244testResourceDirectories := filepath .Join ("testdata" ,"resources" )
@@ -51,22 +53,28 @@ func TestConvertStateGoldenFiles(t *testing.T) {
5153testFiles ,err := os .ReadDir (filepath .Join (testResourceDirectories ,testDirectory .Name ()))
5254require .NoError (t ,err )
5355
56+ // ConvertState works on both a plan file and a state file.
57+ // The test should create a golden file for both.
5458for _ ,step := range []string {"plan" ,"state" } {
55- planIdx := slices .IndexFunc (testFiles ,func (entry os.DirEntry )bool {
59+ srcIdc := slices .IndexFunc (testFiles ,func (entry os.DirEntry )bool {
5660return strings .HasSuffix (entry .Name (),fmt .Sprintf (".tf%s.json" ,step ))
5761})
5862dotIdx := slices .IndexFunc (testFiles ,func (entry os.DirEntry )bool {
5963return strings .HasSuffix (entry .Name (),fmt .Sprintf (".tf%s.dot" ,step ))
6064})
6165
62- if planIdx == - 1 || dotIdx == - 1 {
66+ // If the directory is missing these files, we cannot run ConvertState
67+ // on it. So it's skipped.
68+ if srcIdc == - 1 || dotIdx == - 1 {
6369continue
6470}
6571
6672t .Run (step + "_" + testDirectory .Name (),func (t * testing.T ) {
73+ // Load the paths before t.Parallel()
6774testDirectoryPath := filepath .Join (testResourceDirectories ,testDirectory .Name ())
68- planFile := filepath .Join (testDirectoryPath ,testFiles [planIdx ].Name ())
75+ planFile := filepath .Join (testDirectoryPath ,testFiles [srcIdc ].Name ())
6976dotFile := filepath .Join (testDirectoryPath ,testFiles [dotIdx ].Name ())
77+
7078t .Parallel ()
7179ctx := testutil .Context (t ,testutil .WaitMedium )
7280logger := slogtest .Make (t ,nil )
@@ -99,6 +107,8 @@ func TestConvertStateGoldenFiles(t *testing.T) {
99107dotFileRaw ,err := os .ReadFile (dotFile )
100108require .NoError (t ,err )
101109
110+ // expectedOutput is `any` to support errors too. If `ConvertState` returns an
111+ // error, that error is the golden file output.
102112var expectedOutput any
103113state ,err := terraform .ConvertState (ctx ,modules ,string (dotFileRaw ),logger )
104114if err == nil {