client_test.go 1.9 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
	"strconv"
	"strings"
	"testing"
	"time"

H
Helin Wang 已提交
14 15
	log "github.com/sirupsen/logrus"

16
	"github.com/PaddlePaddle/Paddle/go/master"
17
	"github.com/PaddlePaddle/recordio"
18 19 20 21 22 23 24 25 26 27
)

const (
	totalTask    = 20
	chunkPerTask = 10
)

var port int

func init() {
H
Helin Wang 已提交
28 29
	log.SetLevel(log.ErrorLevel)

30 31 32 33 34 35 36 37 38 39 40 41 42
	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)
	}
	port = p

	go func(l net.Listener) {
43
		s := master.NewService(chunkPerTask, time.Second, 1)
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
		server := rpc.NewServer()
		err := server.Register(s)
		if err != nil {
			panic(err)
		}

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

type addresser string

func (a addresser) Address() string {
	return string(a)
}

func TestClientFull(t *testing.T) {
66 67 68 69 70 71 72 73 74 75 76 77 78 79
	const p = "/tmp/master_client_test_0"
	f, err := os.Create(p)
	if err != nil {
		panic(err)
	}

	for i := 0; i < totalTask*chunkPerTask; i++ {
		w := recordio.NewWriter(f, -1, -1)
		w.Write(nil)
		// call Close to force RecordIO writing a chunk.
		w.Close()
	}
	f.Close()

80
	c := master.NewClient(addresser(fmt.Sprintf(":%d", port)))
81
	c.SetDataset([]string{p})
82

83 84 85 86 87 88 89 90
	checkOnePass := func(i int) {
		var tasks []master.Task
		for i := 0; i < totalTask; i++ {
			task, err := c.GetTask()
			if err != nil {
				t.Fatal(i, err)
			}
			tasks = append(tasks, task)
91 92
		}

93 94 95
		_, err = c.GetTask()
		if err == nil {
			t.Fatal(i, "should get error.")
96 97
		}

H
Helin Wang 已提交
98 99 100 101 102 103 104 105 106 107 108
		err = c.TaskFinished(tasks[0].ID)
		if err != nil {
			t.Fatal(err)
		}
		tasks = tasks[1:]
		task, err := c.GetTask()
		if err != nil {
			t.Fatal(err)
		}
		tasks = append(tasks, task)

109 110 111 112 113
		for _, task := range tasks {
			err = c.TaskFinished(task.ID)
			if err != nil {
				t.Fatal(i, err)
			}
114 115
		}
	}
116 117 118 119

	for i := 0; i < 10; i++ {
		checkOnePass(i)
	}
120
}