github.com/noisysockets/noisysockets@v0.21.2-0.20240515114641-7f467e651c90/routing_table_test.go (about)

     1  // SPDX-License-Identifier: MPL-2.0
     2  /*
     3   * Copyright (C) 2024 The Noisy Sockets Authors.
     4   *
     5   * This Source Code Form is subject to the terms of the Mozilla Public
     6   * License, v. 2.0. If a copy of the MPL was not distributed with this
     7   * file, You can obtain one at http://mozilla.org/MPL/2.0/.
     8   */
     9  
    10  package noisysockets
    11  
    12  import (
    13  	"net/netip"
    14  	"testing"
    15  
    16  	"github.com/neilotoole/slogt"
    17  	"github.com/noisysockets/noisysockets/types"
    18  	"github.com/stretchr/testify/require"
    19  )
    20  
    21  func TestRoutingTable(t *testing.T) {
    22  	rt := newRoutingTable(slogt.New(t))
    23  
    24  	defaultGWPrivateKey, err := types.NewPrivateKey()
    25  	require.NoError(t, err)
    26  
    27  	p := newPeer(nil, "default-gateway", defaultGWPrivateKey.Public())
    28  	p.AddAddresses(netip.MustParseAddr("10.7.0.1"))
    29  	p.AddDestinationPrefixes(netip.MustParsePrefix("0.0.0.0/0"))
    30  
    31  	require.NoError(t, rt.update(p))
    32  
    33  	privateGWPrivateKey, err := types.NewPrivateKey()
    34  	require.NoError(t, err)
    35  
    36  	p = newPeer(nil, "private-gateway", privateGWPrivateKey.Public())
    37  	p.AddAddresses(netip.MustParseAddr("10.7.0.2"))
    38  	p.AddDestinationPrefixes(netip.MustParsePrefix("10.8.0.0/24"))
    39  
    40  	require.NoError(t, rt.update(p))
    41  
    42  	peerPrivateKey, err := types.NewPrivateKey()
    43  	require.NoError(t, err)
    44  
    45  	p = newPeer(nil, "peer", peerPrivateKey.Public())
    46  	p.AddAddresses(netip.MustParseAddr("10.7.0.3"))
    47  
    48  	require.NoError(t, rt.update(p))
    49  
    50  	t.Run("Destination", func(t *testing.T) {
    51  		t.Run("Peer IP", func(t *testing.T) {
    52  			p, ok := rt.destination(netip.MustParseAddr("10.7.0.3"))
    53  			require.True(t, ok)
    54  
    55  			require.Equal(t, "peer", p.Name())
    56  		})
    57  
    58  		t.Run("Gateway", func(t *testing.T) {
    59  			// Should pick the private gateway due to longer prefix length.
    60  			p, ok := rt.destination(netip.MustParseAddr("10.8.0.1"))
    61  			require.True(t, ok)
    62  
    63  			require.Equal(t, "private-gateway", p.Name())
    64  		})
    65  
    66  		t.Run("Default Gateway", func(t *testing.T) {
    67  			p, ok := rt.destination(netip.MustParseAddr("1.1.1.1"))
    68  			require.True(t, ok)
    69  
    70  			require.Equal(t, "default-gateway", p.Name())
    71  		})
    72  	})
    73  }