| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 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 |
|
| 33 |
|
| 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 |