| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package sqlhealth |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"database/sql" |
| 20 |
"database/sql/driver" |
| 21 |
"errors" |
| 22 |
"sync" |
| 23 |
"testing" |
| 24 |
|
| 25 |
"gocloud.dev/server/health" |
| 26 |
) |
| 27 |
|
| 28 |
var _ = health.Checker((*Checker)(nil)) |
| 29 |
|
| 30 |
func TestCheck(t *testing.T) { |
| 31 |
connector := new(stubConnector) |
| 32 |
db := sql.OpenDB(connector) |
| 33 |
defer db.Close() |
| 34 |
|
| 35 |
check := New(db) |
| 36 |
defer check.Stop() |
| 37 |
if err := check.CheckHealth(); err == nil { |
| 38 |
t.Error("checker starts healthy") |
| 39 |
} |
| 40 |
connector.setHealthy(true) |
| 41 |
|
| 42 |
// Should eventually become healthy. Otherwise, stopped by test timeout. |
| 43 |
for { |
| 44 |
if err := check.CheckHealth(); err == nil { |
| 45 |
break |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
type stubConnector struct { |
| 51 |
mu sync.RWMutex |
| 52 |
healthy bool |
| 53 |
} |
| 54 |
|
| 55 |
func (c *stubConnector) setHealthy(h bool) { |
| 56 |
c.mu.Lock() |
| 57 |
c.healthy = h |
| 58 |
c.mu.Unlock() |
| 59 |
} |
| 60 |
|
| 61 |
func (c *stubConnector) Connect(ctx context.Context) (driver.Conn, error) { |
| 62 |
return &stubConn{c}, nil |
| 63 |
} |
| 64 |
|
| 65 |
func (c *stubConnector) Driver() driver.Driver { |
| 66 |
return nil |
| 67 |
} |
| 68 |
|
| 69 |
type stubConn struct { |
| 70 |
c *stubConnector |
| 71 |
} |
| 72 |
|
| 73 |
func (conn *stubConn) Prepare(query string) (driver.Stmt, error) { |
| 74 |
panic("not implemented") |
| 75 |
} |
| 76 |
|
| 77 |
func (conn *stubConn) Close() error { |
| 78 |
return nil |
| 79 |
} |
| 80 |
|
| 81 |
func (conn *stubConn) Begin() (driver.Tx, error) { |
| 82 |
panic("not implemented") |
| 83 |
} |
| 84 |
|
| 85 |
func (conn *stubConn) Ping(ctx context.Context) error { |
| 86 |
conn.c.mu.RLock() |
| 87 |
healthy := conn.c.healthy |
| 88 |
conn.c.mu.RUnlock() |
| 89 |
if !healthy { |
| 90 |
return errors.New("unhealthy") |
| 91 |
} |
| 92 |
return nil |
| 93 |
} |