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.

258 lines
4.9 KiB

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