dcefc5ca24
This allows us to round-trip Body to JSON and back without any loss as long as the expression source codes are always valid UTF-8, and we require that during expression parsing anyway so that is a fine restriction. The JSON encoding is a little noisy to read due to the extra annotations required to be lossless (including source ranges) but still relatively compact due to the base64-VLQ encoding of the source location information.
48 lines
852 B
Go
48 lines
852 B
Go
package hclpack
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/google/go-cmp/cmp"
|
|
|
|
"github.com/hashicorp/hcl2/hcl"
|
|
)
|
|
|
|
func TestJSONRoundTrip(t *testing.T) {
|
|
src := `
|
|
service "example" {
|
|
priority = 2
|
|
platform {
|
|
os = "linux"
|
|
arch = "amd64"
|
|
}
|
|
process "web" {
|
|
exec = ["./webapp"]
|
|
}
|
|
process "worker" {
|
|
exec = ["./worker"]
|
|
}
|
|
}
|
|
`
|
|
|
|
startBody, diags := PackNativeFile([]byte(src), "example.svc", hcl.Pos{Line: 1, Column: 1})
|
|
if diags.HasErrors() {
|
|
t.Fatalf("Failed to parse: %s", diags.Error())
|
|
}
|
|
|
|
jb, err := startBody.MarshalJSON()
|
|
if err != nil {
|
|
t.Fatalf("Failed to marshal: %s", err)
|
|
}
|
|
|
|
endBody := &Body{}
|
|
err = endBody.UnmarshalJSON(jb)
|
|
if err != nil {
|
|
t.Fatalf("Failed to unmarshal: %s", err)
|
|
}
|
|
|
|
if !cmp.Equal(startBody, endBody) {
|
|
t.Errorf("incorrect result\n%s", cmp.Diff(startBody, endBody))
|
|
}
|
|
}
|