github.com/hashicorp/terraform-plugin-sdk@v1.17.2/internal/states/statefile/roundtrip_test.go (about)

     1  package statefile
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io/ioutil"
     7  	"os"
     8  	"path/filepath"
     9  	"sort"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/go-test/deep"
    14  
    15  	tfversion "github.com/hashicorp/terraform-plugin-sdk/internal/version"
    16  )
    17  
    18  func TestRoundtrip(t *testing.T) {
    19  	const dir = "testdata/roundtrip"
    20  	entries, err := ioutil.ReadDir(dir)
    21  	if err != nil {
    22  		t.Fatal(err)
    23  	}
    24  
    25  	currentVersion := tfversion.Version
    26  
    27  	for _, info := range entries {
    28  		const inSuffix = ".in.tfstate"
    29  		const outSuffix = ".out.tfstate"
    30  
    31  		if info.IsDir() {
    32  			continue
    33  		}
    34  		inName := info.Name()
    35  		if !strings.HasSuffix(inName, inSuffix) {
    36  			continue
    37  		}
    38  		name := inName[:len(inName)-len(inSuffix)]
    39  		outName := name + outSuffix
    40  
    41  		t.Run(name, func(t *testing.T) {
    42  			ir, err := os.Open(filepath.Join(dir, inName))
    43  			if err != nil {
    44  				t.Fatal(err)
    45  			}
    46  			oSrcWant, err := ioutil.ReadFile(filepath.Join(dir, outName))
    47  			if err != nil {
    48  				t.Fatal(err)
    49  			}
    50  
    51  			f, err := Read(ir)
    52  			if err != nil {
    53  				t.Fatalf("unexpected error: %s", err)
    54  			}
    55  
    56  			var buf bytes.Buffer
    57  			err = Write(f, &buf)
    58  			if err != nil {
    59  				t.Fatal(err)
    60  			}
    61  			oSrcGot := buf.Bytes()
    62  
    63  			var oGot, oWant map[string]interface{}
    64  			err = json.Unmarshal(oSrcGot, &oGot)
    65  			if err != nil {
    66  				t.Fatalf("result isn't JSON: %s", err)
    67  			}
    68  			err = json.Unmarshal(oSrcWant, &oWant)
    69  			if err != nil {
    70  				t.Fatalf("wanted result isn't JSON: %s", err)
    71  			}
    72  
    73  			// A newly written state should always reflect the current terraform version.
    74  			oWant["terraform_version"] = currentVersion
    75  
    76  			problems := deep.Equal(oGot, oWant)
    77  			sort.Strings(problems)
    78  			for _, problem := range problems {
    79  				t.Error(problem)
    80  			}
    81  		})
    82  	}
    83  }