github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/drivers/shared/hostnames/mount_unix_test.go (about) 1 //go:build !windows 2 // +build !windows 3 4 package hostnames 5 6 import ( 7 "io/ioutil" 8 "path/filepath" 9 "testing" 10 11 "github.com/hashicorp/nomad/plugins/drivers" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestGenerateEtcHostsMount(t *testing.T) { 16 17 testCases := []struct { 18 name string 19 spec *drivers.NetworkIsolationSpec 20 extraHosts []string 21 expected []string 22 expectedErr string 23 }{ 24 { 25 name: "no-spec", 26 }, 27 { 28 name: "no-hosts-config", 29 spec: &drivers.NetworkIsolationSpec{Mode: drivers.NetIsolationModeGroup}, 30 }, 31 { 32 name: "base-case", 33 spec: &drivers.NetworkIsolationSpec{ 34 Mode: drivers.NetIsolationModeGroup, 35 HostsConfig: &drivers.HostsConfig{ 36 Address: "192.168.1.1", 37 Hostname: "xyzzy", 38 }, 39 }, 40 expected: []string{ 41 "192.168.1.1 xyzzy", 42 }, 43 }, 44 { 45 name: "with-valid-extra-hosts", 46 spec: &drivers.NetworkIsolationSpec{ 47 Mode: drivers.NetIsolationModeGroup, 48 HostsConfig: &drivers.HostsConfig{ 49 Address: "192.168.1.1", 50 Hostname: "xyzzy", 51 }, 52 }, 53 extraHosts: []string{ 54 "apple:192.168.1.2", 55 "banana:2001:0db8:85a3:0000:0000:8a2e:0370:7334", 56 }, 57 expected: []string{ 58 "192.168.1.1 xyzzy", 59 "192.168.1.2 apple", 60 "2001:0db8:85a3:0000:0000:8a2e:0370:7334 banana", 61 }, 62 }, 63 { 64 name: "invalid-extra-hosts-syntax", 65 spec: &drivers.NetworkIsolationSpec{ 66 Mode: drivers.NetIsolationModeGroup, 67 HostsConfig: &drivers.HostsConfig{ 68 Address: "192.168.1.1", 69 Hostname: "xyzzy", 70 }, 71 }, 72 extraHosts: []string{"apple192.168.1.2"}, 73 expectedErr: "invalid hosts entry \"apple192.168.1.2\"", 74 }, 75 { 76 name: "invalid-extra-hosts-bad-ip", 77 spec: &drivers.NetworkIsolationSpec{ 78 Mode: drivers.NetIsolationModeGroup, 79 HostsConfig: &drivers.HostsConfig{ 80 Address: "192.168.1.1", 81 Hostname: "xyzzy", 82 }, 83 }, 84 extraHosts: []string{"apple:192.168.1.256"}, 85 expectedErr: "invalid IP address \"apple:192.168.1.256\"", 86 }, 87 } 88 for _, tc := range testCases { 89 tc := tc 90 t.Run(tc.name, func(t *testing.T) { 91 require := require.New(t) 92 93 taskDir := t.TempDir() 94 dest := filepath.Join(taskDir, "hosts") 95 96 got, err := GenerateEtcHostsMount(taskDir, tc.spec, tc.extraHosts) 97 98 if tc.expectedErr != "" { 99 require.EqualError(err, tc.expectedErr) 100 } else { 101 require.NoError(err) 102 } 103 if len(tc.expected) == 0 { 104 require.Nil(got) 105 } else { 106 require.NotNil(got) 107 require.FileExists(dest) 108 tmpHosts, err := ioutil.ReadFile(dest) 109 require.NoError(err) 110 for _, line := range tc.expected { 111 require.Contains(string(tmpHosts), line) 112 } 113 } 114 }) 115 } 116 }