github.com/mailru/activerecord@v1.12.2/internal/pkg/parser/index_b_test.go (about) 1 package parser_test 2 3 import ( 4 "go/ast" 5 "testing" 6 7 "github.com/mailru/activerecord/internal/pkg/ds" 8 "github.com/mailru/activerecord/internal/pkg/parser" 9 "gotest.tools/assert" 10 "gotest.tools/assert/cmp" 11 ) 12 13 func TestParseIndexPart(t *testing.T) { 14 type args struct { 15 dst *ds.RecordPackage 16 fields []*ast.Field 17 } 18 19 wantRp := ds.NewRecordPackage() 20 wantRp.Fields = []ds.FieldDeclaration{ 21 {Name: "Field1", Format: "int"}, 22 {Name: "Field2", Format: "int"}, 23 } 24 wantRp.FieldsMap = map[string]int{"Field1": 0, "Field2": 1} 25 wantRp.Indexes = []ds.IndexDeclaration{ 26 { 27 Name: "Field1Field2", 28 Num: 0, 29 Selector: "SelectByField1Field2", 30 Fields: []int{0, 1}, 31 FieldsMap: map[string]ds.IndexField{ 32 "Field1": {IndField: 0, Order: 0}, 33 "Field2": {IndField: 1, Order: 0}, 34 }, 35 Unique: true, 36 }, 37 { 38 Name: "Field1Part", 39 Num: 0, 40 Selector: "SelectByField1", 41 Fields: []int{0}, 42 FieldsMap: map[string]ds.IndexField{ 43 "Field1": {IndField: 0, Order: 0}, 44 }, 45 Partial: true, 46 }, 47 } 48 wantRp.IndexMap = map[string]int{"Field1Field2": 0, "Field1Part": 1} 49 wantRp.SelectorMap = map[string]int{"SelectByField1": 1, "SelectByField1Field2": 0} 50 51 rp := ds.NewRecordPackage() 52 53 err := rp.AddField(ds.FieldDeclaration{ 54 Name: "Field1", 55 Format: "int", 56 PrimaryKey: false, 57 }) 58 if err != nil { 59 t.Errorf("can't prepare test data: %s", err) 60 return 61 } 62 63 err = rp.AddField(ds.FieldDeclaration{ 64 Name: "Field2", 65 Format: "int", 66 PrimaryKey: false, 67 }) 68 if err != nil { 69 t.Errorf("can't prepare test data: %s", err) 70 return 71 } 72 73 err = rp.AddIndex(ds.IndexDeclaration{ 74 Name: "Field1Field2", 75 Num: 0, 76 Selector: "SelectByField1Field2", 77 Fields: []int{0, 1}, 78 FieldsMap: map[string]ds.IndexField{"Field1": {IndField: 0, Order: ds.IndexOrderAsc}, "Field2": {IndField: 1, Order: ds.IndexOrderAsc}}, 79 Primary: false, 80 Unique: true, 81 Type: "", 82 }) 83 if err != nil { 84 t.Errorf("can't prepare test data: %s", err) 85 return 86 } 87 88 tests := []struct { 89 name string 90 args args 91 wantErr bool 92 want *ds.RecordPackage 93 }{ 94 { 95 name: "simple index part", 96 args: args{ 97 dst: rp, 98 fields: []*ast.Field{ 99 { 100 Names: []*ast.Ident{{Name: "Field1Part"}}, 101 Type: &ast.Ident{Name: "bool"}, 102 Tag: &ast.BasicLit{Value: "`" + `ar:"index:Field1Field2;fieldnum:1;selector:SelectByField1"` + "`"}, 103 }, 104 }, 105 }, 106 wantErr: false, 107 want: wantRp, 108 }, 109 } 110 for _, tt := range tests { 111 t.Run(tt.name, func(t *testing.T) { 112 if err := parser.ParseIndexPart(tt.args.dst, tt.args.fields); (err != nil) != tt.wantErr { 113 t.Errorf("ParseIndexPart() error = %v, wantErr %v", err, tt.wantErr) 114 return 115 } 116 117 assert.Check(t, cmp.DeepEqual(tt.want, tt.args.dst), "Invalid response, test `%s`", tt.name) 118 }) 119 } 120 }