You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.6 KiB

  1. package core
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestPaginationPage(t *testing.T) {
  8. cases := []struct {
  9. totalCount int
  10. perPage int
  11. page int
  12. newPage int
  13. expErr bool
  14. }{
  15. {0, 10, 1, 1, false},
  16. {0, 10, 0, 1, false},
  17. {0, 10, 1, 1, false},
  18. {0, 10, 2, 0, true},
  19. {5, 10, -1, 0, true},
  20. {5, 10, 0, 1, false},
  21. {5, 10, 1, 1, false},
  22. {5, 10, 2, 0, true},
  23. {5, 10, 2, 0, true},
  24. {5, 5, 1, 1, false},
  25. {5, 5, 2, 0, true},
  26. {5, 5, 3, 0, true},
  27. {5, 3, 2, 2, false},
  28. {5, 3, 3, 0, true},
  29. {5, 2, 2, 2, false},
  30. {5, 2, 3, 3, false},
  31. {5, 2, 4, 0, true},
  32. }
  33. for _, c := range cases {
  34. p, err := validatePage(&c.page, c.perPage, c.totalCount)
  35. if c.expErr {
  36. assert.Error(t, err)
  37. continue
  38. }
  39. assert.Equal(t, c.newPage, p, fmt.Sprintf("%v", c))
  40. }
  41. // nil case
  42. p, err := validatePage(nil, 1, 1)
  43. if assert.NoError(t, err) {
  44. assert.Equal(t, 1, p)
  45. }
  46. }
  47. func TestPaginationPerPage(t *testing.T) {
  48. cases := []struct {
  49. perPage int
  50. newPerPage int
  51. }{
  52. {0, defaultPerPage},
  53. {1, 1},
  54. {2, 2},
  55. {defaultPerPage, defaultPerPage},
  56. {maxPerPage - 1, maxPerPage - 1},
  57. {maxPerPage, maxPerPage},
  58. {maxPerPage + 1, maxPerPage},
  59. }
  60. env := &Environment{}
  61. for _, c := range cases {
  62. p := env.validatePerPage(&c.perPage)
  63. assert.Equal(t, c.newPerPage, p, fmt.Sprintf("%v", c))
  64. }
  65. // nil case
  66. p := env.validatePerPage(nil)
  67. assert.Equal(t, defaultPerPage, p)
  68. // test in unsafe mode
  69. env.Config.Unsafe = true
  70. perPage := 1000
  71. p = env.validatePerPage(&perPage)
  72. assert.Equal(t, perPage, p)
  73. env.Config.Unsafe = false
  74. }