src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/eval/vals/struct_map_test.go (about)

     1  package vals
     2  
     3  import (
     4  	"testing"
     5  
     6  	"src.elv.sh/pkg/persistent/hash"
     7  )
     8  
     9  type testStructMap struct {
    10  	Name  string
    11  	Score float64
    12  }
    13  
    14  func (testStructMap) IsStructMap() {}
    15  
    16  func (m testStructMap) ScorePlusTen() float64 { return m.Score + 10 }
    17  
    18  // Equivalent to testStructMap for Elvish.
    19  type testStructMap2 struct {
    20  	Name         string
    21  	Score        float64
    22  	ScorePlusTen float64
    23  }
    24  
    25  func (testStructMap2) IsStructMap() {}
    26  
    27  func TestStructMap(t *testing.T) {
    28  	TestValue(t, testStructMap{"ls", 1.0}).
    29  		Kind("map").
    30  		Bool(true).
    31  		Hash(
    32  			hash.DJB(Hash("name"), Hash("ls"))+
    33  				hash.DJB(Hash("score"), Hash(1.0))+
    34  				hash.DJB(Hash("score-plus-ten"), Hash(11.0))).
    35  		Repr(`[&name=ls &score=(num 1.0) &score-plus-ten=(num 11.0)]`).
    36  		Len(3).
    37  		Equal(
    38  			// Struct maps behave like maps, so they are equal to normal maps
    39  			// and other struct maps with the same entries.
    40  			MakeMap("name", "ls", "score", 1.0, "score-plus-ten", 11.0),
    41  			testStructMap{"ls", 1.0},
    42  			testStructMap2{"ls", 1.0, 11.0}).
    43  		NotEqual("a", MakeMap(), testStructMap{"ls", 2.0}, testStructMap{"l", 1.0}).
    44  		HasKey("name", "score", "score-plus-ten").
    45  		HasNoKey("bad", 1.0).
    46  		IndexError("bad", NoSuchKey("bad")).
    47  		IndexError(1.0, NoSuchKey(1.0)).
    48  		AllKeys("name", "score", "score-plus-ten").
    49  		Index("name", "ls").
    50  		Index("score", 1.0).
    51  		Index("score-plus-ten", 11.0)
    52  }
    53  
    54  type testPseudoMap struct{}
    55  
    56  func (testPseudoMap) Kind() string      { return "test-pseudo-map" }
    57  func (testPseudoMap) Fields() StructMap { return testStructMap{"pseudo", 100} }
    58  
    59  func TestPseudoMap(t *testing.T) {
    60  	TestValue(t, testPseudoMap{}).
    61  		Repr("[^test-pseudo-map &name=pseudo &score=(num 100.0) &score-plus-ten=(num 110.0)]").
    62  		HasKey("name", "score", "score-plus-ten").
    63  		NotEqual(
    64  			// Pseudo struct maps are nominally typed, so they are not equal to
    65  			// maps or struct maps with the same entries.
    66  			MakeMap("name", "", "score", 1.0, "score-plus-ten", 11.0),
    67  			testStructMap{"ls", 1.0},
    68  		).
    69  		HasNoKey("bad", 1.0).
    70  		IndexError("bad", NoSuchKey("bad")).
    71  		IndexError(1.0, NoSuchKey(1.0)).
    72  		AllKeys("name", "score", "score-plus-ten").
    73  		Index("name", "pseudo").
    74  		Index("score", 100.0).
    75  		Index("score-plus-ten", 110.0)
    76  }