opentofu/states/statefile/roundtrip_test.go

77 lines
1.4 KiB
Go
Raw Normal View History

statefile: New package for loading and saving state files Whereas the parent directory "states" contains the models that represent state in memory, this package's responsibility is in serializing a subset of that data to a JSON-based file format and then reloading that data back into memory later. For reading, this package supports state file formats going back to version 1, using lightly-adapted versions of the migration code previously used in the "terraform" package. State data is upgraded to the latest version step by step and then transformed into the in-memory state representation, which is distinct from any of the file format structs in this package to enable these to evolve separately. For writing, only the latest version (4) is supported, which is a new format that is a slightly-flattened version of the new in-memory state models introduced in the prior commit. This format retains the outputs from only the root module and it flattens out the module and instance parts of the hierarchy by including the identifiers for these inside the child object. The loader then reconstructs the multi-layer structure we use for more convenient access in memory. For now, the only testing in this package is of round-tripping different versions of state through a read and a write, ensuring the output is as desired. This exercises all of the reading, upgrading, and writing functions but should be augmented in later commits to improve coverage and introduce more focused tests for specific parts of the functionality.
2018-06-07 19:35:55 -05:00
package statefile
import (
"bytes"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"github.com/go-test/deep"
)
func TestRoundtrip(t *testing.T) {
const dir = "testdata/roundtrip"
entries, err := ioutil.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
for _, info := range entries {
const inSuffix = ".in.tfstate"
const outSuffix = ".out.tfstate"
if info.IsDir() {
continue
}
inName := info.Name()
if !strings.HasSuffix(inName, inSuffix) {
continue
}
name := inName[:len(inName)-len(inSuffix)]
outName := name + outSuffix
t.Run(name, func(t *testing.T) {
ir, err := os.Open(filepath.Join(dir, inName))
if err != nil {
t.Fatal(err)
}
oSrcWant, err := ioutil.ReadFile(filepath.Join(dir, outName))
if err != nil {
t.Fatal(err)
}
f, err := Read(ir)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
var buf bytes.Buffer
err = Write(f, &buf)
if err != nil {
t.Fatal(err)
}
oSrcGot := buf.Bytes()
var oGot, oWant interface{}
err = json.Unmarshal(oSrcGot, &oGot)
if err != nil {
t.Fatalf("result isn't JSON: %s", err)
}
err = json.Unmarshal(oSrcWant, &oWant)
if err != nil {
t.Fatalf("wanted result isn't JSON: %s", err)
}
problems := deep.Equal(oGot, oWant)
sort.Strings(problems)
for _, problem := range problems {
t.Error(problem)
}
})
}
}