summaryrefslogtreecommitdiffhomepage
path: root/dhcpv6/option_bootfileparam_test.go
blob: 3bc266d67a64ea4758c9d45f6cd0fb2396ceabe4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package dhcpv6

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"
)

var (
	testBootfileParams0Compiled = "\x00\x0eroot=/dev/sda1\x00\x00\x00\x02rw"
	testBootfileParams1         = []string{
		"initrd=http://myserver.mycompany.local/initrd.xz",
		"",
		"root=/dev/sda1",
		"rw",
		"netconsole=..:\000:.something\000here.::..",
		string(make([]byte, (1<<16)-1)),
	}
)

// compileTestBootfileParams is an independent implementation of bootfile param encoder
func compileTestBootfileParams(t *testing.T, params []string) []byte {
	var length [2]byte
	buf := bytes.Buffer{}
	for _, param := range params {
		if len(param) >= 1<<16 {
			panic("a too long parameter")
		}
		binary.BigEndian.PutUint16(length[:], uint16(len(param)))
		_, err := buf.Write(length[:])
		require.NoError(t, err)
		_, err = buf.WriteString(param)
		require.NoError(t, err)
	}

	return buf.Bytes()
}

func TestOptBootFileParam(t *testing.T) {
	expected := string(compileTestBootfileParams(t, testBootfileParams1))
	var opt optBootFileParam
	if err := opt.FromBytes([]byte(expected)); err != nil {
		t.Fatal(err)
	}
	if string(opt.ToBytes()) != expected {
		t.Fatalf("Invalid boot file parameter. Expected %v, got %v", expected, opt)
	}
}

func TestParsedTypeOptBootFileParam(t *testing.T) {
	tryParse := func(compiled []byte, expected []string) {
		opt, err := ParseOption(OptionBootfileParam, compiled)
		require.NoError(t, err)
		bootfileParamOpt, ok := opt.(*optBootFileParam)
		require.True(t, ok, fmt.Sprintf("invalid type: %T instead of %T", opt, bootfileParamOpt))
		require.Equal(t, compiled, bootfileParamOpt.ToBytes())
		require.Equal(t, expected, bootfileParamOpt.params)
	}

	tryParse(
		[]byte(testBootfileParams0Compiled),
		[]string{"root=/dev/sda1", "", "rw"},
	)
	tryParse(
		compileTestBootfileParams(t, testBootfileParams1),
		testBootfileParams1,
	)
}