github.com/zooyer/miskit@v1.0.71/imdb/driver/test_test.go (about)

     1  package driver
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/zooyer/miskit/imdb"
    10  	_ "github.com/zooyer/miskit/imdb/driver/buntdb"
    11  	_ "github.com/zooyer/miskit/imdb/driver/redis"
    12  )
    13  
    14  func TestOpen(t *testing.T) {
    15  	var tests = []struct {
    16  		dialect string
    17  		args    string
    18  	}{
    19  		{
    20  			dialect: "buntdb",
    21  			args:    ":memory:",
    22  		},
    23  		{
    24  			dialect: "redis",
    25  			args:    "localhost:6379",
    26  		},
    27  	}
    28  
    29  	for _, test := range tests {
    30  		conn, err := imdb.Open(test.dialect, test.args)
    31  		if err != nil {
    32  			t.Fatal(err)
    33  		}
    34  
    35  		const key = "name"
    36  		var ctx = context.Background()
    37  
    38  		if err = conn.Set(ctx, key, "张三"); err != nil {
    39  			t.Fatal(err)
    40  		}
    41  		value, err := conn.Get(ctx, key)
    42  		if err != nil {
    43  			t.Fatal(err)
    44  		}
    45  		assert.Equal(t, "张三", value)
    46  
    47  		if err = conn.SetEx(ctx, key, "李四", 1); err != nil {
    48  			t.Fatal(err)
    49  		}
    50  		if value, err = conn.Get(ctx, key); err != nil {
    51  			t.Fatal(err)
    52  		}
    53  		assert.Equal(t, "李四", value)
    54  
    55  		time.Sleep(time.Second)
    56  
    57  		if value, err = conn.Get(ctx, key); err != nil {
    58  			t.Fatal(err)
    59  		}
    60  		assert.Equal(t, "", value)
    61  
    62  		if err = conn.Del(ctx, key); err != nil {
    63  			t.Fatal(err)
    64  		}
    65  
    66  		if err = conn.Del(ctx, key); err != nil {
    67  			t.Fatal(err)
    68  		}
    69  
    70  		seconds, err := conn.TTL(ctx, key)
    71  		if err != nil {
    72  			t.Fatal(err)
    73  		}
    74  		assert.Equal(t, int64(-2), seconds)
    75  
    76  		if err = conn.SetEx(ctx, key, "ttl", 1); err != nil {
    77  			t.Fatal(err)
    78  		}
    79  
    80  		if seconds, err = conn.TTL(ctx, key); err != nil {
    81  			t.Fatal(err)
    82  		}
    83  		assert.Equal(t, int64(1), seconds)
    84  	}
    85  }