github.com/xraypb/Xray-core@v1.8.1/common/uuid/uuid_test.go (about)

     1  package uuid_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/google/go-cmp/cmp"
     7  	"github.com/xraypb/Xray-core/common"
     8  	. "github.com/xraypb/Xray-core/common/uuid"
     9  )
    10  
    11  func TestParseBytes(t *testing.T) {
    12  	str := "2418d087-648d-4990-86e8-19dca1d006d3"
    13  	bytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3}
    14  
    15  	uuid, err := ParseBytes(bytes)
    16  	common.Must(err)
    17  	if diff := cmp.Diff(uuid.String(), str); diff != "" {
    18  		t.Error(diff)
    19  	}
    20  
    21  	_, err = ParseBytes([]byte{1, 3, 2, 4})
    22  	if err == nil {
    23  		t.Fatal("Expect error but nil")
    24  	}
    25  }
    26  
    27  func TestParseString(t *testing.T) {
    28  	str := "2418d087-648d-4990-86e8-19dca1d006d3"
    29  	expectedBytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3}
    30  
    31  	uuid, err := ParseString(str)
    32  	common.Must(err)
    33  	if r := cmp.Diff(expectedBytes, uuid.Bytes()); r != "" {
    34  		t.Fatal(r)
    35  	}
    36  
    37  	u0, _ := ParseString("example")
    38  	u5, _ := ParseString("feb54431-301b-52bb-a6dd-e1e93e81bb9e")
    39  	if r := cmp.Diff(u0, u5); r != "" {
    40  		t.Fatal(r)
    41  	}
    42  
    43  	_, err = ParseString("2418d087-648k-4990-86e8-19dca1d006d3")
    44  	if err == nil {
    45  		t.Fatal("Expect error but nil")
    46  	}
    47  }
    48  
    49  func TestNewUUID(t *testing.T) {
    50  	uuid := New()
    51  	uuid2, err := ParseString(uuid.String())
    52  
    53  	common.Must(err)
    54  	if uuid.String() != uuid2.String() {
    55  		t.Error("uuid string: ", uuid.String(), " != ", uuid2.String())
    56  	}
    57  	if r := cmp.Diff(uuid.Bytes(), uuid2.Bytes()); r != "" {
    58  		t.Error(r)
    59  	}
    60  }
    61  
    62  func TestRandom(t *testing.T) {
    63  	uuid := New()
    64  	uuid2 := New()
    65  
    66  	if uuid.String() == uuid2.String() {
    67  		t.Error("duplicated uuid")
    68  	}
    69  }
    70  
    71  func TestEquals(t *testing.T) {
    72  	var uuid *UUID
    73  	var uuid2 *UUID
    74  	if !uuid.Equals(uuid2) {
    75  		t.Error("empty uuid should equal")
    76  	}
    77  
    78  	uuid3 := New()
    79  	if uuid.Equals(&uuid3) {
    80  		t.Error("nil uuid equals non-nil uuid")
    81  	}
    82  }