github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/port/pool_test.go (about)

     1  /*
     2   * Copyright (C) 2019 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package port
    19  
    20  import (
    21  	"net"
    22  	"strconv"
    23  	"sync"
    24  	"testing"
    25  
    26  	"github.com/stretchr/testify/assert"
    27  )
    28  
    29  const testIterations = 10_000
    30  
    31  func TestAcquiredPortsAreUsable(t *testing.T) {
    32  	pool := NewFixedRangePool(Range{10000, 60000})
    33  
    34  	port, _ := pool.Acquire()
    35  	err := listenUDP(port.Num())
    36  
    37  	assert.NoError(t, err)
    38  }
    39  
    40  func iteratedTest(t *testing.T) {
    41  	start := 59980
    42  	end := 60000
    43  	pool := NewFixedRangePool(Range{start, end})
    44  
    45  	for i := 0; i < testIterations; i++ {
    46  		port, err := pool.Acquire()
    47  		if err != nil {
    48  			t.Errorf("Failed to acquire port: %v", err)
    49  			return
    50  		}
    51  		if port.Num() >= end || port.Num() < start {
    52  			t.Errorf("Port number %d doesn't fits range %d:%d", port, start, end)
    53  			return
    54  		}
    55  	}
    56  }
    57  
    58  func TestFitsPoolRange(t *testing.T) {
    59  	iteratedTest(t)
    60  }
    61  
    62  func TestConcurrentUsage(t *testing.T) {
    63  	var wg sync.WaitGroup
    64  	wg.Add(10)
    65  	for i := 0; i < 10; i++ {
    66  		go func() {
    67  			defer wg.Done()
    68  			iteratedTest(t)
    69  		}()
    70  	}
    71  	wg.Wait()
    72  }
    73  
    74  func listenUDP(port int) error {
    75  	udpAddr, err := net.ResolveUDPAddr("udp", ":"+strconv.Itoa(port))
    76  	if err != nil {
    77  		return err
    78  	}
    79  	udpConn, err := net.ListenUDP("udp", udpAddr)
    80  	if err != nil {
    81  		return err
    82  	}
    83  	defer udpConn.Close()
    84  	return nil
    85  }