exporter_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package exchange_test
  2. import (
  3. "bytes"
  4. "testing"
  5. "time"
  6. "github.com/qor5/x/exchange"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. func TestExport(t *testing.T) {
  10. initTables()
  11. records := []*TestExchangeModel{
  12. {
  13. ID: 1,
  14. Name: "Tom",
  15. Age: ptrInt(6),
  16. Birth: ptrTime(time.Date(1939, 1, 1, 0, 0, 0, 0, time.UTC)),
  17. },
  18. {
  19. ID: 2,
  20. Name: "Jerry",
  21. Age: ptrInt(5),
  22. Birth: ptrTime(time.Date(1940, 2, 10, 0, 0, 0, 0, time.UTC)),
  23. },
  24. }
  25. err := db.Create(&records).Error
  26. if err != nil {
  27. panic(err)
  28. }
  29. for _, c := range []struct {
  30. name string
  31. metas []*exchange.Meta
  32. whereCondition string
  33. expectCSVContent string
  34. expectError error
  35. }{
  36. {
  37. name: "normal",
  38. metas: []*exchange.Meta{
  39. exchange.NewMeta("ID").PrimaryKey(true),
  40. exchange.NewMeta("Name").Header("Nameeee"),
  41. exchange.NewMeta("Age"),
  42. exchange.NewMeta("Birth"),
  43. },
  44. expectCSVContent: `ID,Nameeee,Age,Birth
  45. 1,Tom,6,1939-01-01 00:00:00 +0000 UTC
  46. 2,Jerry,5,1940-02-10 00:00:00 +0000 UTC
  47. `,
  48. expectError: nil,
  49. },
  50. {
  51. name: "valuer",
  52. metas: []*exchange.Meta{
  53. exchange.NewMeta("ID").PrimaryKey(true),
  54. exchange.NewMeta("Name").Header("Nameeee"),
  55. exchange.NewMeta("Age"),
  56. exchange.NewMeta("Birth").Valuer(func(record interface{}) (string, error) {
  57. m := record.(*TestExchangeModel)
  58. b := m.Birth.Format("2006-01-02")
  59. return b, nil
  60. }),
  61. },
  62. expectCSVContent: `ID,Nameeee,Age,Birth
  63. 1,Tom,6,1939-01-01
  64. 2,Jerry,5,1940-02-10
  65. `,
  66. expectError: nil,
  67. },
  68. } {
  69. exporter := exchange.NewExporter(&TestExchangeModel{}).
  70. Metas(c.metas...)
  71. buf := bytes.Buffer{}
  72. w, err := exchange.NewCSVWriter(&buf)
  73. assert.NoError(t, err, c.name)
  74. err = exporter.Exec(db, w)
  75. if err != nil {
  76. assert.Equal(t, c.expectError, err, c.name)
  77. continue
  78. }
  79. assert.Equal(t, c.expectCSVContent, buf.String(), c.name)
  80. }
  81. }