gorm_operator_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package integration_test
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. "github.com/qor5/admin/presets"
  7. "github.com/qor5/admin/presets/gorm2op"
  8. "github.com/qor5/web"
  9. "github.com/theplant/gofixtures"
  10. )
  11. type TestVariant struct {
  12. ProductCode string
  13. ColorCode string
  14. Name string
  15. }
  16. var emptyData = gofixtures.Data(gofixtures.Sql(``, []string{"test_variants"}))
  17. func (tv *TestVariant) PrimarySlug() string {
  18. return fmt.Sprintf("%s_%s", tv.ProductCode, tv.ColorCode)
  19. }
  20. func (tv *TestVariant) PrimaryColumnValuesBySlug(slug string) map[string]string {
  21. segs := strings.Split(slug, "_")
  22. if len(segs) != 2 {
  23. panic("wrong slug")
  24. }
  25. return map[string]string{
  26. "product_code": segs[0],
  27. "color_code": segs[1],
  28. }
  29. }
  30. func TestPrimarySlugger(t *testing.T) {
  31. db := ConnectDB()
  32. db.AutoMigrate(&TestVariant{})
  33. rawDB, _ := db.DB()
  34. emptyData.TruncatePut(rawDB)
  35. op := gorm2op.DataOperator(db)
  36. ctx := new(web.EventContext)
  37. err := op.Save(&TestVariant{ProductCode: "P01", ColorCode: "C01", Name: "Product 1"}, "", ctx)
  38. if err != nil {
  39. panic(err)
  40. }
  41. err = op.Save(&TestVariant{ProductCode: "P01", ColorCode: "C01", Name: "Product 2"}, "P01_C01", ctx)
  42. if err != nil {
  43. panic(err)
  44. }
  45. tv, err := op.Fetch(&TestVariant{}, "P01_C01", ctx)
  46. if err != nil {
  47. panic(err)
  48. }
  49. if tv.(*TestVariant).Name != "Product 2" {
  50. t.Error("didn't update product 2", tv)
  51. }
  52. err = op.Delete(&TestVariant{}, "P01_C01", ctx)
  53. if err != nil {
  54. panic(err)
  55. }
  56. tv, err = op.Fetch(&TestVariant{}, "P01_C01", ctx)
  57. if err != presets.ErrRecordNotFound {
  58. t.Error("didn't return not found after delete", tv, err)
  59. }
  60. }