Browse Source

Merge pull request #10557 from johncming/add_test

contrib/raftexample: add test for httpKVAPI.
Xiang Li 6 years ago
parent
commit
d5e94b1c0d
1 changed files with 63 additions and 0 deletions
  1. 63 0
      contrib/raftexample/raftexample_test.go

+ 63 - 0
contrib/raftexample/raftexample_test.go

@@ -15,9 +15,14 @@
 package main
 package main
 
 
 import (
 import (
+	"bytes"
 	"fmt"
 	"fmt"
+	"io/ioutil"
+	"net/http"
+	"net/http/httptest"
 	"os"
 	"os"
 	"testing"
 	"testing"
+	"time"
 
 
 	"go.etcd.io/etcd/raft/raftpb"
 	"go.etcd.io/etcd/raft/raftpb"
 )
 )
@@ -157,3 +162,61 @@ func TestCloseProposerInflight(t *testing.T) {
 		t.Fatalf("Commit failed")
 		t.Fatalf("Commit failed")
 	}
 	}
 }
 }
+
+func TestPutAndGetKeyValue(t *testing.T) {
+	clusters := []string{"http://127.0.0.1:9021"}
+
+	proposeC := make(chan string)
+	defer close(proposeC)
+
+	confChangeC := make(chan raftpb.ConfChange)
+	defer close(confChangeC)
+
+	var kvs *kvstore
+	getSnapshot := func() ([]byte, error) { return kvs.getSnapshot() }
+	commitC, errorC, snapshotterReady := newRaftNode(1, clusters, false, getSnapshot, proposeC, confChangeC)
+
+	kvs = newKVStore(<-snapshotterReady, proposeC, commitC, errorC)
+
+	srv := httptest.NewServer(&httpKVAPI{
+		store:       kvs,
+		confChangeC: confChangeC,
+	})
+	defer srv.Close()
+
+	// wait server started
+	<-time.After(time.Second * 3)
+
+	wantKey, wantValue := "test-key", "test-value"
+	url := fmt.Sprintf("%s/%s", srv.URL, wantKey)
+	body := bytes.NewBufferString(wantValue)
+	cli := srv.Client()
+
+	req, err := http.NewRequest("PUT", url, body)
+	if err != nil {
+		t.Fatal(err)
+	}
+	req.Header.Set("Content-Type", "text/html; charset=utf-8")
+	_, err = cli.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// wait for a moment for processing message, otherwise get would be failed.
+	<-time.After(time.Second)
+
+	resp, err := cli.Get(url)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	data, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer resp.Body.Close()
+
+	if gotValue := string(data); wantValue != gotValue {
+		t.Fatalf("expect %s, got %s", wantValue, gotValue)
+	}
+}