Debian Codegraph @

neutron_fwaas/tests/unit/privileged/test_utils.py

raw symbols SCIP
1 # Copyright (c) 2017 Thales Services SAS
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 from unittest import mock
17
18 import testtools
19
20 from neutron_fwaas.privileged import utils
21 from neutron_fwaas.tests import base
22
23
24 class InNamespaceTest(base.BaseTestCase):
25 ORG_NETNS_FD = 124
26 NEW_NETNS_FD = 421
27 NEW_NETNS = 'newns'
28
29 def setUp(self):
30 super().setUp()
31
32 # NOTE(cby): we should unmock os.open/close as early as possible
33 # because there are used in cleanups
34 open_patch = mock.patch('os.open', return_value=self.ORG_NETNS_FD)
35 self.open_mock = open_patch.start()
36 self.addCleanup(open_patch.stop)
37
38 close_patch = mock.patch('os.close')
39 self.close_mock = close_patch.start()
40 self.addCleanup(close_patch.stop)
41
42 self.setns_mock = mock.patch(
43 'pyroute2.netns.setns').start()
44
45 def test_in_namespace(self):
46 with utils.in_namespace(self.NEW_NETNS):
47 self.setns_mock.assert_called_once_with(self.NEW_NETNS)
48
49 setns_calls = [mock.call(self.NEW_NETNS), mock.call(self.ORG_NETNS_FD)]
50 self.setns_mock.assert_has_calls(setns_calls)
51
52 def test_in_no_namespace(self):
53 for namespace in ('', None):
54 with utils.in_namespace(namespace):
55 pass
56 self.setns_mock.assert_not_called()
57 self.close_mock.assert_not_called()
58
59 def test_in_namespace_failed(self):
60 with testtools.ExpectedException(ValueError):
61 with utils.in_namespace(self.NEW_NETNS):
62 self.setns_mock.assert_called_once_with(self.NEW_NETNS)
63 raise ValueError
64
65 setns_calls = [mock.call(self.NEW_NETNS), mock.call(self.ORG_NETNS_FD)]
66 self.setns_mock.assert_has_calls(setns_calls)
67
68 def test_in_namespace_enter_failed(self):
69 self.setns_mock.side_effect = ValueError
70 with testtools.ExpectedException(ValueError):
71 with utils.in_namespace(self.NEW_NETNS):
72 self.fail('It should fail before we reach this code')
73
74 self.setns_mock.assert_called_once_with(self.NEW_NETNS)
75
76 def test_in_namespace_exit_failed(self):
77 self.setns_mock.side_effect = [self.NEW_NETNS_FD, ValueError]
78 with testtools.ExpectedException(utils.BackInNamespaceExit):
79 with utils.in_namespace(self.NEW_NETNS):
80 pass