github.com/dop251/goja_nodejs@v0.0.0-20240418154818-2aae10d4cbcf/process/module_test.go (about)

     1  package process
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/dop251/goja"
    10  	"github.com/dop251/goja_nodejs/require"
    11  )
    12  
    13  func TestProcessEnvStructure(t *testing.T) {
    14  	vm := goja.New()
    15  
    16  	new(require.Registry).Enable(vm)
    17  	Enable(vm)
    18  
    19  	if c := vm.Get("process"); c == nil {
    20  		t.Fatal("process not found")
    21  	}
    22  
    23  	if c, err := vm.RunString("process.env"); c == nil || err != nil {
    24  		t.Fatal("error accessing process.env")
    25  	}
    26  }
    27  
    28  func TestProcessEnvValuesArtificial(t *testing.T) {
    29  	os.Setenv("GOJA_IS_AWESOME", "true")
    30  	defer os.Unsetenv("GOJA_IS_AWESOME")
    31  
    32  	vm := goja.New()
    33  
    34  	new(require.Registry).Enable(vm)
    35  	Enable(vm)
    36  
    37  	jsRes, err := vm.RunString("process.env['GOJA_IS_AWESOME']")
    38  
    39  	if err != nil {
    40  		t.Fatalf("Error executing: %s", err)
    41  	}
    42  
    43  	if jsRes.String() != "true" {
    44  		t.Fatalf("Error executing: got %s but expected %s", jsRes, "true")
    45  	}
    46  }
    47  
    48  func TestProcessEnvValuesBrackets(t *testing.T) {
    49  	vm := goja.New()
    50  
    51  	new(require.Registry).Enable(vm)
    52  	Enable(vm)
    53  
    54  	for _, e := range os.Environ() {
    55  		envKeyValue := strings.SplitN(e, "=", 2)
    56  		jsExpr := fmt.Sprintf("process.env['%s']", envKeyValue[0])
    57  
    58  		jsRes, err := vm.RunString(jsExpr)
    59  
    60  		if err != nil {
    61  			t.Fatalf("Error executing %s: %s", jsExpr, err)
    62  		}
    63  
    64  		if jsRes.String() != envKeyValue[1] {
    65  			t.Fatalf("Error executing %s: got %s but expected %s", jsExpr, jsRes, envKeyValue[1])
    66  		}
    67  	}
    68  }