z_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package rest
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "mime/multipart"
  9. "net/http"
  10. "net/textproto"
  11. "testing"
  12. "time"
  13. "git.ali33.ru/fcg-xvii/go-tools/json"
  14. )
  15. var (
  16. AddrCorrect = "localhost:7000"
  17. AddrIncorrect = "1.1.1.1:7000"
  18. Secret = []byte("itsMyWay")
  19. )
  20. func URL(path string) string {
  21. return fmt.Sprintf("http://%s%s", AddrCorrect, path)
  22. }
  23. func sendRequest(uri string, data json.Map, files map[string]io.ReadCloser, auth string) ([]byte, error) {
  24. log.Println(uri)
  25. body := &bytes.Buffer{}
  26. var contentType string
  27. if len(files) == 0 {
  28. // Если файлов нет, используем application/json
  29. contentType = "application/json"
  30. jsonData, err := json.Marshal(data)
  31. if err != nil {
  32. return nil, err
  33. }
  34. body.Write(jsonData)
  35. } else {
  36. // Если есть файлы, используем multipart/form-data
  37. writer := multipart.NewWriter(body)
  38. // Прикрепление файлов
  39. for fieldName, file := range files {
  40. part, err := writer.CreateFormFile(fieldName, fieldName)
  41. if err != nil {
  42. return nil, err
  43. }
  44. _, err = io.Copy(part, file)
  45. if err != nil {
  46. return nil, err
  47. }
  48. file.Close()
  49. }
  50. // Прикрепление JSON как части с Content-Type application/json
  51. jsonHeader := make(textproto.MIMEHeader)
  52. jsonHeader.Set("Content-Disposition", `form-data; name="data"`)
  53. jsonHeader.Set("Content-Type", "application/json")
  54. jsonPart, err := writer.CreatePart(jsonHeader)
  55. if err != nil {
  56. return nil, err
  57. }
  58. jsonPart.Write(data.JSON())
  59. err = writer.Close()
  60. if err != nil {
  61. return nil, err
  62. }
  63. contentType = writer.FormDataContentType()
  64. }
  65. req, err := http.NewRequest("POST", uri, body)
  66. if err != nil {
  67. return nil, err
  68. }
  69. if len(auth) > 0 {
  70. req.Header.Add("Authorization", "Bearer "+auth)
  71. }
  72. req.Header.Add("Content-Type", contentType)
  73. client := &http.Client{}
  74. resp, err := client.Do(req)
  75. if err != nil {
  76. return nil, err
  77. }
  78. defer resp.Body.Close()
  79. rBody, _ := ioutil.ReadAll(resp.Body)
  80. if resp.StatusCode != http.StatusOK {
  81. err = fmt.Errorf("failed sending request: %s", resp.Status)
  82. }
  83. return rBody, err
  84. }
  85. func initFile(data []byte) io.ReadCloser {
  86. buf := bytes.NewBuffer(data)
  87. return io.NopCloser(buf)
  88. }
  89. func TestListen(t *testing.T) {
  90. commands := NewCommandStore()
  91. rest := NewRest(AddrCorrect, Secret, commands)
  92. err := rest.Listen(time.Second)
  93. if err != nil {
  94. t.Log("open", err, rest.opened.Load())
  95. return
  96. }
  97. t.Log("close", rest.Close(), rest.opened.Load())
  98. }
  99. func TestRequest(t *testing.T) {
  100. command := new(ObjectDemo)
  101. commands := NewCommandStore()
  102. commands.AddCommand("/demo", command)
  103. commands.AddCommand("/json-debug", &JSONDebug{})
  104. rest := NewRest(AddrCorrect, Secret, commands)
  105. err := rest.Listen(time.Second)
  106. if err != nil {
  107. t.Log("open", err, rest.opened.Load())
  108. return
  109. }
  110. defer rest.Close()
  111. body, err := sendRequest(
  112. URL("/demo"),
  113. json.Map{
  114. "get-one": true,
  115. "get-two": false,
  116. },
  117. map[string]io.ReadCloser{
  118. "test-file.txt": initFile([]byte("test file contents...")),
  119. },
  120. "",
  121. )
  122. t.Log(string(body), err)
  123. }
  124. func TestToken(t *testing.T) {
  125. commands := NewCommandStore()
  126. auth := &AuthDebug{}
  127. commands.AddCommand("/register", auth)
  128. commands.AddCommand("/login", auth)
  129. rest := NewRest(AddrCorrect, Secret, commands)
  130. err := rest.Listen(time.Second)
  131. if err != nil {
  132. t.Log("open", err, rest.opened.Load())
  133. return
  134. }
  135. defer rest.Close()
  136. // register
  137. body, err := sendRequest(
  138. URL("/register"),
  139. json.Map{
  140. "login": "test",
  141. },
  142. nil,
  143. "",
  144. )
  145. if err != nil {
  146. t.Fatal(err, string(body))
  147. }
  148. var jm json.Map
  149. json.Unmarshal(body, &jm)
  150. token := jm.StringVal("token", "")
  151. t.Log("token", token)
  152. // auth
  153. body, err = sendRequest(
  154. URL("/login"),
  155. json.Map{},
  156. nil,
  157. token,
  158. )
  159. if err != nil {
  160. t.Fatal(err, string(body))
  161. }
  162. }
  163. func NewFielderTest(id, parentID int64, name string, price float64, child *FielderTest) *FielderTest {
  164. f := &FielderTest{
  165. ID: id,
  166. Password: "top-secret",
  167. ParentID: parentID,
  168. Name: name,
  169. Price: price,
  170. }
  171. f.Fielder = NewFielder(f)
  172. return f
  173. }
  174. type FielderTest struct {
  175. *Fielder
  176. ID int64
  177. Password string
  178. ParentID int64
  179. Name string
  180. Price float64
  181. Child *FielderTest
  182. }
  183. func (s *FielderTest) FieldCheck(name string) bool {
  184. if name == "password" {
  185. return false
  186. }
  187. return true
  188. }
  189. func TestFielder(t *testing.T) {
  190. f := NewFielderTest(1, 10, "VTBR", 100, nil)
  191. f1 := NewFielderTest(10, 100, "SBER", 1000, nil)
  192. f.Child = f1
  193. fm, err := f.Fields(
  194. "id",
  195. "name",
  196. "parent_id",
  197. "price",
  198. "password",
  199. )
  200. if err != nil {
  201. t.Fatal(err)
  202. }
  203. fm.LogPretty()
  204. f.ID = 11
  205. fm, err = f.Fields(
  206. "id",
  207. "name",
  208. "parent_id",
  209. "price",
  210. map[string]any{
  211. "name": "child",
  212. "fields": []any{
  213. "id",
  214. "name",
  215. "parent_id",
  216. map[string]any{
  217. "name": "child",
  218. "fields": []any{
  219. "id",
  220. },
  221. },
  222. },
  223. },
  224. )
  225. if err != nil {
  226. t.Fatal(err)
  227. }
  228. fm.LogPretty()
  229. }
  230. func TestCase(t *testing.T) {
  231. // Тестирование функций
  232. testCamel := "ParentID"
  233. testSnake := "parent_id"
  234. snake := CamelToSnake(testCamel)
  235. camel := SnakeToCamel(testSnake)
  236. println(testCamel, "->", snake)
  237. println(testSnake, "->", camel)
  238. }