client_test.go 1.1 KB
Newer Older
O
ob-robot 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
package http

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"
)

type Struct struct {
	Value string
}

func TestClient(t *testing.T) {
	listener := NewListener()
	listener.AddHandler("/hello", NewFuncHandler(func(s string) Struct {
		return Struct{Value: "hello " + s}
	}))
	listener.AddHandler("/error", NewFuncHandler(func() error {
		return errors.New("error")
	}))
	defer listener.Close()
	socket := filepath.Join(os.TempDir(), fmt.Sprintf("test_%d.sock", time.Now().UnixNano()))
	err := listener.StartSocket(socket)
	if err != nil {
		t.Error(err)
	}
	defer os.Remove(socket)

	if !CanConnect("unix", socket, time.Second) {
		t.Error("CanConnect should return true")
	}

	client := NewSocketApiClient(socket, time.Second)
	ret := &Struct{}
	err = client.Call("hello", "world", ret)
	if err != nil {
		t.Error(err)
	}
	if ret.Value != "hello world" {
		t.Error("parse result wrong")
	}

	err = client.Call("/not_exists", nil, nil)
	if err == nil {
		t.Error("should error on not_exists api")
	}
	fmt.Println(err)

	err = client.Call("/error", nil, nil)
	if err == nil {
		t.Error("should error on not_exists api")
	}
	fmt.Println(err)
}