github.com/noisysockets/noisysockets@v0.21.2-0.20240515114641-7f467e651c90/internal/util/prefix_range_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 util_test
    11  
    12  import (
    13  	"net/netip"
    14  	"testing"
    15  
    16  	"github.com/noisysockets/noisysockets/internal/util"
    17  	"github.com/stretchr/testify/assert"
    18  	"github.com/stretchr/testify/require"
    19  )
    20  
    21  func TestPrefixRange(t *testing.T) {
    22  	t.Run("Valid IPv4 Prefix", func(t *testing.T) {
    23  		prefix := netip.MustParsePrefix("192.168.1.0/24")
    24  		expectedStartAddr := netip.MustParseAddr("192.168.1.0")
    25  		expectedEndAddr := netip.MustParseAddr("192.168.1.255")
    26  		startAddr, endAddr, err := util.PrefixRange(prefix)
    27  		require.NoError(t, err)
    28  
    29  		assert.Equal(t, expectedStartAddr, startAddr)
    30  		assert.Equal(t, expectedEndAddr, endAddr)
    31  	})
    32  
    33  	t.Run("Valid IPv6 Prefix", func(t *testing.T) {
    34  		prefix := netip.MustParsePrefix("2001:db8::/32")
    35  		expectedStartAddr := netip.MustParseAddr("2001:db8::")
    36  		expectedEndAddr := netip.MustParseAddr("2001:db8:ffff:ffff:ffff:ffff:ffff:ffff")
    37  		startAddr, endAddr, err := util.PrefixRange(prefix)
    38  		require.NoError(t, err)
    39  
    40  		assert.Equal(t, expectedStartAddr, startAddr)
    41  		assert.Equal(t, expectedEndAddr, endAddr)
    42  	})
    43  
    44  	t.Run("IPv4 in IPv6 with Invalid Mask", func(t *testing.T) {
    45  		// Invalid mask length for IPv4-mapped-to-IPv6 address.
    46  		prefix := netip.MustParsePrefix("::ffff:192.168.1.0/95")
    47  		_, _, err := util.PrefixRange(prefix)
    48  
    49  		assert.Error(t, err)
    50  	})
    51  }