gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/sentry/socket/netlink/port/port_test.go (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package port
    16  
    17  import (
    18  	"testing"
    19  )
    20  
    21  func TestAllocateHint(t *testing.T) {
    22  	m := New()
    23  
    24  	// We can get the hint port.
    25  	p, ok := m.Allocate(0, 1)
    26  	if !ok {
    27  		t.Errorf("m.Allocate got !ok want ok")
    28  	}
    29  	if p != 1 {
    30  		t.Errorf("m.Allocate(0, 1) got %d want 1", p)
    31  	}
    32  
    33  	// Hint is taken.
    34  	p, ok = m.Allocate(0, 1)
    35  	if !ok {
    36  		t.Errorf("m.Allocate got !ok want ok")
    37  	}
    38  	if p == 1 {
    39  		t.Errorf("m.Allocate(0, 1) got 1 want anything else")
    40  	}
    41  
    42  	// Hint is available for a different protocol.
    43  	p, ok = m.Allocate(1, 1)
    44  	if !ok {
    45  		t.Errorf("m.Allocate got !ok want ok")
    46  	}
    47  	if p != 1 {
    48  		t.Errorf("m.Allocate(1, 1) got %d want 1", p)
    49  	}
    50  
    51  	m.Release(0, 1)
    52  
    53  	// Hint is available again after release.
    54  	p, ok = m.Allocate(0, 1)
    55  	if !ok {
    56  		t.Errorf("m.Allocate got !ok want ok")
    57  	}
    58  	if p != 1 {
    59  		t.Errorf("m.Allocate(0, 1) got %d want 1", p)
    60  	}
    61  }
    62  
    63  func TestAllocateExhausted(t *testing.T) {
    64  	m := New()
    65  
    66  	// Fill all ports (0 is already reserved).
    67  	for i := int32(1); i < maxPorts; i++ {
    68  		p, ok := m.Allocate(0, i)
    69  		if !ok {
    70  			t.Fatalf("m.Allocate got !ok want ok")
    71  		}
    72  		if p != i {
    73  			t.Fatalf("m.Allocate(0, %d) got %d want %d", i, p, i)
    74  		}
    75  	}
    76  
    77  	// Now no more can be allocated.
    78  	p, ok := m.Allocate(0, 1)
    79  	if ok {
    80  		t.Errorf("m.Allocate got %d, ok want !ok", p)
    81  	}
    82  }