github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/tcpip/header/ipversion_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 header_test
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/SagerNet/gvisor/pkg/tcpip/header"
    21  )
    22  
    23  func TestIPv4(t *testing.T) {
    24  	b := header.IPv4(make([]byte, header.IPv4MinimumSize))
    25  	b.Encode(&header.IPv4Fields{})
    26  
    27  	const want = header.IPv4Version
    28  	if v := header.IPVersion(b); v != want {
    29  		t.Fatalf("Bad version, want %v, got %v", want, v)
    30  	}
    31  }
    32  
    33  func TestIPv6(t *testing.T) {
    34  	b := header.IPv6(make([]byte, header.IPv6MinimumSize))
    35  	b.Encode(&header.IPv6Fields{})
    36  
    37  	const want = header.IPv6Version
    38  	if v := header.IPVersion(b); v != want {
    39  		t.Fatalf("Bad version, want %v, got %v", want, v)
    40  	}
    41  }
    42  
    43  func TestOtherVersion(t *testing.T) {
    44  	const want = header.IPv4Version + header.IPv6Version
    45  	b := make([]byte, 1)
    46  	b[0] = want << 4
    47  
    48  	if v := header.IPVersion(b); v != want {
    49  		t.Fatalf("Bad version, want %v, got %v", want, v)
    50  	}
    51  }
    52  
    53  func TestTooShort(t *testing.T) {
    54  	b := make([]byte, 1)
    55  	b[0] = (header.IPv4Version + header.IPv6Version) << 4
    56  
    57  	// Get the version of a zero-length slice.
    58  	const want = -1
    59  	if v := header.IPVersion(b[:0]); v != want {
    60  		t.Fatalf("Bad version, want %v, got %v", want, v)
    61  	}
    62  
    63  	// Get the version of a nil slice.
    64  	if v := header.IPVersion(nil); v != want {
    65  		t.Fatalf("Bad version, want %v, got %v", want, v)
    66  	}
    67  }