github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/experimental/gojs/example/cat_test.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"os/exec"
     8  	"testing"
     9  
    10  	"github.com/wasilibs/wazerox/internal/testing/maintester"
    11  	"github.com/wasilibs/wazerox/internal/testing/require"
    12  )
    13  
    14  // Test_main ensures the following will work:
    15  //
    16  //	go run cat.go /test.txt
    17  func Test_main(t *testing.T) {
    18  	stdout, stderr := maintester.TestMain(t, main, "cat", "test.txt")
    19  	require.Equal(t, "", stderr)
    20  	require.Equal(t, "greet filesystem\n", stdout)
    21  }
    22  
    23  // TestMain compiles the wasm on-demand, which uses the runner's Go as opposed
    24  // to a binary checked in, which would be pinned to one version. This is
    25  // separate from Test_main to show that compilation doesn't dominate the
    26  // execution time.
    27  func TestMain(m *testing.M) {
    28  	// Notably our scratch containers don't have go, so don't fail tests.
    29  	if err := compileFromGo(); err != nil {
    30  		log.Println("Skipping tests due to:", err)
    31  		os.Exit(0)
    32  	}
    33  	os.Exit(m.Run())
    34  }
    35  
    36  // compileFromGo compiles "stars/main.go" on demand as the binary generated is
    37  // too big (>7MB) to check into the source tree.
    38  func compileFromGo() error {
    39  	cmd := exec.Command("go", "build", "-o", "main.wasm", ".")
    40  	cmd.Dir = "cat"
    41  	cmd.Env = append(os.Environ(), "GOARCH=wasm", "GOOS=js", "GOWASM=satconv,signext")
    42  	if out, err := cmd.CombinedOutput(); err != nil {
    43  		return fmt.Errorf("go build: %v\n%s", err, out)
    44  	}
    45  	return nil
    46  }