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 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
)

const (
	totalTask    = 20
	chunkPerTask = 10
)

var port int

func init() {
	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) {
39
		s := master.NewService(chunkPerTask, time.Second, 1)
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
		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) {
62 63 64 65 66 67 68 69 70 71 72 73 74 75
	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()

76
	c := master.NewClient(addresser(fmt.Sprintf(":%d", port)))
77
	c.SetDataset([]string{p})
78

79 80 81 82 83 84 85 86
	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)
87 88
		}

89 90 91
		_, err = c.GetTask()
		if err == nil {
			t.Fatal(i, "should get error.")
92 93
		}

94 95 96 97 98
		for _, task := range tasks {
			err = c.TaskFinished(task.ID)
			if err != nil {
				t.Fatal(i, err)
			}
99 100
		}
	}
101 102 103 104

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