github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/client/allocrunner/network_hook_test.go (about) 1 package allocrunner 2 3 import ( 4 "testing" 5 6 "github.com/hashicorp/nomad/client/allocrunner/interfaces" 7 "github.com/hashicorp/nomad/helper/testlog" 8 "github.com/hashicorp/nomad/nomad/mock" 9 "github.com/hashicorp/nomad/nomad/structs" 10 "github.com/hashicorp/nomad/plugins/drivers" 11 "github.com/hashicorp/nomad/plugins/drivers/testutils" 12 "github.com/stretchr/testify/require" 13 ) 14 15 // statically assert network hook implements the expected interfaces 16 var _ interfaces.RunnerPrerunHook = (*networkHook)(nil) 17 var _ interfaces.RunnerPostrunHook = (*networkHook)(nil) 18 19 type mockNetworkIsolationSetter struct { 20 t *testing.T 21 expectedSpec *drivers.NetworkIsolationSpec 22 called bool 23 } 24 25 func (m *mockNetworkIsolationSetter) SetNetworkIsolation(spec *drivers.NetworkIsolationSpec) { 26 m.called = true 27 require.Exactly(m.t, m.expectedSpec, spec) 28 } 29 30 // Test that the prerun and postrun hooks call the setter with the expected spec when 31 // the network mode is not host 32 func TestNetworkHook_Prerun_Postrun(t *testing.T) { 33 alloc := mock.Alloc() 34 alloc.Job.TaskGroups[0].Networks = []*structs.NetworkResource{ 35 { 36 Mode: "bridge", 37 }, 38 } 39 spec := &drivers.NetworkIsolationSpec{ 40 Mode: drivers.NetIsolationModeGroup, 41 Path: "test", 42 Labels: map[string]string{"abc": "123"}, 43 } 44 45 destroyCalled := false 46 nm := &testutils.MockDriver{ 47 MockNetworkManager: testutils.MockNetworkManager{ 48 CreateNetworkF: func(allocID string) (*drivers.NetworkIsolationSpec, bool, error) { 49 require.Equal(t, alloc.ID, allocID) 50 return spec, false, nil 51 }, 52 53 DestroyNetworkF: func(allocID string, netSpec *drivers.NetworkIsolationSpec) error { 54 destroyCalled = true 55 require.Equal(t, alloc.ID, allocID) 56 require.Exactly(t, spec, netSpec) 57 return nil 58 }, 59 }, 60 } 61 setter := &mockNetworkIsolationSetter{ 62 t: t, 63 expectedSpec: spec, 64 } 65 require := require.New(t) 66 67 logger := testlog.HCLogger(t) 68 hook := newNetworkHook(logger, setter, alloc, nm, &hostNetworkConfigurator{}) 69 require.NoError(hook.Prerun()) 70 require.True(setter.called) 71 require.False(destroyCalled) 72 require.NoError(hook.Postrun()) 73 require.True(destroyCalled) 74 75 // reset and use host network mode 76 setter.called = false 77 destroyCalled = false 78 alloc.Job.TaskGroups[0].Networks[0].Mode = "host" 79 hook = newNetworkHook(logger, setter, alloc, nm, &hostNetworkConfigurator{}) 80 require.NoError(hook.Prerun()) 81 require.False(setter.called) 82 require.False(destroyCalled) 83 require.NoError(hook.Postrun()) 84 require.False(destroyCalled) 85 86 }