|
| 1 | +package db |
| 2 | + |
| 3 | +import ( |
| 4 | + "reflect" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func TestTableForStruct(t *testing.T) { |
| 9 | + tests := []struct { |
| 10 | + name string |
| 11 | + t reflect.Type |
| 12 | + tagKey string |
| 13 | + wantTable string |
| 14 | + wantErr bool |
| 15 | + }{ |
| 16 | + { |
| 17 | + name: "OK", |
| 18 | + t: reflect.TypeFor[struct { |
| 19 | + Table `db:"table_name"` |
| 20 | + }](), |
| 21 | + tagKey: "db", |
| 22 | + wantTable: "table_name", |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "more struct fields", |
| 26 | + t: reflect.TypeFor[struct { |
| 27 | + ID int `db:"id"` |
| 28 | + Table `db:"table_name"` |
| 29 | + Value string `db:"value"` |
| 30 | + }](), |
| 31 | + tagKey: "db", |
| 32 | + wantTable: "table_name", |
| 33 | + }, |
| 34 | + // Error cases |
| 35 | + { |
| 36 | + name: "empty", |
| 37 | + t: reflect.TypeFor[struct{}](), |
| 38 | + tagKey: "db", |
| 39 | + wantErr: true, |
| 40 | + }, |
| 41 | + { |
| 42 | + name: "no tagKey", |
| 43 | + t: reflect.TypeFor[struct { |
| 44 | + Table |
| 45 | + }](), |
| 46 | + tagKey: "db", |
| 47 | + wantErr: true, |
| 48 | + }, |
| 49 | + { |
| 50 | + name: "wrong tagKey", |
| 51 | + t: reflect.TypeFor[struct { |
| 52 | + Table `json:"table_name"` |
| 53 | + }](), |
| 54 | + tagKey: "db", |
| 55 | + wantErr: true, |
| 56 | + }, |
| 57 | + { |
| 58 | + name: "named field", |
| 59 | + t: reflect.TypeFor[struct { |
| 60 | + Table Table `db:"table_name"` |
| 61 | + }](), |
| 62 | + tagKey: "db", |
| 63 | + wantErr: true, |
| 64 | + }, |
| 65 | + } |
| 66 | + for _, tt := range tests { |
| 67 | + t.Run(tt.name, func(t *testing.T) { |
| 68 | + gotTable, err := TableForStruct(tt.t, tt.tagKey) |
| 69 | + if (err != nil) != tt.wantErr { |
| 70 | + t.Errorf("TableForStruct(%s, %#v) error = %v, wantErr %v", tt.t, tt.tagKey, err, tt.wantErr) |
| 71 | + return |
| 72 | + } |
| 73 | + if gotTable != tt.wantTable { |
| 74 | + t.Errorf("TableForStruct(%s, %#v) = %v, want %v", tt.t, tt.tagKey, gotTable, tt.wantTable) |
| 75 | + } |
| 76 | + }) |
| 77 | + } |
| 78 | +} |
0 commit comments