github.com/elves/elvish@v0.15.0/pkg/eval/vals/struct_map_test.go (about) 1 package vals 2 3 import ( 4 "testing" 5 6 "github.com/xiaq/persistent/hash" 7 ) 8 9 type testStructMap struct { 10 Name string 11 ScoreNumber float64 12 } 13 14 func (testStructMap) IsStructMap() {} 15 16 // Structurally identical to testStructMap. 17 type testStructMap2 struct { 18 Name string 19 ScoreNumber float64 20 } 21 22 func (testStructMap2) IsStructMap() {} 23 24 type testStructMap3 struct { 25 Name string 26 score float64 27 } 28 29 func (testStructMap3) IsStructMap() {} 30 31 func (m testStructMap3) Score() float64 { 32 return m.score + 10 33 } 34 35 func TestStructMap(t *testing.T) { 36 TestValue(t, testStructMap{}). 37 Kind("structmap"). 38 Bool(true). 39 Hash(hash.DJB(Hash(""), Hash(0.0))). 40 Repr(`[&name='' &score-number=(float64 0)]`). 41 Len(2). 42 Equal(testStructMap{}). 43 NotEqual("a", MakeMap(), testStructMap{"a", 1.0}). 44 // StructMap's are nominally typed. This may change in future. 45 NotEqual(testStructMap2{}). 46 HasKey("name", "score-number"). 47 HasNoKey("bad", 1.0). 48 IndexError("bad", NoSuchKey("bad")). 49 IndexError(1.0, NoSuchKey(1.0)). 50 AllKeys("name", "score-number"). 51 Index("name", ""). 52 Index("score-number", 0.0) 53 54 TestValue(t, testStructMap{"a", 1.0}). 55 Kind("structmap"). 56 Bool(true). 57 Hash(hash.DJB(Hash("a"), Hash(1.0))). 58 Repr(`[&name=a &score-number=(float64 1)]`). 59 Len(2). 60 Equal(testStructMap{"a", 1.0}). 61 NotEqual( 62 "a", MakeMap("name", "", "score-number", 1.0), 63 testStructMap{}, testStructMap{"a", 2.0}, testStructMap{"b", 1.0}). 64 // Keys are tested above, thus omitted here. 65 Index("name", "a"). 66 Index("score-number", 1.0) 67 68 TestValue(t, testStructMap3{"a", 1.0}). 69 Kind("structmap"). 70 Bool(true). 71 Hash(hash.DJB(Hash("a"), Hash(11.0))). 72 Repr(`[&name=a &score=(float64 11)]`). 73 Len(2). 74 Equal(testStructMap3{"a", 1.0}). 75 NotEqual( 76 "a", MakeMap("name", "", "score-number", 1.0), 77 testStructMap{}, testStructMap{"a", 11.0}). 78 // Keys are tested above, thus omitted here. 79 Index("name", "a"). 80 Index("score", 11.0) 81 } 82 83 type pseudoStructMap struct{} 84 85 func (pseudoStructMap) Fields() StructMap { 86 return testStructMap{"pseudo", 100} 87 } 88 89 func TestPseudoStructMap(t *testing.T) { 90 TestValue(t, pseudoStructMap{}). 91 Repr("[&name=pseudo &score-number=(float64 100)]"). 92 HasKey("name", "score-number"). 93 HasNoKey("bad", 1.0). 94 IndexError("bad", NoSuchKey("bad")). 95 IndexError(1.0, NoSuchKey(1.0)). 96 AllKeys("name", "score-number"). 97 Index("name", "pseudo"). 98 Index("score-number", 100.0) 99 }