github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/pkg/etcd/etcd_test.go (about) 1 // Copyright 2020 PingCAP, Inc. 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 // 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, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package etcd 15 16 import ( 17 "context" 18 "net/url" 19 "testing" 20 "time" 21 22 "github.com/pingcap/check" 23 "github.com/pingcap/ticdc/pkg/util/testleak" 24 "go.etcd.io/etcd/clientv3" 25 "go.etcd.io/etcd/embed" 26 ) 27 28 func Test(t *testing.T) { check.TestingT(t) } 29 30 type etcdSuite struct { 31 etcd *embed.Etcd 32 clientURL *url.URL 33 } 34 35 var _ = check.Suite(&etcdSuite{}) 36 37 // Set up a embeded etcd using free ports. 38 func (s *etcdSuite) SetUpTest(c *check.C) { 39 dir := c.MkDir() 40 curl, e, err := SetupEmbedEtcd(dir) 41 c.Assert(err, check.IsNil) 42 s.clientURL = curl 43 s.etcd = e 44 } 45 46 func (s *etcdSuite) TearDownTest(c *check.C) { 47 s.etcd.Close() 48 logEtcdError: 49 for { 50 select { 51 case err := <-s.etcd.Err(): 52 c.Logf("etcd server error: %v", err) 53 default: 54 break logEtcdError 55 } 56 } 57 } 58 59 func (s *etcdSuite) TestEmbedEtcd(c *check.C) { 60 defer testleak.AfterTest(c)() 61 curl := s.clientURL.String() 62 cli, err := clientv3.New(clientv3.Config{ 63 Endpoints: []string{curl}, 64 DialTimeout: 3 * time.Second, 65 }) 66 c.Assert(err, check.IsNil) 67 defer cli.Close() 68 69 var ( 70 key = "test-key" 71 val = "test-val" 72 ) 73 _, err = cli.Put(context.Background(), key, val) 74 c.Assert(err, check.IsNil) 75 resp, err2 := cli.Get(context.Background(), key) 76 c.Assert(err2, check.IsNil) 77 c.Assert(resp.Kvs, check.HasLen, 1) 78 c.Assert(resp.Kvs[0].Value, check.DeepEquals, []byte(val)) 79 s.TearDownTest(c) 80 }