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.

88 lines
1.5 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. for _, c := range cases {
  61. p := validatePerPage(&c.perPage)
  62. assert.Equal(t, c.newPerPage, p, fmt.Sprintf("%v", c))
  63. }
  64. // nil case
  65. p := validatePerPage(nil)
  66. assert.Equal(t, defaultPerPage, p)
  67. // test in unsafe mode
  68. env.Config.Unsafe = true
  69. perPage := 1000
  70. p = validatePerPage(&perPage)
  71. assert.Equal(t, perPage, p)
  72. env.Config.Unsafe = false
  73. }