github.com/ipfans/trojan-go@v0.11.0/api/service/client_test.go (about)

     1  package service
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  	"time"
     8  
     9  	"google.golang.org/grpc"
    10  
    11  	"github.com/ipfans/trojan-go/common"
    12  	"github.com/ipfans/trojan-go/config"
    13  	"github.com/ipfans/trojan-go/statistic/memory"
    14  )
    15  
    16  func TestClientAPI(t *testing.T) {
    17  	ctx, cancel := context.WithCancel(context.Background())
    18  	ctx = config.WithConfig(ctx, memory.Name,
    19  		&memory.Config{
    20  			Passwords: []string{"useless"},
    21  		})
    22  	port := common.PickPort("tcp", "127.0.0.1")
    23  	ctx = config.WithConfig(ctx, Name, &Config{
    24  		APIConfig{
    25  			Enabled: true,
    26  			APIHost: "127.0.0.1",
    27  			APIPort: port,
    28  		},
    29  	})
    30  	auth, err := memory.NewAuthenticator(ctx)
    31  	common.Must(err)
    32  	go RunClientAPI(ctx, auth)
    33  
    34  	time.Sleep(time.Second * 3)
    35  	common.Must(auth.AddUser("hash1234"))
    36  	valid, user := auth.AuthUser("hash1234")
    37  	if !valid {
    38  		t.Fail()
    39  	}
    40  	user.AddTraffic(1234, 5678)
    41  	time.Sleep(time.Second)
    42  	conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", port), grpc.WithInsecure())
    43  	common.Must(err)
    44  	client := NewTrojanClientServiceClient(conn)
    45  	resp, err := client.GetTraffic(ctx, &GetTrafficRequest{User: &User{
    46  		Hash: "hash1234",
    47  	}})
    48  	common.Must(err)
    49  	if resp.TrafficTotal.DownloadTraffic != 5678 || resp.TrafficTotal.UploadTraffic != 1234 {
    50  		t.Fail()
    51  	}
    52  	_, err = client.GetTraffic(ctx, &GetTrafficRequest{})
    53  	if err == nil {
    54  		t.Fail()
    55  	}
    56  	cancel()
    57  }