Skip to content

Commit

Permalink
Merge pull request #157 from grafana/fix-155
Browse files Browse the repository at this point in the history
thema: Try to return a concrete result from #Translate
  • Loading branch information
sam boyer committed May 18, 2023
2 parents b3fb56d + 844bb3f commit 3adcb5f
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
6 changes: 5 additions & 1 deletion instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,12 @@ func (i *Instance) Translate(to SyntacticVersion) (*Instance, TranslationLacunas
lac := make(multiTranslationLacunas, 0)
out.LookupPath(cue.MakePath(cue.Str("lacunas"))).Decode(&lac)

// Attempt to evaluate #Translate result into a concrete cue.Value, if possible.
// Otherwise, all the #Translate results are non-concrete, which leads to undesired effects.
raw, _ := out.LookupPath(cue.MakePath(cue.Str("result"), cue.Str("result"))).Default()

return &Instance{
raw: out.LookupPath(cue.MakePath(cue.Str("result"), cue.Str("result"))),
raw: raw,
name: i.name,
sch: newsch,
}, lac
Expand Down
56 changes: 56 additions & 0 deletions instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,59 @@ func marshalAndWrite(tc *vanilla.Test, w io.Writer, any interface{}) {
_, err = w.Write(append(bytes, '\n'))
require.NoError(tc, err)
}

// TestInstance_LookupPathOnTranslatedInstance is a regression test
// specifically written for https://github.com/grafana/thema/issues/155.
//
// Caused because [Instance.Translate] results were always non-concrete,
// when the result evaluates to something concrete.
//
// So, this test checks that [cue.Value.LookupPath] behaves as expected
// when used over an [Instance.Translate] result.
func TestInstance_LookupPathOnTranslatedInstance(t *testing.T) {
ctx := cuecontext.New()
rt := NewRuntime(ctx)

// Initialize lineage for testing
linstr := `name: "simple"
schemas: [
{
version: [0, 0]
schema:
{
title: string
},
},
{
version: [0, 1]
schema:
{
title: string
header?: string
},
},
]`
linval := rt.Context().CompileString(linstr)
lin, err := BindLineage(linval, rt)
require.NoError(t, err)

// Initialize cue.Value
expected := "foo"
val := ctx.CompileString(fmt.Sprintf(`{"title": "%s"}`, expected))

// Validate cue.Value
inst := lin.ValidateAny(val)
require.Equal(t, SV(0, 0), inst.Schema().Version())

got, err := inst.Underlying().LookupPath(cue.ParsePath("title")).String()
require.NoError(t, err)
require.Equal(t, expected, got)

// Translate cue.Value (no lacunas)
tinst, _ := inst.Translate(SV(0, 1))
require.Equal(t, SV(0, 0), inst.Schema().Version())

got, err = tinst.Underlying().LookupPath(cue.ParsePath("title")).String()
require.NoError(t, err)
require.Equal(t, expected, got)
}

0 comments on commit 3adcb5f

Please sign in to comment.