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.

273 lines
5.2 KiB

  1. package Api
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "mime/multipart"
  11. "net/http"
  12. "net/http/httptest"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strconv"
  18. "testing"
  19. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
  20. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  21. "github.com/gorilla/mux"
  22. "gorm.io/gorm"
  23. )
  24. func init() {
  25. // Fix working directory for tests
  26. _, filename, _, _ := runtime.Caller(0)
  27. dir := path.Join(path.Dir(filename), "..")
  28. err := os.Chdir(dir)
  29. if err != nil {
  30. panic(err)
  31. }
  32. log.SetOutput(ioutil.Discard)
  33. Database.Init()
  34. r = mux.NewRouter()
  35. }
  36. func get(url string) (resp *http.Response, err error) {
  37. for i := 0; i < 5; i++ {
  38. resp, err = http.Get(url)
  39. if err == nil {
  40. return resp, err
  41. }
  42. }
  43. return resp, err
  44. }
  45. // Image generates a *os.File with a random image using the loremflickr.com service
  46. func fakeImage(width, height int, categories []string, prefix string, categoriesStrict bool) *os.File {
  47. url := "https://loremflickr.com"
  48. switch prefix {
  49. case "g":
  50. url += "/g"
  51. case "p":
  52. url += "/p"
  53. case "red":
  54. url += "/red"
  55. case "green":
  56. url += "/green"
  57. case "blue":
  58. url += "/blue"
  59. }
  60. url += string('/') + strconv.Itoa(width) + string('/') + strconv.Itoa(height)
  61. if len(categories) > 0 {
  62. url += string('/')
  63. for _, category := range categories {
  64. url += category + string(',')
  65. }
  66. if categoriesStrict {
  67. url += "/all"
  68. }
  69. }
  70. resp, err := get(url)
  71. defer resp.Body.Close()
  72. if err != nil {
  73. panic(err)
  74. }
  75. f, err := ioutil.TempFile(os.TempDir(), "loremflickr-img-*.jpg")
  76. if err != nil {
  77. panic(err)
  78. }
  79. io.Copy(f, resp.Body)
  80. err = f.Close()
  81. if err != nil {
  82. panic(err)
  83. }
  84. return f
  85. }
  86. func Test_createPostImages(t *testing.T) {
  87. t.Log("Testing createPostImages...")
  88. r.HandleFunc("/post/{postID}/image", createPostImage).Methods("POST")
  89. ts := httptest.NewServer(r)
  90. defer ts.Close()
  91. postData := Models.Post{
  92. Title: "Test post",
  93. Content: "Test content",
  94. FrontPage: true,
  95. Order: 1,
  96. PostLinks: []Models.PostLink{
  97. {
  98. Type: "Facebook",
  99. Link: "http://facebook.com/",
  100. },
  101. },
  102. }
  103. err := Database.CreatePost(&postData)
  104. if err != nil {
  105. t.Errorf("Expected nil, recieved %s", err.Error())
  106. }
  107. image := fakeImage(100, 100, []string{}, "", false)
  108. image, err = os.Open(image.Name())
  109. if err != nil {
  110. t.Errorf("Expected nil, recieved %s", err.Error())
  111. }
  112. body := &bytes.Buffer{}
  113. writer := multipart.NewWriter(body)
  114. part, err := writer.CreateFormFile("files", filepath.Base(image.Name()))
  115. if err != nil {
  116. t.Errorf("Expected nil, recieved %s", err.Error())
  117. }
  118. io.Copy(part, image)
  119. writer.Close()
  120. request, err := http.NewRequest(
  121. "POST",
  122. fmt.Sprintf(
  123. "%s/post/%s/image",
  124. ts.URL,
  125. postData.ID,
  126. ),
  127. body,
  128. )
  129. if err != nil {
  130. t.Errorf("Expected nil, recieved %s", err.Error())
  131. }
  132. request.Header.Add("Content-Type", writer.FormDataContentType())
  133. client := &http.Client{}
  134. res, err := client.Do(request)
  135. if err != nil {
  136. t.Errorf("Expected nil, recieved %s", err.Error())
  137. }
  138. if res.StatusCode != http.StatusOK {
  139. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  140. }
  141. defer res.Body.Close()
  142. updatePostData := new(Models.Post)
  143. err = json.NewDecoder(res.Body).Decode(updatePostData)
  144. if err != nil {
  145. t.Errorf("Expected nil, recieved %s", err.Error())
  146. }
  147. defer Database.DB.
  148. Session(&gorm.Session{FullSaveAssociations: true}).
  149. Unscoped().
  150. Select("PostLinks", "PostImages").
  151. Delete(&postData)
  152. if len(updatePostData.PostImages) != 1 {
  153. t.Errorf("Expected len(updatePostData.PostImages) == 1, recieved %d", len(updatePostData.PostImages))
  154. }
  155. for _, f := range updatePostData.PostImages {
  156. if _, err := os.Stat("./" + f.Filepath); errors.Is(err, os.ErrNotExist) {
  157. t.Errorf(
  158. "File ./%s does not exist",
  159. f.Filepath,
  160. )
  161. } else {
  162. os.Remove("./" + f.Filepath)
  163. }
  164. }
  165. }
  166. func Test_deletePostImages(t *testing.T) {
  167. t.Log("Testing createPostImages...")
  168. r.HandleFunc("/post/{postID}/image/{imageID}", deletePostImage).Methods("DELETE")
  169. ts := httptest.NewServer(r)
  170. defer ts.Close()
  171. image := fakeImage(100, 100, []string{}, "", false)
  172. image, err := os.Open(image.Name())
  173. if err != nil {
  174. t.Errorf("Expected nil, recieved %s", err.Error())
  175. }
  176. defer image.Close()
  177. postData := Models.Post{
  178. Title: "Test post",
  179. Content: "Test content",
  180. FrontPage: true,
  181. Order: 1,
  182. PostLinks: []Models.PostLink{
  183. {
  184. Type: "Facebook",
  185. Link: "http://facebook.com/",
  186. },
  187. },
  188. PostImages: []Models.PostImage{
  189. {
  190. Filepath: image.Name(),
  191. },
  192. },
  193. }
  194. err = Database.CreatePost(&postData)
  195. if err != nil {
  196. t.Errorf("Expected nil, recieved %s", err.Error())
  197. }
  198. defer Database.DB.
  199. Session(&gorm.Session{FullSaveAssociations: true}).
  200. Unscoped().
  201. Select("PostLinks", "PostImages").
  202. Delete(&postData)
  203. req, err := http.NewRequest("DELETE", fmt.Sprintf(
  204. "%s/post/%s/image/%s",
  205. ts.URL,
  206. postData.ID,
  207. postData.PostImages[0].ID,
  208. ), nil)
  209. if err != nil {
  210. t.Errorf("Expected nil, recieved %s", err.Error())
  211. }
  212. res, err := http.DefaultClient.Do(req)
  213. if err != nil {
  214. t.Errorf("Expected nil, recieved %s", err.Error())
  215. return
  216. }
  217. defer res.Body.Close()
  218. if res.StatusCode != http.StatusOK {
  219. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  220. }
  221. }