...

Source file src/github.com/gomodule/redigo/internal/redistest/testdb.go

Documentation: github.com/gomodule/redigo/internal/redistest

     1  // Copyright 2014 Gary Burd
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"): you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at
     6  //
     7  //     http://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, WITHOUT
    11  // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    12  // License for the specific language governing permissions and limitations
    13  // under the License.
    14  
    15  // Package redistest contains utilities for writing Redigo tests.
    16  package redistest
    17  
    18  import (
    19  	"errors"
    20  	"time"
    21  
    22  	"github.com/gomodule/redigo/redis"
    23  )
    24  
    25  type testConn struct {
    26  	redis.Conn
    27  }
    28  
    29  func (t testConn) Close() error {
    30  	_, err := t.Conn.Do("SELECT", "9")
    31  	if err != nil {
    32  		return nil
    33  	}
    34  	_, err = t.Conn.Do("FLUSHDB")
    35  	if err != nil {
    36  		return err
    37  	}
    38  	return t.Conn.Close()
    39  }
    40  
    41  // Dial dials the local Redis server and selects database 9. To prevent
    42  // stomping on real data, DialTestDB fails if database 9 contains data. The
    43  // returned connection flushes database 9 on close.
    44  func Dial() (redis.Conn, error) {
    45  	c, err := redis.DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	_, err = c.Do("SELECT", "9")
    51  	if err != nil {
    52  		c.Close()
    53  		return nil, err
    54  	}
    55  
    56  	n, err := redis.Int(c.Do("DBSIZE"))
    57  	if err != nil {
    58  		c.Close()
    59  		return nil, err
    60  	}
    61  
    62  	if n != 0 {
    63  		c.Close()
    64  		return nil, errors.New("database #9 is not empty, test can not continue")
    65  	}
    66  
    67  	return testConn{c}, nil
    68  }
    69  

View as plain text