render_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package routes
  2. import (
  3. "io"
  4. "log"
  5. "os"
  6. "reflect"
  7. "strings"
  8. "testing"
  9. "github.com/CloudyKit/jet/v6"
  10. "github.com/go-faker/faker/v4"
  11. )
  12. func TestTemplates(t *testing.T) {
  13. {
  14. data := fakeData[Data_error]()
  15. data.Error = io.EOF
  16. manualTest(t, data)
  17. }
  18. autoTest[Data_about](t)
  19. autoTest[Data_artwork](t)
  20. autoTest[Data_artworkMulti](t)
  21. autoTest[Data_discovery](t)
  22. autoTest[Data_following](t)
  23. autoTest[Data_index](t)
  24. autoTest[Data_newest](t)
  25. autoTest[Data_novel](t)
  26. autoTest[Data_novelDiscovery](t)
  27. autoTest[Data_pixivision_article](t)
  28. autoTest[Data_pixivision_index](t)
  29. autoTest[Data_rank](t)
  30. autoTest[Data_rankingCalendar](t)
  31. autoTest[Data_settings](t)
  32. autoTest[Data_tag](t)
  33. autoTest[Data_unauthorized](t)
  34. autoTest[Data_user](t)
  35. autoTest[Data_userAtom](t)
  36. }
  37. func TestMain(m *testing.M) {
  38. err := os.Chdir("..")
  39. if err != nil {
  40. panic(err)
  41. }
  42. InitTemplatingEngine(false)
  43. m.Run()
  44. }
  45. func fakeData[T any]() T {
  46. var data T
  47. faker.FakeData(&data)
  48. return data
  49. }
  50. // autoTest template with fake data
  51. func autoTest[T any](t *testing.T) {
  52. manualTest(t, fakeData[T]())
  53. }
  54. func manualTest[T any](t *testing.T, data T) {
  55. route_name, found := strings.CutPrefix(reflect.TypeFor[T]().Name(), "Data_")
  56. if !found {
  57. log.Panicf("struct name does not start with 'Data_': %s", route_name)
  58. }
  59. // log.Println("Testing " + route_name)
  60. variables := jet.VarMap{}
  61. for k, v := range map[string]any{
  62. "BaseURL": fakeData[string](),
  63. "OriginalURL": fakeData[string](),
  64. "PageURL": fakeData[string](),
  65. "LoggedIn": fakeData[bool](),
  66. "Queries": fakeData[map[string]string](),
  67. "CookieList": fakeData[map[string]string](),
  68. } {
  69. variables.Set(k, v)
  70. }
  71. err := RenderInner(io.Discard, variables, data)
  72. if err != nil {
  73. template_name, _ := strings.CutPrefix(reflect.TypeFor[T]().Name(), "Data_")
  74. t.Errorf("while rendering template %s: %v", template_name, err)
  75. }
  76. }