github.com/portworx/kvdb@v0.0.0-20241107215734-a185a966f535/consul/kv_consul_test.go (about)

     1  package consul
     2  
     3  import (
     4  	"os"
     5  	"os/exec"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/portworx/kvdb"
    10  	"github.com/portworx/kvdb/test"
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  var (
    15  	cmd *exec.Cmd
    16  )
    17  
    18  func TestAll(t *testing.T) {
    19  	// Run the common test suite
    20  	test.Run(New, t, Start, Stop)
    21  
    22  	// Run consul specific tests
    23  	err := Start(true)
    24  	assert.NoError(t, err, "Unable to start kvdb")
    25  	// Wait for kvdb to start
    26  	time.Sleep(5 * time.Second)
    27  
    28  	kv, err := New("pwx/test", nil, nil, nil)
    29  	if err != nil {
    30  		t.Fatalf(err.Error())
    31  	}
    32  	createUsingCAS(kv, t)
    33  	err = Stop()
    34  	assert.NoError(t, err, "Unable to stop kvdb")
    35  }
    36  
    37  func createUsingCAS(kv kvdb.Kvdb, t *testing.T) {
    38  	defer func() {
    39  		_ = kv.DeleteTree("foo")
    40  	}()
    41  	kvPair := &kvdb.KVPair{Key: "foo/createKey", ModifiedIndex: 0}
    42  	_, err := kv.CompareAndSet(kvPair, kvdb.KVModifiedIndex, []byte("some"))
    43  	assert.NoError(t, err, "CompareAndSet failed on create")
    44  
    45  	kvPair, err = kv.Get("foo/createKey")
    46  	assert.NoError(t, err, "Failed in Get")
    47  
    48  	kvPair.ModifiedIndex = 0
    49  	_, err = kv.CompareAndSet(kvPair, kvdb.KVModifiedIndex, []byte("some"))
    50  	assert.Error(t, err, "CompareAndSet did not fail on create")
    51  }
    52  
    53  func Start(removeDir bool) error {
    54  	if removeDir {
    55  		if err := os.RemoveAll("/tmp/consul"); err != nil {
    56  			return err
    57  		}
    58  		if err := os.MkdirAll("/tmp/consul", os.ModeDir); err != nil {
    59  			return err
    60  		}
    61  	}
    62  
    63  	//consul agent -server -client=0.0.0.0  -data-dir /opt/consul/data -bind 0.0.0.0 -syslog -bootstrap-expect 1 -advertise 127.0.0.1
    64  	cmd = exec.Command("consul", "agent", "-server", "-advertise", "127.0.0.1", "-bind", "0.0.0.0", "-data-dir", "/tmp/consul", "-bootstrap-expect", "1")
    65  	err := cmd.Start()
    66  	time.Sleep(5 * time.Second)
    67  	return err
    68  }
    69  
    70  func Stop() error {
    71  	return cmd.Process.Kill()
    72  }