...

Source file src/cmd/cgo/internal/teststdio/stdio_test.go

Documentation: cmd/cgo/internal/teststdio

     1  // Copyright 2019 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package stdio_test
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/cgo/internal/cgotest"
    10  	"internal/testenv"
    11  	"log"
    12  	"os"
    13  	"os/exec"
    14  	"path/filepath"
    15  	"strings"
    16  	"testing"
    17  )
    18  
    19  func TestMain(m *testing.M) {
    20  	log.SetFlags(log.Lshortfile)
    21  	os.Exit(testMain(m))
    22  }
    23  
    24  func testMain(m *testing.M) int {
    25  	GOPATH, err := os.MkdirTemp("", "cgostdio")
    26  	if err != nil {
    27  		log.Panic(err)
    28  	}
    29  	defer os.RemoveAll(GOPATH)
    30  	os.Setenv("GOPATH", GOPATH)
    31  
    32  	// Copy testdata into GOPATH/src/cgostdio, along with a go.mod file
    33  	// declaring the same path.
    34  	modRoot := filepath.Join(GOPATH, "src", "cgostdio")
    35  	if err := cgotest.OverlayDir(modRoot, "testdata"); err != nil {
    36  		log.Panic(err)
    37  	}
    38  	if err := os.Chdir(modRoot); err != nil {
    39  		log.Panic(err)
    40  	}
    41  	os.Setenv("PWD", modRoot)
    42  	if err := os.WriteFile("go.mod", []byte("module cgostdio\n"), 0666); err != nil {
    43  		log.Panic(err)
    44  	}
    45  
    46  	return m.Run()
    47  }
    48  
    49  // TestTestRun runs a cgo test that doesn't depend on non-standard libraries.
    50  func TestTestRun(t *testing.T) {
    51  	testenv.MustHaveGoRun(t)
    52  	testenv.MustHaveCGO(t)
    53  
    54  	for _, file := range [...]string{
    55  		"chain.go",
    56  		"fib.go",
    57  		"hello.go",
    58  	} {
    59  		file := file
    60  		wantFile := strings.Replace(file, ".go", ".out", 1)
    61  		t.Run(file, func(t *testing.T) {
    62  			cmd := exec.Command("go", "run", file)
    63  			got, err := cmd.CombinedOutput()
    64  			if err != nil {
    65  				t.Fatalf("%v: %s\n%s", cmd, err, got)
    66  			}
    67  			got = bytes.ReplaceAll(got, []byte("\r\n"), []byte("\n"))
    68  			want, err := os.ReadFile(wantFile)
    69  			if err != nil {
    70  				t.Fatal("reading golden output:", err)
    71  			}
    72  			if !bytes.Equal(got, want) {
    73  				t.Errorf("'%v' output does not match expected in %s. Instead saw:\n%s", cmd, wantFile, got)
    74  			}
    75  		})
    76  	}
    77  }
    78  

View as plain text