Source file src/runtime/trace2map_test.go

     1  // Copyright 2024 The Go Authors. 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 runtime_test
     6  
     7  import (
     8  	. "runtime"
     9  	"strconv"
    10  	"sync"
    11  	"testing"
    12  )
    13  
    14  func TestTraceMap(t *testing.T) {
    15  	var m TraceMap
    16  
    17  	// Try all these operations multiple times between resets, to make sure
    18  	// we're resetting properly.
    19  	for range 3 {
    20  		var d = [...]string{
    21  			"a",
    22  			"b",
    23  			"aa",
    24  			"ab",
    25  			"ba",
    26  			"bb",
    27  		}
    28  		for i, s := range d {
    29  			id, inserted := m.PutString(s)
    30  			if !inserted {
    31  				t.Errorf("expected to have inserted string %q, but did not", s)
    32  			}
    33  			if id != uint64(i+1) {
    34  				t.Errorf("expected string %q to have ID %d, but got %d instead", s, i+1, id)
    35  			}
    36  		}
    37  		for i, s := range d {
    38  			id, inserted := m.PutString(s)
    39  			if inserted {
    40  				t.Errorf("inserted string %q, but expected to have not done so", s)
    41  			}
    42  			if id != uint64(i+1) {
    43  				t.Errorf("expected string %q to have ID %d, but got %d instead", s, i+1, id)
    44  			}
    45  		}
    46  		m.Reset()
    47  	}
    48  }
    49  
    50  func TestTraceMapConcurrent(t *testing.T) {
    51  	var m TraceMap
    52  
    53  	var wg sync.WaitGroup
    54  	for i := range 3 {
    55  		wg.Add(1)
    56  		go func(i int) {
    57  			defer wg.Done()
    58  
    59  			si := strconv.Itoa(i)
    60  			var d = [...]string{
    61  				"a" + si,
    62  				"b" + si,
    63  				"aa" + si,
    64  				"ab" + si,
    65  				"ba" + si,
    66  				"bb" + si,
    67  			}
    68  			ids := make([]uint64, 0, len(d))
    69  			for _, s := range d {
    70  				id, inserted := m.PutString(s)
    71  				if !inserted {
    72  					t.Errorf("expected to have inserted string %q, but did not", s)
    73  				}
    74  				ids = append(ids, id)
    75  			}
    76  			for i, s := range d {
    77  				id, inserted := m.PutString(s)
    78  				if inserted {
    79  					t.Errorf("inserted string %q, but expected to have not done so", s)
    80  				}
    81  				if id != ids[i] {
    82  					t.Errorf("expected string %q to have ID %d, but got %d instead", s, ids[i], id)
    83  				}
    84  			}
    85  		}(i)
    86  	}
    87  	wg.Wait()
    88  	m.Reset()
    89  }
    90  

View as plain text