client_test.go 1.7 KB
Newer Older
1 2 3 4 5 6 7
package master_test

import (
	"fmt"
	"net"
	"net/http"
	"net/rpc"
8
	"os"
9 10 11 12 13 14
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/PaddlePaddle/Paddle/go/master"
15
	"github.com/PaddlePaddle/recordio"
16 17
)

H
Helin Wang 已提交
18 19 20 21 22
func TestNextRecord(t *testing.T) {
	const (
		path  = "/tmp/master_client_TestFull"
		total = 50
	)
23 24 25 26 27 28 29 30 31 32 33
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		panic(err)
	}

	ss := strings.Split(l.Addr().String(), ":")
	p, err := strconv.Atoi(ss[len(ss)-1])
	if err != nil {
		panic(err)
	}
	go func(l net.Listener) {
H
Helin Wang 已提交
34
		s, err := master.NewService(&master.InMemStore{}, 10, time.Second, 1)
35 36 37 38
		if err != nil {
			panic(err)
		}

39
		server := rpc.NewServer()
40
		err = server.Register(s)
41 42 43 44 45 46 47 48 49 50 51 52
		if err != nil {
			panic(err)
		}

		mux := http.NewServeMux()
		mux.Handle(rpc.DefaultRPCPath, server)
		err = http.Serve(l, mux)
		if err != nil {
			panic(err)
		}
	}(l)

H
Helin Wang 已提交
53
	f, err := os.Create(path)
54 55 56 57
	if err != nil {
		panic(err)
	}

H
Helin Wang 已提交
58 59
	w := recordio.NewWriter(f, -1, -1)
	for i := 0; i < total; i++ {
H
Helin Wang 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73
		_, err = w.Write([]byte{byte(i)})
		if err != nil {
			panic(err)
		}
	}

	err = w.Close()
	if err != nil {
		panic(err)
	}

	err = f.Close()
	if err != nil {
		panic(err)
74
	}
H
Helin Wang 已提交
75

76 77 78
	curAddr := make(chan string, 1)
	curAddr <- fmt.Sprintf(":%d", p)
	c := master.NewClient(curAddr, 10)
H
Helin Wang 已提交
79 80 81 82 83
	err = c.SetDataset([]string{path})
	if err != nil {
		panic(err)
	}

H
Helin Wang 已提交
84 85
	for pass := 0; pass < 50; pass++ {
		received := make(map[byte]bool)
G
gongweibao 已提交
86
		for i := 0; i < total; i++ {
G
gongweibao 已提交
87 88 89 90 91
			r, err := c.NextRecord()
			if err != nil {
				t.Fatal(pass, i, "Read error:", err)
			}

H
Helin Wang 已提交
92
			if len(r) != 1 {
G
gongweibao 已提交
93
				t.Fatal(pass, i, "Length should be 1.", r)
94
			}
G
gongweibao 已提交
95

H
Helin Wang 已提交
96
			if received[r[0]] {
G
gongweibao 已提交
97
				t.Fatal(pass, i, "Received duplicate.", received, r)
98
			}
H
Helin Wang 已提交
99
			received[r[0]] = true
100 101 102
		}
	}
}