github.com/mcuadros/ascode@v1.3.1/starlark/types/examples_test.go (about)

     1  package types
     2  
     3  import (
     4  	"bufio"
     5  	"os"
     6  	stdos "os"
     7  	"path/filepath"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"go.starlark.net/starlark"
    13  )
    14  
    15  func TestExamples(t *testing.T) {
    16  	pwd, _ := stdos.Getwd()
    17  	defer func() {
    18  		stdos.Chdir(pwd)
    19  	}()
    20  
    21  	err := stdos.Chdir(filepath.Join(pwd, "testdata", "examples"))
    22  	assert.NoError(t, err)
    23  
    24  	tests, err := filepath.Glob("*.star")
    25  	assert.NoError(t, err)
    26  
    27  	for _, test := range tests {
    28  		if test == "evaluable.star" {
    29  			continue
    30  		}
    31  
    32  		doTestExample(t, test)
    33  	}
    34  }
    35  
    36  func doTestExample(t *testing.T, filename string) {
    37  	var output string
    38  	printer := func(_ *starlark.Thread, msg string) {
    39  		if output != "" {
    40  			output += "\n"
    41  		}
    42  
    43  		output += msg
    44  	}
    45  
    46  	doTestPrint(t, filename, printer)
    47  	expected := strings.TrimSpace(getExpectedFromExample(t, filename))
    48  
    49  	assert.Equalf(t, strings.TrimSpace(output), expected, filename)
    50  }
    51  
    52  func getExpectedFromExample(t *testing.T, filename string) string {
    53  	f, err := os.Open(filename)
    54  	assert.NoError(t, err)
    55  	defer f.Close()
    56  
    57  	var expected []string
    58  	scanner := bufio.NewScanner(f)
    59  	var capture bool
    60  	for scanner.Scan() {
    61  		line := scanner.Text()
    62  		if line == "# Output:" {
    63  			capture = true
    64  			continue
    65  		}
    66  
    67  		if !capture {
    68  			continue
    69  		}
    70  
    71  		if len(line) >= 2 {
    72  			line = line[2:]
    73  		} else {
    74  			line = ""
    75  		}
    76  
    77  		expected = append(expected, line)
    78  
    79  	}
    80  
    81  	return strings.Join(expected, "\n")
    82  }