render_test.go 1.9 KB

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