github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/eval/vals/iterate_keys_test.go (about)

     1  package vals
     2  
     3  import (
     4  	"testing"
     5  
     6  	. "github.com/markusbkk/elvish/pkg/tt"
     7  )
     8  
     9  func vs(xs ...interface{}) []interface{} { return xs }
    10  
    11  type keysIterator struct{ keys []interface{} }
    12  
    13  func (k keysIterator) IterateKeys(f func(interface{}) bool) {
    14  	Feed(f, k.keys...)
    15  }
    16  
    17  type nonKeysIterator struct{}
    18  
    19  func TestIterateKeys(t *testing.T) {
    20  	Test(t, Fn("collectKeys", collectKeys), Table{
    21  		Args(MakeMap("k1", "v1", "k2", "v2")).Rets(vs("k1", "k2"), nil),
    22  		Args(keysIterator{vs("lorem", "ipsum")}).Rets(vs("lorem", "ipsum")),
    23  		Args(nonKeysIterator{}).Rets(
    24  			Any, cannotIterateKeysOf{"!!vals.nonKeysIterator"}),
    25  	})
    26  }
    27  
    28  func TestIterateKeys_Map_Break(t *testing.T) {
    29  	var gotKey interface{}
    30  	IterateKeys(MakeMap("k", "v", "k2", "v2"), func(k interface{}) bool {
    31  		if gotKey != nil {
    32  			t.Errorf("callback called again after returning false")
    33  		}
    34  		gotKey = k
    35  		return false
    36  	})
    37  	if gotKey != "k" && gotKey != "k2" {
    38  		t.Errorf("got key %v, want k or k2", gotKey)
    39  	}
    40  }
    41  
    42  func TestIterateKeys_StructMap_Break(t *testing.T) {
    43  	var gotKey interface{}
    44  	IterateKeys(testStructMap{}, func(k interface{}) bool {
    45  		if gotKey != nil {
    46  			t.Errorf("callback called again after returning false")
    47  		}
    48  		gotKey = k
    49  		return false
    50  	})
    51  	if gotKey != "name" {
    52  		t.Errorf("got key %v, want name", gotKey)
    53  	}
    54  }
    55  
    56  func TestIterateKeys_Unsupported(t *testing.T) {
    57  	err := IterateKeys(1, func(interface{}) bool { return true })
    58  	wantErr := cannotIterateKeysOf{"number"}
    59  	if err != wantErr {
    60  		t.Errorf("got error %v, want %v", err, wantErr)
    61  	}
    62  }