github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/vars/vars_test.go (about)

     1  package vars
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  )
     7  
     8  func TestAnyVariable(t *testing.T) {
     9  	v := NewAnyWithInit(true)
    10  	if v.Get() != true {
    11  		t.Errorf("PtrVariable.Get doesn't return initial value")
    12  	}
    13  	if v.Set("233") != nil {
    14  		t.Errorf("PtrVariable.Set errors")
    15  	}
    16  	if v.Get() != "233" {
    17  		t.Errorf("PtrVariable.Get doesn't return altered value")
    18  	}
    19  }
    20  
    21  func TestRoVariable(t *testing.T) {
    22  	v := NewRo("haha")
    23  	if v.Get() != "haha" {
    24  		t.Errorf("RoVariable.Get doesn't return initial value")
    25  	}
    26  	if v.Set("lala") == nil {
    27  		t.Errorf("RoVariable.Set doesn't error")
    28  	}
    29  }
    30  
    31  func TestCbVariable(t *testing.T) {
    32  	getCalled := false
    33  	get := func() interface{} {
    34  		getCalled = true
    35  		return "cb"
    36  	}
    37  	var setCalledWith interface{}
    38  	set := func(v interface{}) error {
    39  		setCalledWith = v
    40  		return nil
    41  	}
    42  
    43  	v := FromSetGet(set, get)
    44  	if v.Get() != "cb" {
    45  		t.Errorf("cbVariable doesn't return value from callback")
    46  	}
    47  	if !getCalled {
    48  		t.Errorf("cbVariable doesn't call callback")
    49  	}
    50  	v.Set("setting")
    51  	if setCalledWith != "setting" {
    52  		t.Errorf("cbVariable.Set doesn't call setter with value")
    53  	}
    54  }
    55  
    56  func TestRoCbVariable(t *testing.T) {
    57  	getCalled := false
    58  	get := func() interface{} {
    59  		getCalled = true
    60  		return "cb"
    61  	}
    62  	v := FromGet(get)
    63  	if v.Get() != "cb" {
    64  		t.Errorf("roCbVariable doesn't return value from callback")
    65  	}
    66  	if !getCalled {
    67  		t.Errorf("roCbVariable doesn't call callback")
    68  	}
    69  	if v.Set("lala") == nil {
    70  		t.Errorf("roCbVariable.Set doesn't error")
    71  	}
    72  }
    73  
    74  func TestEnvVariable(t *testing.T) {
    75  	name := "elvish_test"
    76  	v := envVariable{name}
    77  	os.Setenv(name, "foo")
    78  	if v.Get() != "foo" {
    79  		t.Errorf("envVariable.Get doesn't return env value")
    80  	}
    81  	v.Set("bar")
    82  	if os.Getenv(name) != "bar" {
    83  		t.Errorf("envVariable.Set doesn't alter env value")
    84  	}
    85  }