github.com/searKing/golang/go@v1.2.74/reflect/example_test.go (about)

     1  // Copyright 2022 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package reflect
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  	osexec "os/exec"
    11  	"testing"
    12  )
    13  
    14  func TestGetppid(t *testing.T) {
    15  	if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
    16  		fmt.Print(os.Getppid())
    17  		os.Exit(0)
    18  	}
    19  
    20  	cmd := osexec.Command(os.Args[0], "-test.run=TestGetppid")
    21  	cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
    22  
    23  	// verify that Getppid() from the forked process reports our process id
    24  	output, err := cmd.CombinedOutput()
    25  	if err != nil {
    26  		t.Fatalf("Failed to spawn child process: %v %q", err, string(output))
    27  	}
    28  
    29  	childPpid := string(output)
    30  	ourPid := fmt.Sprintf("%d", os.Getpid())
    31  	if childPpid != ourPid {
    32  		t.Fatalf("Child process reports parent process id '%v', expected '%v'", childPpid, ourPid)
    33  	}
    34  }
    35  
    36  func TestTruncate(t *testing.T) {
    37  	type Human struct {
    38  		Name       string
    39  		Desc       []byte
    40  		Friends    []Human
    41  		FriendById map[string][]Human
    42  	}
    43  
    44  	var info = Human{
    45  		Name:       "ALPHA",
    46  		Desc:       []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
    47  		Friends:    []Human{{Name: "BETA", Desc: []byte("abcdefghijklmnopqrstuvwxyz")}},
    48  		FriendById: map[string][]Human{"quick brown fox": {{Name: "GRAMMAR", Desc: []byte("The quick brown fox jumps over the lazy dog")}}},
    49  	}
    50  	TruncateBytes(info, 3)
    51  	TruncateString(info, 3)
    52  	fmt.Printf("info truncated\n")
    53  	fmt.Printf("info.Name: %s\n", info.Name)
    54  	fmt.Printf("info.Desc: %s\n", info.Desc)
    55  
    56  	for i, friend := range info.Friends {
    57  		fmt.Printf("info.Friends[%d].Name: %s\n", i, friend.Name)
    58  		fmt.Printf("info.Friends[%d].Desc: %s\n", i, friend.Desc)
    59  	}
    60  	for id, friends := range info.FriendById {
    61  		for i, friend := range friends {
    62  			fmt.Printf("info.FriendById[%s][%d].Name: %s\n", id, i, friend.Name)
    63  			fmt.Printf("info.FriendById[%s][%d].Desc: %s\n", id, i, friend.Desc)
    64  		}
    65  	}
    66  	// Output:
    67  	// info truncated
    68  	// info.Name: size: 5, string: ALP
    69  	// info.Desc: size: 26, bytes: ABC
    70  	// info.Friends[0].Name: size: 4, string: BET
    71  	// info.Friends[0].Desc: size: 26, bytes: abc
    72  	// info.FriendById[quick brown fox][0].Name: size: 7, string: GRA
    73  	// info.FriendById[quick brown fox][0].Desc: size: 43, bytes: The
    74  
    75  }