package database import ( "context" "database/sql" "database/sql/driver" "errors" "io" "testing" "time" ) // failingConnector opens connections whose queries fail on the first row read, // like a disk I/O error or a corrupted page. type failingConnector struct{} func (failingConnector) Connect(context.Context) (driver.Conn, error) { return failingConn{}, nil } func (failingConnector) Driver() driver.Driver { return nil } type failingConn struct{} func (failingConn) Prepare(string) (driver.Stmt, error) { return nil, io.EOF } func (failingConn) Close() error { return nil } func (failingConn) Begin() (driver.Tx, error) { return nil, io.EOF } func (failingConn) QueryContext(context.Context, string, []driver.NamedValue) (driver.Rows, error) { return failingRows{}, nil } type failingRows struct{} func (failingRows) Columns() []string { return []string{"value"} } func (failingRows) Close() error { return nil } func (failingRows) Next([]driver.Value) error { return errors.New("disk I/O error") } func TestReadersReturnRowReadErrors(t *testing.T) { db := &DB{DB: sql.OpenDB(failingConnector{})} defer db.Close() readers := map[string]func() error{ "GetAllMetricsContainer": func() error { _, err := db.GetAllMetricsContainer("web"); return err }, "GetLastNContainerMetrics": func() error { _, err := db.GetLastNContainerMetrics("web", 50); return err }, "GetAllMetrics": func() error { _, err := db.GetAllMetrics(); return err }, "GetLastNMetrics": func() error { _, err := db.GetLastNMetrics(50); return err }, "GetMetricsInRange": func() error { _, err := db.GetMetricsInRange(time.Now().Add(-time.Hour), time.Now()) return err }, } for name, read := range readers { if err := read(); err == nil { t.Errorf("%s returned no error after a failed row read", name) } } }