github.com/cilium/cilium@v1.16.2/pkg/policy/identifier_test.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package policy
     5  
     6  import (
     7  	"sync"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/require"
    11  
    12  	"github.com/cilium/cilium/pkg/identity"
    13  )
    14  
    15  type DummyEndpoint struct {
    16  	rev      uint64
    17  	Endpoint // Implement methods of the interface that need to mock out real behavior.
    18  }
    19  
    20  func (d *DummyEndpoint) GetSecurityIdentity() (*identity.Identity, error) {
    21  	return nil, nil
    22  }
    23  
    24  func (d *DummyEndpoint) PolicyRevisionBumpEvent(rev uint64) {
    25  	d.rev = rev
    26  }
    27  
    28  func (d *DummyEndpoint) RLockAlive() error {
    29  	return nil
    30  }
    31  
    32  func (d *DummyEndpoint) RUnlock() {
    33  }
    34  
    35  func TestNewEndpointSet(t *testing.T) {
    36  	d := &DummyEndpoint{}
    37  	epSet := NewEndpointSet(map[Endpoint]struct{}{
    38  		d: {},
    39  	})
    40  	require.Equal(t, 1, epSet.Len())
    41  	epSet.Delete(d)
    42  	require.Equal(t, 0, epSet.Len())
    43  }
    44  
    45  func TestForEachGo(t *testing.T) {
    46  	var wg sync.WaitGroup
    47  
    48  	d0 := &DummyEndpoint{}
    49  	d1 := &DummyEndpoint{}
    50  
    51  	epSet := NewEndpointSet(map[Endpoint]struct{}{
    52  		d0: {},
    53  		d1: {},
    54  	})
    55  	epSet.ForEachGo(&wg, func(e Endpoint) {
    56  		e.PolicyRevisionBumpEvent(100)
    57  	})
    58  
    59  	wg.Wait()
    60  
    61  	require.Equal(t, uint64(100), d0.rev)
    62  	require.Equal(t, uint64(100), d1.rev)
    63  }
    64  
    65  func BenchmarkForEachGo(b *testing.B) {
    66  	m := make(map[Endpoint]struct{}, b.N)
    67  	for i := uint64(0); i < uint64(b.N); i++ {
    68  		m[&DummyEndpoint{rev: i}] = struct{}{}
    69  	}
    70  	epSet := NewEndpointSet(m)
    71  
    72  	b.StartTimer()
    73  	var wg sync.WaitGroup
    74  	epSet.ForEachGo(&wg, func(e Endpoint) {
    75  		e.PolicyRevisionBumpEvent(100)
    76  	})
    77  	wg.Wait()
    78  	b.StopTimer()
    79  }