wa-lang.org/wazero@v1.0.2/internal/integration_test/filecache/filecache_test.go (about)

     1  package filecache
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  	"testing"
    11  
    12  	"wa-lang.org/wazero/experimental"
    13  	"wa-lang.org/wazero/internal/engine/compiler"
    14  	"wa-lang.org/wazero/internal/integration_test/spectest"
    15  	v1 "wa-lang.org/wazero/internal/integration_test/spectest/v1"
    16  	"wa-lang.org/wazero/internal/platform"
    17  	"wa-lang.org/wazero/internal/testing/require"
    18  )
    19  
    20  func TestSpecTestCompilerCache(t *testing.T) {
    21  	if !platform.CompilerSupported() {
    22  		return
    23  	}
    24  
    25  	const cachePathKey = "FILE_CACHE_DIR"
    26  	cacheDir := os.Getenv(cachePathKey)
    27  	if len(cacheDir) == 0 {
    28  		// This case, this is the parent of the test.
    29  		cacheDir = t.TempDir()
    30  
    31  		// Before running test, no file should exist in the directory.
    32  		files, err := os.ReadDir(cacheDir)
    33  		require.NoError(t, err)
    34  		require.True(t, len(files) == 0)
    35  
    36  		// Get the executable path of this test.
    37  		testExecutable, err := os.Executable()
    38  		require.NoError(t, err)
    39  
    40  		// Execute this test multiple times with the env $cachePathKey=cacheDir, so that
    41  		// the subsequent execution of this test will enter the following "else" block.
    42  		var exp []string
    43  		buf := bytes.NewBuffer(nil)
    44  		for i := 0; i < 2; i++ {
    45  			cmd := exec.Command(testExecutable)
    46  			cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", cachePathKey, cacheDir))
    47  			cmd.Stdout = buf
    48  			cmd.Stderr = buf
    49  			err = cmd.Run()
    50  			require.NoError(t, err, buf.String())
    51  			exp = append(exp, "PASS\n")
    52  		}
    53  
    54  		// Ensures that the tests actually run 2 times.
    55  		require.Equal(t, strings.Join(exp, ""), buf.String())
    56  
    57  		// Check the number of cache files is greater than zero.
    58  		files, err = os.ReadDir(cacheDir)
    59  		require.NoError(t, err)
    60  		require.True(t, len(files) > 0)
    61  	} else {
    62  		// Run the spectest with the file cache.
    63  		ctx, err := experimental.WithCompilationCacheDirName(context.Background(), cacheDir)
    64  		require.NoError(t, err)
    65  		spectest.Run(t, v1.Testcases, ctx, compiler.NewEngine, v1.EnabledFeatures)
    66  	}
    67  }