package nstore import ( "errors" "slices" "testing" "time" ) type testperson struct { Name string Age int height int Weight float64 } type testPerson struct { Name string Age int height int Friends []testPerson FavoriteColor string } type testCarType struct { CreatedAt time.Time Name string Make string Model string } type testBook struct { Name string Year int Authors []string } func exampleTestPerson() testPerson { return testPerson{ Name: "Nathan", Age: 39, height: 72, Friends: []testPerson{ {Name: "Sam", Age: 33, height: 70, FavoriteColor: "red"}, }, FavoriteColor: "blue", } } func TestStructTypeTableName(t *testing.T) { errUnexpectedTableName := errors.New("unexpected table name") tableNameMap := map[string]any{ "testperson": &testperson{}, "test_person": &testPerson{}, "test_car_type": testCarType{}, "test_book": testBook{}, } for expectedTableName, structValue := range tableNameMap { rType, err := reflectStructType(structValue) if err != nil { t.Fatal(err) } if structTypeTableName(rType) != expectedTableName { t.Error(errUnexpectedTableName) } } } func TestFieldTypeToDatabaseType(t *testing.T) { errUnexpectedFieldType := errors.New("unexpected field type") fieldTypeMap := map[any][]string{ testperson{}: {"TEXT", "INTEGER", "INTEGER", "REAL"}, &testPerson{}: {"TEXT", "INTEGER", "INTEGER", "", "TEXT"}, testCarType{}: {"TIMESTAMP", "TEXT", "TEXT", "TEXT"}, } for structValue, expectedTypes := range fieldTypeMap { rType, err := reflectStructType(structValue) if err != nil { t.Fatal(err) } for i, rField := range slices.Collect(rType.Fields()) { if fieldTypeToDatabaseType(rField.Type) != expectedTypes[i] { t.Error(errUnexpectedFieldType) } } } } func TestStructTypeToColumnNames(t *testing.T) { errUnexpectedColumns := errors.New("unexpected columns") colNameMap := map[any][]string{ testperson{}: {"name", "age", "weight"}, &testPerson{}: {"name", "age", "favorite_color"}, testCarType{}: {"created_at", "name", "make", "model"}, } for structValue, expectedColumns := range colNameMap { rType, err := reflectStructType(structValue) if err != nil { t.Fatal(err) } columnNames, err := structTypeToColumnNames(rType) if err != nil { t.Fatal(err) } if !slices.Equal(columnNames, expectedColumns) { t.Error(errUnexpectedColumns) } } }