github.com/gopacket/gopacket@v1.1.0/layers/base_test.go (about)

     1  // Copyright 2012, Google, Inc. All rights reserved.
     2  //
     3  // Use of this source code is governed by a BSD-style license
     4  // that can be found in the LICENSE file in the root of the source
     5  // tree.
     6  
     7  // This file contains some test helper functions.
     8  
     9  package layers
    10  
    11  import (
    12  	"testing"
    13  
    14  	"github.com/gopacket/gopacket"
    15  )
    16  
    17  func checkLayers(p gopacket.Packet, want []gopacket.LayerType, t *testing.T) {
    18  	layers := p.Layers()
    19  	t.Log("Checking packet layers, want", want)
    20  	for _, l := range layers {
    21  		t.Logf("  Got layer %v, %d bytes, payload of %d bytes", l.LayerType(),
    22  			len(l.LayerContents()), len(l.LayerPayload()))
    23  	}
    24  	t.Log(p)
    25  	if len(layers) < len(want) {
    26  		t.Errorf("  Number of layers mismatch: got %d want %d", len(layers),
    27  			len(want))
    28  		return
    29  	}
    30  	for i, l := range want {
    31  		if l == gopacket.LayerTypePayload {
    32  			// done matching layers
    33  			return
    34  		}
    35  
    36  		if layers[i].LayerType() != l {
    37  			t.Errorf("  Layer %d mismatch: got %v want %v", i,
    38  				layers[i].LayerType(), l)
    39  		}
    40  	}
    41  }
    42  
    43  // Checks that when a serialized version of p is decoded, p and the serialized version of p are the same.
    44  // Does not work for packets where the order of options can change, like icmpv6 router advertisements, dhcpv6, etc.
    45  func checkSerialization(p gopacket.Packet, t *testing.T) {
    46  	buf := gopacket.NewSerializeBuffer()
    47  	opts := gopacket.SerializeOptions{
    48  		ComputeChecksums: false,
    49  		FixLengths:       false,
    50  	}
    51  	if err := gopacket.SerializePacket(buf, opts, p); err != nil {
    52  		t.Error("Failed to encode packet:", err)
    53  	}
    54  
    55  	p2 := gopacket.NewPacket(buf.Bytes(), LinkTypeEthernet, gopacket.Default)
    56  	if p2.ErrorLayer() != nil {
    57  		t.Error("Failed to decode the re-encoded packet:", p2.ErrorLayer().Error())
    58  	}
    59  
    60  	if p2.Dump() != p.Dump() {
    61  		t.Errorf("The decoded and the re-encoded packet are different!\nDecoded:\n%s\n Re-Encoded:\n%s", p.Dump(), p2.Dump())
    62  	}
    63  }