Fault Injection With testing/iotest
Exercise error paths with testing/iotest readers that fail on first read, return one byte at a time, and simulate timeouts.
Code
package main
import (
"bytes"
"errors"
"fmt"
"io"
"testing/iotest"
)
func main() {
// ErrReader 第一次读取就失败,覆盖错误分支
_, err := io.ReadAll(iotest.ErrReader(errors.New("disk failed")))
fmt.Println("err reader:", err)
// OneByteReader 每次只返回 1 字节,模拟短读
payload := []byte("chunked-transfer")
slow, err := io.ReadAll(iotest.OneByteReader(bytes.NewReader(payload)))
if err != nil {
fmt.Println("one byte reader failed:", err)
return
}
fmt.Println("one byte read:", string(slow), "equal:", bytes.Equal(slow, payload))
// HalfReader 每次最多读半个缓冲区
half, err := io.ReadAll(iotest.HalfReader(bytes.NewReader(payload)))
fmt.Println("half read:", string(half), "err:", err)
// DataErrReader 把数据与 EOF 合并到同一次返回
dataErr := iotest.DataErrReader(bytes.NewReader([]byte("tail")))
buf, err := io.ReadAll(dataErr)
fmt.Println("data err read:", string(buf), "err:", err)
// TimeoutReader 在流末尾返回 ErrTimeout
timedOut, err := io.ReadAll(iotest.TimeoutReader(bytes.NewReader(payload)))
fmt.Println("timeout read bytes:", len(timedOut), "err:", err)
}How it works
Count the function main as the entire surface area of Fault Injection With testing/iotest.
err is inspected at 1 call site before any result is trusted.
Using it
Each run prints the 6 labeled blocks err reader:, one byte reader failed:, one byte read:, half read:, data err read:, timeout read bytes: in source order.
Key statements
if err != nil {
fmt.Println("one byte reader failed:", err)
return
}
_, err := io.ReadAll(iotest.ErrReader(errors.New("disk failed")))
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.
FAQ
- What does Fault Injection With testing/iotest print when run?
- Execute the whole file; each printed line is prefixed with a label like `err reader:`, `one byte reader failed:`, `one byte read:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.