Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Goで multipart/form-dataのUnit Testingを書く方法

VIVEN, Inc.
August 03, 2022
840

Goで multipart/form-dataのUnit Testingを書く方法

会社HP🦉 https://www.viven.inc/

PDFファイル 📁は以下のリンクからでも、Downloadできます。
https://viven-inc-tech-presentations.s3.ap-northeast-1.amazonaws.com/2022_0803_Go_MultiPartFormData_UnitTesting.pdf

VIVEN, Inc.

August 03, 2022
Tweet

Transcript

  1. ⽬次 1 2 3 4 5 ⾃⼰紹介 なぜ、Unit Testingを書くべきか multipart/form-dataとは

    multipart/form-dataのUnit Testingを書く まとめ・参考資料
  2. multipart/form-dataのUnit Testingを書く(1) url := ”/decks” req := httptest.NewRequest(http.MethodPost, url, bytes.NewReader(body.Bytes()))

    req.Header.Set(“Content-Type”, mwriter.FormDataContentType()) Request周りのポイント2つ 1. MIME Typeのhttptest.NewRequestの第三引数にbodyとしてbyte列を挿⼊ 2. requestのHeaderにmime/multipartのFormDataContentTypeという関数で Content-Typeを設定
  3. multipart/form-dataのUnit Testingを書く(2) body := new(bytes.Buffer) mwriter = multipart.NewWriter(body) mwriter.close() writer1,

    err := mwriter.CreateFormFile(“pdf”, “./tmp.pdf”) writer1.close() _, err := writer1.write([]byte(”pdf sample body”)) writer2, err := mwriter.CreateFormField(“title”) writer2.close() _, err := writer2.write([]byte(“sample title”)) requestのbodyについて 1. Request Bodyのbyte配列をmultipart.Writerがio.Writerを作成し、 そのio.Writerが書き込みを⾏う 2. 画像やPDFといったファイル形式のMIME Typeに対してはCreateFormFileを使⽤ その他のMIME Typeに関しては CreateFormFieldを使⽤
  4. 参考資料 1. Testing in Go (Oreilly Learning) 2. Intro to

    Unit Testing in Go (YouTube) 3. Unit Testing Principles, Practices, and Patterns 4. MIME Types 5. bytes.Buffer (STL) 6. RFC 2046