github.com/xg0n/routine@v0.0.0-20240119033701-c364deb94aee/g/g_test.go (about)

     1  // Copyright 2021-2024 TimAndy. All rights reserved.
     2  // Licensed under the Apache-2.0 license that can be found in the LICENSE file.
     3  
     4  package g
     5  
     6  import (
     7  	"reflect"
     8  	"runtime"
     9  	"sync"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  func TestGetgp(t *testing.T) {
    16  	gp0 := getgp()
    17  	runtime.GC()
    18  	assert.NotNil(t, gp0)
    19  	//
    20  	runTest(t, func() {
    21  		gp := getgp()
    22  		runtime.GC()
    23  		assert.NotNil(t, gp)
    24  		assert.NotEqual(t, gp0, gp)
    25  	})
    26  }
    27  
    28  func TestGetg0(t *testing.T) {
    29  	runTest(t, func() {
    30  		g := getg0()
    31  		runtime.GC()
    32  		stackguard0 := reflect.ValueOf(g).FieldByName("stackguard0")
    33  		assert.Greater(t, stackguard0.Uint(), uint64(0))
    34  	})
    35  }
    36  
    37  func TestGetgt(t *testing.T) {
    38  	runTest(t, func() {
    39  		gt := getgt()
    40  		runtime.GC()
    41  		assert.Equal(t, "g", gt.Name())
    42  		//
    43  		assert.Greater(t, gt.NumField(), 20)
    44  	})
    45  }
    46  
    47  func runTest(t *testing.T, fun func()) {
    48  	run := false
    49  	wg := &sync.WaitGroup{}
    50  	wg.Add(1)
    51  	go func() {
    52  		fun()
    53  		run = true
    54  		wg.Done()
    55  	}()
    56  	wg.Wait()
    57  	assert.True(t, run)
    58  }