nova/nova/tests/unit/privsep/test_utils.py
Stephen Finucane 89ef050b8c Use unittest.mock instead of third party mock
Now that we no longer support py27, we can use the standard library
unittest.mock module instead of the third party mock lib. Most of this
is autogenerated, as described below, but there is one manual change
necessary:

nova/tests/functional/regressions/test_bug_1781286.py
  We need to avoid using 'fixtures.MockPatch' since fixtures is using
  'mock' (the library) under the hood and a call to 'mock.patch.stop'
  found in that test will now "stop" mocks from the wrong library. We
  have discussed making this configurable but the option proposed isn't
  that pretty [1] so this is better.

The remainder was auto-generated with the following (hacky) script, with
one or two manual tweaks after the fact:

  import glob

  for path in glob.glob('nova/tests/**/*.py', recursive=True):
      with open(path) as fh:
          lines = fh.readlines()
      if 'import mock\n' not in lines:
          continue
      import_group_found = False
      create_first_party_group = False
      for num, line in enumerate(lines):
          line = line.strip()
          if line.startswith('import ') or line.startswith('from '):
              tokens = line.split()
              for lib in (
                  'ddt', 'six', 'webob', 'fixtures', 'testtools'
                  'neutron', 'cinder', 'ironic', 'keystone', 'oslo',
              ):
                  if lib in tokens[1]:
                      create_first_party_group = True
                      break
              if create_first_party_group:
                  break
              import_group_found = True
          if not import_group_found:
              continue
          if line.startswith('import ') or line.startswith('from '):
              tokens = line.split()
              if tokens[1] > 'unittest':
                  break
              elif tokens[1] == 'unittest' and (
                  len(tokens) == 2 or tokens[4] > 'mock'
              ):
                  break
          elif not line:
              break
      if create_first_party_group:
          lines.insert(num, 'from unittest import mock\n\n')
      else:
          lines.insert(num, 'from unittest import mock\n')
      del lines[lines.index('import mock\n')]
      with open(path, 'w+') as fh:
          fh.writelines(lines)

Note that we cannot remove mock from our requirements files yet due to
importing pypowervm unit test code in nova unit tests. This library
still uses the mock lib, and since we are importing test code and that
lib (correctly) only declares mock in its test-requirements.txt, mock
would not otherwise be installed and would cause errors while loading
nova unit test code.

[1] https://github.com/testing-cabal/fixtures/pull/49

Change-Id: Id5b04cf2f6ca24af8e366d23f15cf0e5cac8e1cc
Signed-off-by: Stephen Finucane <stephenfin@redhat.com>
2022-08-01 17:46:26 +02:00

128 lines
5.3 KiB
Python

# Copyright 2011 Justin Santa Barbara
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import errno
import os
from unittest import mock
import nova.privsep.utils
from nova import test
class SupportDirectIOTestCase(test.NoDBTestCase):
def setUp(self):
super(SupportDirectIOTestCase, self).setUp()
# O_DIRECT is not supported on all Python runtimes, so on platforms
# where it's not supported (e.g. Mac), we can still test the code-path
# by stubbing out the value.
if not hasattr(os, 'O_DIRECT'):
# `mock` seems to have trouble stubbing an attr that doesn't
# originally exist, so falling back to stubbing out the attribute
# directly.
os.O_DIRECT = 16384
self.addCleanup(delattr, os, 'O_DIRECT')
self.einval = OSError()
self.einval.errno = errno.EINVAL
self.enoent = OSError()
self.enoent.errno = errno.ENOENT
self.test_path = os.path.join('.', '.directio.test.123')
self.io_flags = os.O_CREAT | os.O_WRONLY | os.O_DIRECT
open_patcher = mock.patch('os.open')
write_patcher = mock.patch('os.write')
close_patcher = mock.patch('os.close')
unlink_patcher = mock.patch('os.unlink')
random_string_patcher = mock.patch(
'nova.privsep.utils.generate_random_string', return_value='123')
self.addCleanup(open_patcher.stop)
self.addCleanup(write_patcher.stop)
self.addCleanup(close_patcher.stop)
self.addCleanup(unlink_patcher.stop)
self.addCleanup(random_string_patcher.stop)
self.mock_open = open_patcher.start()
self.mock_write = write_patcher.start()
self.mock_close = close_patcher.start()
self.mock_unlink = unlink_patcher.start()
random_string_patcher.start()
def test_supports_direct_io(self):
self.mock_open.return_value = 3
self.assertTrue(nova.privsep.utils.supports_direct_io('.'))
self.mock_open.assert_called_once_with(self.test_path, self.io_flags)
self.mock_write.assert_called_once_with(3, mock.ANY)
# ensure unlink(filepath) will actually remove the file by deleting
# the remaining link to it in close(fd)
self.mock_close.assert_called_once_with(3)
self.mock_unlink.assert_called_once_with(self.test_path)
def test_supports_direct_io_with_exception_in_write(self):
self.mock_open.return_value = 3
self.mock_write.side_effect = ValueError()
self.assertRaises(ValueError, nova.privsep.utils.supports_direct_io,
'.')
self.mock_open.assert_called_once_with(self.test_path, self.io_flags)
self.mock_write.assert_called_once_with(3, mock.ANY)
# ensure unlink(filepath) will actually remove the file by deleting
# the remaining link to it in close(fd)
self.mock_close.assert_called_once_with(3)
self.mock_unlink.assert_called_once_with(self.test_path)
def test_supports_direct_io_with_exception_in_open(self):
self.mock_open.side_effect = ValueError()
self.assertRaises(ValueError, nova.privsep.utils.supports_direct_io,
'.')
self.mock_open.assert_called_once_with(self.test_path, self.io_flags)
self.mock_write.assert_not_called()
self.mock_close.assert_not_called()
self.mock_unlink.assert_called_once_with(self.test_path)
def test_supports_direct_io_with_oserror_in_write(self):
self.mock_open.return_value = 3
self.mock_write.side_effect = self.einval
self.assertFalse(nova.privsep.utils.supports_direct_io('.'))
self.mock_open.assert_called_once_with(self.test_path, self.io_flags)
self.mock_write.assert_called_once_with(3, mock.ANY)
# ensure unlink(filepath) will actually remove the file by deleting
# the remaining link to it in close(fd)
self.mock_close.assert_called_once_with(3)
self.mock_unlink.assert_called_once_with(self.test_path)
def test_supports_direct_io_with_oserror_in_open_einval(self):
self.mock_open.side_effect = self.einval
self.assertFalse(nova.privsep.utils.supports_direct_io('.'))
self.mock_open.assert_called_once_with(self.test_path, self.io_flags)
self.mock_write.assert_not_called()
self.mock_close.assert_not_called()
self.mock_unlink.assert_called_once_with(self.test_path)
def test_supports_direct_io_with_oserror_in_open_enoent(self):
self.mock_open.side_effect = self.enoent
self.assertFalse(nova.privsep.utils.supports_direct_io('.'))
self.mock_open.assert_called_once_with(self.test_path, self.io_flags)
self.mock_write.assert_not_called()
self.mock_close.assert_not_called()
self.mock_unlink.assert_called_once_with(self.test_path)