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
7package pcapgo
8
9import (
10	"bytes"
11	"testing"
12	"time"
13
14	"github.com/google/gopacket"
15)
16
17func TestWriteHeaderNanos(t *testing.T) {
18	var buf bytes.Buffer
19	w := NewWriterNanos(&buf)
20	w.WriteFileHeader(0x1234, 0x56)
21	want := []byte{
22		0x4d, 0x3c, 0xb2, 0xa1, 0x02, 0x00, 0x04, 0x00,
23		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24		0x34, 0x12, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00,
25	}
26	if got := buf.Bytes(); !bytes.Equal(got, want) {
27		t.Errorf("buf mismatch:\nwant: %+v\ngot:  %+v", want, got)
28	}
29}
30
31func TestWriteHeader(t *testing.T) {
32	var buf bytes.Buffer
33	w := NewWriter(&buf)
34	w.WriteFileHeader(0x1234, 0x56)
35	want := []byte{
36		0xd4, 0xc3, 0xb2, 0xa1, 0x02, 0x00, 0x04, 0x00,
37		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
38		0x34, 0x12, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00,
39	}
40	if got := buf.Bytes(); !bytes.Equal(got, want) {
41		t.Errorf("buf mismatch:\nwant: %+v\ngot:  %+v", want, got)
42	}
43}
44
45func TestWritePacket(t *testing.T) {
46	ci := gopacket.CaptureInfo{
47		Timestamp:     time.Unix(0x01020304, 0xAA*1000),
48		Length:        0xABCD,
49		CaptureLength: 10,
50	}
51	data := []byte{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
52	var buf bytes.Buffer
53	w := NewWriter(&buf)
54	w.WritePacket(ci, data)
55	want := []byte{
56		0x04, 0x03, 0x02, 0x01, 0xAA, 0x00, 0x00, 0x00,
57		0x0A, 0x00, 0x00, 0x00, 0xCD, 0xAB, 0x00, 0x00,
58		0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
59	}
60	if got := buf.Bytes(); !bytes.Equal(got, want) {
61		t.Errorf("buf mismatch:\nwant: %+v\ngot:  %+v", want, got)
62	}
63}
64
65func BenchmarkWritePacket(b *testing.B) {
66	b.StopTimer()
67	ci := gopacket.CaptureInfo{
68		Timestamp:     time.Unix(0x01020304, 0xAA*1000),
69		Length:        0xABCD,
70		CaptureLength: 10,
71	}
72	data := []byte{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
73	var buf bytes.Buffer
74	w := NewWriter(&buf)
75	b.StartTimer()
76
77	for i := 0; i < b.N; i++ {
78		w.WritePacket(ci, data)
79	}
80}
81
82func TestCaptureInfoErrors(t *testing.T) {
83	data := []byte{1, 2, 3, 4}
84	ts := time.Unix(0, 0)
85	for _, test := range []gopacket.CaptureInfo{
86		gopacket.CaptureInfo{
87			Timestamp:     ts,
88			Length:        5,
89			CaptureLength: 5,
90		},
91		gopacket.CaptureInfo{
92			Timestamp:     ts,
93			Length:        3,
94			CaptureLength: 4,
95		},
96	} {
97		var buf bytes.Buffer
98		w := NewWriter(&buf)
99		if err := w.WritePacket(test, data); err == nil {
100			t.Errorf("CaptureInfo %+v should have error", test)
101		}
102	}
103}
104