66 "context"
77 "database/sql/driver"
88 "errors"
9+ "fmt"
10+ "log"
911 "time"
1012)
1113
@@ -85,11 +87,57 @@ func (c *sqlmock) PrepareContext(ctx context.Context, query string) (driver.Stmt
8587 return nil , err
8688}
8789
88- // Implement the "Pinger" interface
89- // for now we do not have a Ping expectation
90- // may be something for the future
90+ // Implement the "Pinger" interface - the explicit DB driver ping was only added to database/sql in Go 1.8
9191func (c * sqlmock ) Ping (ctx context.Context ) error {
92- return nil
92+ if ! c .monitorPings {
93+ return nil
94+ }
95+
96+ ex , err := c .ping ()
97+ if ex != nil {
98+ select {
99+ case <- ctx .Done ():
100+ return ErrCancelled
101+ case <- time .After (ex .delay ):
102+ }
103+ }
104+
105+ return err
106+ }
107+
108+ func (c * sqlmock ) ping () (* ExpectedPing , error ) {
109+ var expected * ExpectedPing
110+ var fulfilled int
111+ var ok bool
112+ for _ , next := range c .expected {
113+ next .Lock ()
114+ if next .fulfilled () {
115+ next .Unlock ()
116+ fulfilled ++
117+ continue
118+ }
119+
120+ if expected , ok = next .(* ExpectedPing ); ok {
121+ break
122+ }
123+
124+ next .Unlock ()
125+ if c .ordered {
126+ return nil , fmt .Errorf ("call to database Ping, was not expected, next expectation is: %s" , next )
127+ }
128+ }
129+
130+ if expected == nil {
131+ msg := "call to database Ping was not expected"
132+ if fulfilled == len (c .expected ) {
133+ msg = "all expectations were already fulfilled, " + msg
134+ }
135+ return nil , fmt .Errorf (msg )
136+ }
137+
138+ expected .triggered = true
139+ expected .Unlock ()
140+ return expected , expected .err
93141}
94142
95143// Implement the "StmtExecContext" interface
@@ -102,4 +150,14 @@ func (stmt *statement) QueryContext(ctx context.Context, args []driver.NamedValu
102150 return stmt .conn .QueryContext (ctx , stmt .query , args )
103151}
104152
153+ func (c * sqlmock ) ExpectPing () * ExpectedPing {
154+ if ! c .monitorPings {
155+ log .Println ("ExpectPing will have no effect as monitoring pings is disabled. Use MonitorPingsOption to enable." )
156+ return nil
157+ }
158+ e := & ExpectedPing {}
159+ c .expected = append (c .expected , e )
160+ return e
161+ }
162+
105163// @TODO maybe add ExpectedBegin.WithOptions(driver.TxOptions)
0 commit comments