---
title: ioのテストをうまくやりたい
tags: 
author: [ktnyt](https://www.docswell.com/user/nanogram)
site: [Docswell](https://www.docswell.com/)
thumbnail: https://bcdn.docswell.com/page/P7XP2D9ZJX.jpg?width=480
description: ioのテストをうまくやりたい by ktnyt
published: October 02, 24
canonical: https://www.docswell.com/s/nanogram/KWWXMR-tasty-io-test
---
# Page. 1

![Page Image](https://bcdn.docswell.com/page/P7XP2D9ZJX.jpg)

ioのテストをうまくやりたい
by ことね@_ktnyt
at Go言語で語りたい！ #1


# Page. 2

![Page Image](https://bcdn.docswell.com/page/37KDMXPVED.jpg)

自己紹介
ことね（板谷美玲）@_ktnyt
LAPRAS株式会社 Webエンジニア
io.Readerをすこれの人
趣味
プログラミング、ドライブ、音楽


# Page. 3

![Page Image](https://bcdn.docswell.com/page/LJ3RY54QE5.jpg)



# Page. 4

![Page Image](https://bcdn.docswell.com/page/8JDY5DQWJG.jpg)

io.Reader/io.Writer、好きだけどテストは面倒。


# Page. 5

![Page Image](https://bcdn.docswell.com/page/VEP6GXLX78.jpg)

Morph: JSONを構造体リテラルに変換
{
}
&quot;null&quot;: null,
&quot;bool&quot;: true,
&quot;number&quot;: 3.1415,
&quot;string&quot;: &quot;foo&quot;,
&quot;array&quot;: [
null,
true,
3.1415,
&quot;foo&quot;
]
map[string]any{
&quot;null&quot;: nil,
&quot;bool&quot;: true,
&quot;number&quot;: 3.1415,
&quot;string&quot;: &quot;foo&quot;,
&quot;array&quot;: []any{
nil,
true,
3.1415,
&quot;foo&quot;,
},
}


# Page. 6

![Page Image](https://bcdn.docswell.com/page/27V36LQ3JQ.jpg)

Writerに書き込んで文字列結合
func WriteJoined(w io.Writer, ss []string, sep string) (int, error) {
if len(ss) == 0 {
return 0, nil
}
head, tail := ss[0], ss[1:]
n, err := io.WriteString(w, head)
if err != nil {
return n, err
}
if len(tail) &gt; 0 {
m, err := io.WriteString(w, sep)
n += m
if err != nil {
return n, err
}
}
}
m, err := WriteJoined(w, tail, sep)
return n + m, err


# Page. 7

![Page Image](https://bcdn.docswell.com/page/5JG3NXWYEL.jpg)

正常系のテスト
func TestJoinWriter(t *testing.T) {
buf := &amp;bytes.Buffer{}
in := []string{&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;}
sep := &quot;,&quot;
exp := strings.Join(in, sep)
n, err := WriteJoined(buf, in, sep)
if n != len(exp) || err != nil {
t.Errorf(
&quot;WriteJoined(...) = %d, %v: wanted %d, nil&quot;,
n, err, len(exp),
)
}
}
got := buf.String()
if got != exp {
t.Errorf(
&quot;unexpected bytes written (-exp, +got): %v&quot;,
diff.LineDiff(exp, got).Join(),
)
}


# Page. 8

![Page Image](https://bcdn.docswell.com/page/47Q5Q836EP.jpg)

正常系以外は？
func WriteJoined(w io.Writer, ss []string, sep string) (int, error) {
if len(ss) == 0 {
return 0, nil
}
head, tail := ss[0], ss[1:]
n, err := io.WriteString(w, head)
if err != nil {
return n, err //
}
どうやってテストする？
if len(tail) &gt; 0 {
m, err := io.WriteString(w, sep)
n += m
if err != nil {
return n, err //
}
}
どうやってテストする？
}
m, err := WriteJoined(w, tail, sep)
return n + m, err


# Page. 9

![Page Image](https://bcdn.docswell.com/page/KE49N21MJ1.jpg)

とりあえず専用のWriterを作る
var errOnWriteCall = errors.New(&quot;write call error&quot;)
type ErrOnCallWriter struct {
w
io.Writer
call int
count int
}
func NewErrOnWriteCall(w io.Writer, call int) *ErrOnCallWriter {
return &amp;ErrOnCallWriter{w, call, 0}
}
func (w *ErrOnCallWriter) Write(p []byte) (int, error) {
w.count++
if w.count == w.call {
return 0, errOnWriteCall
}
return w.w.Write(p)
}


# Page. 10

![Page Image](https://bcdn.docswell.com/page/L71K5MGYEG.jpg)

要素の書き込みでエラーを上げるテスト
func TestJoinWriterElementError(t *testing.T) {
buf := &amp;bytes.Buffer{}
w := NewErrOnWriteCall(buf, 1)
in := []string{&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;}
sep := &quot;,&quot;
exp := &quot;&quot;
n, err := WriteJoined(w, in, sep)
if n != len(exp) || !errors.Is(err, errOnWriteCall) {
t.Errorf(
&quot;WriteJoined(...) = %d, %v: wanted %d, %v&quot;,
n, err, len(exp), errOnWriteCall,
)
}
}
got := buf.String()
if got != exp {
t.Errorf(
&quot;unexpected bytes written (-exp, +got): %v&quot;,
diff.LineDiff(exp, got).Join(),
)
}


# Page. 11

![Page Image](https://bcdn.docswell.com/page/G7WD53K1E2.jpg)

区切り文字で書き込みでエラーを上げるテスト
func TestJoinWriterSepError(t *testing.T) {
buf := &amp;bytes.Buffer{}
w := NewErrOnWriteCall(buf, 2)
in := []string{&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;}
sep := &quot;,&quot;
exp := &quot;foo&quot;
n, err := WriteJoined(w, in, sep)
if n != len(exp) || !errors.Is(err, errOnWriteCall) {
t.Errorf(
&quot;WriteJoined(...) = %d, %v: wanted %d, %v&quot;,
n, err, len(exp), errOnWriteCall,
)
}
}
got := buf.String()
if got != exp {
t.Errorf(
&quot;unexpected bytes written (-exp, +got): %v&quot;,
diff.LineDiff(exp, got).Join(),
)
}


# Page. 12

![Page Image](https://bcdn.docswell.com/page/4JZGNVZX73.jpg)

構造が見えてきた
ここまで来るとテーブルテストが書けそう。
同時に 「mバイト書き込んだらエラーも便利そう」 という欲が出てくる。


# Page. 13

![Page Image](https://bcdn.docswell.com/page/YE6Y85ZPJV.jpg)

汎用化の思考
実現したいこと
n回目の呼び出しでエラーを返す
mバイト書き込んだらエラーを返す
最初にぱっと思いつくやり方
ErrOnCallAndBytesWriter(w io.Writer, n int, err1 error, m int, err2 error)
圧倒的コレジャナイ感
もっといいやり方があるはず。


# Page. 14

![Page Image](https://bcdn.docswell.com/page/GE5G9YWPE4.jpg)

Not 汎用 but 抽象
できないといけないこと
メソッドを持つオブジェクトを簡単につくれる。
→ io.Writer を関数型でモックする。
Write(p []byte) (int, error)
// Writer represents a mocked Write call.
type Writer func(p []byte) (int, error)
// Write simulates a Write call by using the provided mock function.
func (write Writer) Write(p []byte) (int, error) {
return write(p)
}


# Page. 15

![Page Image](https://bcdn.docswell.com/page/972Y2GQZ7R.jpg)

これでいける？


# Page. 16

![Page Image](https://bcdn.docswell.com/page/DJYGYVWNJM.jpg)

n回目の呼び出しでエラーを返す
func CallCountWriter(write func(i int, p []byte) (int, error)) Writer {
i := 0
return func(p []byte) (int, error) {
i++
return write(i, p)
}
}
func ErrOnCallWriter(count int, err error) Writer {
return CallCountWriter(func(i int, p []byte) (int, error) {
if count == i {
return 0, err
}
return len(p), nil
})
}


# Page. 17

![Page Image](https://bcdn.docswell.com/page/V7NGPM9VE8.jpg)

mバイト書き込んだらエラーを返す
func ByteCountWriter(write func(i int, p []byte) (int, error)) Writer {
i := 0
return func(p []byte) (int, error) {
n, err := write(i, p)
i += len(p)
return n, err
}
}
func ErrOnByteWriter(count int, err error) Writer {
return ByteCountWriter(func(i int, p []byte) (int, error) {
n := count - i
switch {
case len(p) &lt; n:
return len(p), nil
case 0 &lt; n:
return n, err
default:
return 0, err
}
})
}


# Page. 18

![Page Image](https://bcdn.docswell.com/page/YJ9W3N2VJ3.jpg)

良さそうだけど、なんで？
メソッド vs. 関数
メソッドはインライン定義できないけど関数は無名関数でインライン定義できる。
→この違いが使い勝手に大きく影響する。
例：テーブルテストに直書きできる。


# Page. 19

![Page Image](https://bcdn.docswell.com/page/GJ8NMK54ED.jpg)

やったことの本質
Write関数をio.Writerとして使えるようにした。


# Page. 20

![Page Image](https://bcdn.docswell.com/page/LJLP3ZYVER.jpg)

io.Readerの場合はもう一歩
io.Writerは書き込まなくても挙動的におかしくない（呼び出し元には基本的に影響がない*）
がio.Readerは書き込みしないといけないという違いがある。
→io.ReaderをWrapする仕組みを作ってあげるひと手間が不可欠。
* Tips: Writerで書き込み結果がほしい場合はio.MultiWriterを使う。


# Page. 21

![Page Image](https://bcdn.docswell.com/page/47M4DVNNEW.jpg)

n回目のReadでエラーを返す（一部抜粋）
type ReadMocker struct {
r io.Reader
}
func NewReadMocker(r io.Reader) ReadMocker {
return ReadMocker{r}
}
func (mock ReadMocker) ErrOnCall(count int, err error) Reader {
return CallCountReader(func(i int, p []byte) (int, error) {
n, rerr := mock.r.Read(p)
if i == count {
return n, err
}
return n, rerr
})
}


# Page. 22

![Page Image](https://bcdn.docswell.com/page/P7RW42D4E9.jpg)

iomockでらくらくioモック
任意のタイミングでエラーを返すio.Reader/io.Writerが作れる。
コードの物理的カバレッジも論理的カバレッジも上げやすく。
コンビネータが如くつなげればかなり複雑なテストも書けるはず。


# Page. 23

![Page Image](https://bcdn.docswell.com/page/PJXP2D1ZEX.jpg)

Happy io Life!


