1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package command
17
18 import (
19 "strings"
20 "testing"
21
22 "github.com/stretchr/testify/assert"
23 )
24
25 type IptablesTest struct {
26 Exec `exec:"iptables"`
27 Port string `para:"-p"`
28 Ports []string `para:"--ports"`
29 EPort string `para:"-ep"`
30 EPorts []string `para:"--e_ports"`
31 Match `sub_command:""`
32 Match_ `sub_command:""`
33 }
34
35 type Match struct {
36 Exec `exec:"-m"`
37 Helper string `para:"--helper"`
38 }
39
40 type Match_ struct {
41 Exec `exec:"-m"`
42 Helper string `para:"--helper"`
43 }
44
45 func TestMarshal(t *testing.T) {
46 n := IptablesTest{
47 NewExec(),
48 "20",
49 []string{"2021", "2023"},
50 "",
51 []string{"", ""},
52 Match{NewExec(), "help"},
53 Match_{},
54 }
55 path, args, err := Marshal(n)
56 assert.NoError(t, err, "nil")
57 assert.Equal(t, "iptables -p 20 --ports 2021 2023 -m --helper help",
58 path+" "+strings.Join(args, " "))
59 }
60
61 type Iptables struct {
62 Exec `exec:"iptables"`
63 Tables string `para:"-t"`
64 Command string `para:""`
65 Chain string `para:""`
66 JumpTarget string `para:"-j"`
67 Protocol string `para:"--protocol"`
68 MatchExtension string `para:"-m"`
69 SPorts string `para:"--source-ports"`
70 DPorts string `para:"--destination-ports"`
71 SPort string `para:"--source-port"`
72 DPort string `para:"--destination-port"`
73 TcpFlags string `para:"--tcp-flags"`
74 }
75
76 type TestInvalidParaType struct {
77 Exec `exec:"test"`
78 P int `para:"-p"`
79 }
80
81 type TestInvalidParaSliceType struct {
82 Exec `exec:"test"`
83 P []int `para:"-p"`
84 }
85
86 func TestMarshalExample(t *testing.T) {
87 n := Iptables{
88 Exec: NewExec(),
89 Command: "-A",
90 Chain: "Chaos_Chain",
91 JumpTarget: "Chaos_Target",
92 Protocol: "tcp",
93 MatchExtension: "multiport",
94 SPorts: "2021,2022",
95 TcpFlags: "SYN",
96 }
97 path, args, err := Marshal(n)
98 assert.NoError(t, err, "nil")
99 assert.Equal(t, "iptables -A Chaos_Chain -j Chaos_Target --protocol tcp -m multiport --source-ports 2021,2022 --tcp-flags SYN",
100 path+" "+strings.Join(args, " "))
101
102 p := TestInvalidParaType{
103 Exec: NewExec(),
104 P: 2,
105 }
106 _, _, err = Marshal(p)
107 assert.EqualError(t, err, "invalid parameter type int : parameter must be string or string slice")
108 ps := TestInvalidParaSliceType{
109 Exec: NewExec(),
110 P: nil,
111 }
112 _, _, err = Marshal(ps)
113 assert.EqualError(t, err, "invalid parameter slice type <[]int Value> :parameter slice must be string slice")
114 }
115