github.com/brandur/modulir@v0.0.0-20240305213423-94ee82929cbd/modules/myaml/myaml_test.go (about)

     1  package myaml
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	assert "github.com/stretchr/testify/require"
     8  
     9  	"github.com/brandur/modulir/modules/mtesting"
    10  )
    11  
    12  func TestSplitFrontmatter(t *testing.T) {
    13  	type testStruct struct {
    14  		Foo string `toml:"foo"`
    15  	}
    16  
    17  	c := mtesting.NewContext()
    18  
    19  	{
    20  		path := mtesting.WriteTempFile(t, []byte(`---
    21  foo: bar
    22  ---
    23  
    24  other`))
    25  		defer os.Remove(path)
    26  
    27  		var v testStruct
    28  		content, err := ParseFileFrontmatter(c, path, &v)
    29  		assert.NoError(t, err)
    30  		assert.Equal(t, "bar", v.Foo)
    31  		assert.Equal(t, []byte("other"), content)
    32  	}
    33  
    34  	{
    35  		path := mtesting.WriteTempFile(t, []byte("other"))
    36  		defer os.Remove(path)
    37  
    38  		var v testStruct
    39  		content, err := ParseFileFrontmatter(c, path, &v)
    40  		assert.NoError(t, err)
    41  		assert.Equal(t, "", v.Foo)
    42  		assert.Equal(t, []byte("other"), content)
    43  	}
    44  
    45  	{
    46  		path := mtesting.WriteTempFile(t, []byte(`---
    47  foo: bar
    48  ---
    49  `))
    50  		defer os.Remove(path)
    51  
    52  		var v testStruct
    53  		content, err := ParseFileFrontmatter(c, path, &v)
    54  		assert.NoError(t, err)
    55  		assert.Equal(t, "bar", v.Foo)
    56  		assert.Equal(t, []byte(nil), content)
    57  	}
    58  
    59  	{
    60  		path := mtesting.WriteTempFile(t, []byte(`foo = "bar"
    61  foo: bar
    62  ---
    63  `))
    64  		defer os.Remove(path)
    65  
    66  		var v testStruct
    67  		content, err := ParseFileFrontmatter(c, path, &v)
    68  		assert.Equal(t, errBadFrontmatter, err)
    69  		assert.Equal(t, []byte(nil), content)
    70  	}
    71  }