github.com/vugu/vugu@v0.3.6-0.20240430171613-3f6f402e014b/devutil/tinygo-compiler_test.go (about)

     1  package devutil
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"testing"
    10  )
    11  
    12  func TestTinygoCompiler(t *testing.T) {
    13  
    14  	tmpDir, err := os.MkdirTemp("", "TestTinygoCompiler")
    15  	if err != nil {
    16  		t.Fatal(err)
    17  	}
    18  	defer os.RemoveAll(tmpDir)
    19  
    20  	must(os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte(`module example.org/testtgc
    21  
    22  require github.com/vugu/html v0.0.0-20190914200101-c62dc20b8289 // indirect
    23  `), 0644))
    24  	must(os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte(`package main 
    25  
    26  import "fmt"
    27  import "github.com/vugu/html"
    28  
    29  func main() {
    30  	fmt.Printf("testapp says hello! %v\n", html.NodeType(1))
    31  }
    32  `), 0644))
    33  
    34  	goModTidy(tmpDir)
    35  	tgc := MustNewTinygoCompiler()
    36  	defer tgc.Close()
    37  	tgc.SetBuildDir(tmpDir)
    38  
    39  	outpath, err := tgc.Execute()
    40  	if err != nil {
    41  		t.Fatal(err)
    42  	}
    43  	defer os.Remove(outpath)
    44  	b, err := os.ReadFile(outpath)
    45  	if err != nil {
    46  		t.Fatal(err)
    47  	}
    48  	if string(b[:4]) != "\x00asm" {
    49  		t.Fatalf("bad asm magic num: %X", b[:4])
    50  	}
    51  	t.Logf("output file length: %d", len(b))
    52  
    53  	r, err := tgc.WasmExecJS()
    54  	if err != nil {
    55  		t.Fatal(err)
    56  	}
    57  	b, err = io.ReadAll(r)
    58  	if err != nil {
    59  		t.Fatal(err)
    60  	}
    61  	// t.Logf("wasm_exec.js contents:\n%s", b)
    62  	if !bytes.Contains(b, []byte(`global.Go`)) {
    63  		t.Fatalf("unable to find global.Go in wasm_exec.js")
    64  	}
    65  	if !bytes.Contains(b, []byte(`TinyGo`)) {
    66  		t.Fatalf("unable to find TinyGo in wasm_exec.js")
    67  	}
    68  
    69  }
    70  
    71  func goModTidy(dir string) {
    72  	cmd := exec.Command("go", "mod", "tidy")
    73  	cmd.Dir = dir
    74  	_, err := cmd.CombinedOutput()
    75  	if err != nil {
    76  		panic(err)
    77  	}
    78  }