Esempio n. 1
0
 def _get_connection_mock(self, dvs_name):
     return mock.Mock(vim=self.vim)
Esempio n. 2
0
 def test_working_locale(self):
     environ = {'LANG': 'en_GB.UTF-8'}
     self.patch(os, 'environ', environ)
     config = mock.Mock()
     util.check_functional_environment(config)
     self.assertEqual(config.error.called, False)
Esempio n. 3
0
class TestLibrary(unittest.TestCase):
    """Unit test for the ``library`` submodule."""

    def setUp(self):
        """Called before each test.

        Performs setup.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance

        Returns:
          ``None``
        """
        assertRaisesRegexp = getattr(self, 'assertRaisesRegexp', None)
        self.assertRaisesRegexp = getattr(self, 'assertRaisesRegex', assertRaisesRegexp)
        self.lib_path = '/'

    def tearDown(self):
        """Called after each test.

        Performs teardown.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance

        Returns:
          ``None``
        """
        pass

    def mock_directories(self, mock_os, structure, sep):
        """Mocks a directory structure.

        This function is used to mock a directory structure, so that checking
        if something is a file, is a directory, or listing directories will use
        our mocked structure instead.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): the mocked ``os`` module
          structure (list): a list of directories or files
          sep (str): the operating system seperator

        Returns:
          ``None``
        """
        def isfile(f):
            """Returns whether the file exists in the structure."""
            if not any(s.endswith(f) for s in structure):
                return False
            return '.' in f.split(sep)[-1]

        mock_os.path.isfile.side_effect = isfile

        def isdir(f):
            """Returns whether the directory exists within the structure."""
            if not any(s.startswith(f) for s in structure):
                return False
            return not isfile(f)

        mock_os.path.isdir.side_effect = isdir

        def join(*args):
            """Joins several strings to form a path."""
            s = ''
            for arg in args:
                if not s.endswith(sep) and len(s) > 0:
                    s += sep
                s += arg
            return s

        mock_os.path.join.side_effect = join

        def listdir(f):
            """List the files and directories within the directory."""
            if not isdir(f):
                return list()

            directories = []
            for s in structure:
                if s.startswith(f):
                    s = s[len(f):]
                    if s.startswith(sep):
                        s = s[len(sep):]
                    directories.append(s.split(sep)[0])
            return directories

        mock_os.listdir.side_effect = listdir

        def mock_walk(b):
            r = list()
            dirname = b
            if not isdir(dirname):
                return []

            subdirs = filter(len, list(set([d for d in listdir(dirname) if isdir(join(dirname, d))])))
            subfiles = filter(len, list(set([f for f in listdir(dirname) if isfile(join(dirname, f))])))
            r.append((dirname, subdirs, subfiles))
            for subdir in subdirs:
                r.extend(mock_walk(join(dirname, subdir)))

            return r

        mock_os.walk.return_value = mock_walk(sep)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    def test_initialize_default(self, mock_load_library, mock_find_library, mock_open):
        """Tests creating a library and finding the default DLL.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): mock for mocking the
            ``ctypes.util.find_library()`` call
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = self.lib_path

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        mock_open.assert_called_with(self.lib_path, 'rb')
        mock_load_library.assert_called_once()

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('os.path.isdir')
    def test_initialiaze_no(self, mock_isdir, mock_load_library, mock_find_library, mock_open):
        """Tests creating a library when the default DLL does not exist.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_isdir (Mock): mock for mocking the call to ``os.path.isdir``
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): mock for mocking the
            ``ctypes.util.find_library()`` call
          mock_open (Mock): mock for mocking the clal to ``open()``

        Returns:
          ``None``
        """
        mock_isdir.return_value = False
        mock_find_library.return_value = None

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(0, mock_load_library.call_count)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    def test_initialize_with_path(self, mock_load_library, mock_find_library, mock_open):
        """Tests creating a library when passing in a DLL path.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): mock for mocking the
            ``ctypes.util.find_library()`` call
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None

        lib = library.Library(self.lib_path)
        lib.unload = mock.Mock()

        self.assertEqual(0, mock_find_library.call_count)

        mock_open.assert_called_with(self.lib_path, 'rb')
        mock_load_library.assert_called_once()

    @mock.patch('sys.platform', new='windows')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('pylink.library.ctypes')
    def test_initialize_windows(self, mock_ctypes, mock_find_library, mock_open):
        """Tests creating a library on a Windows machine.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_ctypes (Mock): a mocked version of the ctypes library
          mock_find_library (Mock): mock for mocking the
            ``ctypes.util.find_library()`` call
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_windll = mock.Mock()
        mock_windll.__getitem__ = mock.Mock()

        mock_cdll = mock.Mock()
        mock_cdll.__getitem__ = mock.Mock()

        mock_ctypes.windll = mock_windll
        mock_ctypes.cdll = mock_cdll
        mock_find_library.return_value = self.lib_path

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.WINDOWS_JLINK_SDK_NAME)
        mock_open.assert_called_with(self.lib_path, 'rb')
        mock_cdll.LoadLibrary.assert_called_once()
        mock_windll.LoadLibrary.assert_called_once()

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    def test_load(self, mock_load_library, mock_find_library, mock_open):
        """Tests that we can pass in a path to a DLL to load.

        If the path is valid, loads the given ``DLL``, otherwise stays the
        same.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): mock for mocking the
            ``ctypes.util.find_library()`` call
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = self.lib_path

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)

        mock_open.assert_called_with(self.lib_path, 'rb')
        self.assertEqual(1, mock_load_library.call_count)

        new_path = '\\'
        lib.load(new_path)

        mock_open.assert_called_with(new_path, 'rb')
        self.assertEqual(2, mock_load_library.call_count)

        lib.load(None)
        mock_open.assert_called_with(new_path, 'rb')
        self.assertEqual(3, mock_load_library.call_count)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('pylink.library.open', new=mock.MagicMock())
    @mock.patch('pylink.library.ctypes')
    @mock.patch('os.remove')
    def test_unload_no_library(self, mock_remove, mock_ctypes):
        """Tests unloading the library when no DLL is loaded.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_remove (Mock): the mocked call to ``os.remove()``
          mock_ctypes (Mock): mocked ``ctypes`` module

        Returns:
          ``None``
        """
        lib = library.Library('')
        setattr(lib, '_lib', None)
        setattr(lib, '_temp', None)

        self.assertFalse(lib.unload())

        mock_remove.assert_not_called()

    @mock.patch('sys.platform', new='windows')
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('pylink.library.open', new=mock.MagicMock())
    @mock.patch('pylink.library.ctypes')
    @mock.patch('os.remove')
    def test_unload_windows(self, mock_remove, mock_ctypes):
        """Tests unloading the library on Windows.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_remove (Mock): the mocked call to ``os.remove()``
          mock_ctypes (Mock): mocked ``ctypes`` module

        Returns:
          ``None``
        """
        lib = library.Library('')

        self.assertTrue(lib.unload())

        self.assertEqual(2, mock_ctypes.windll.kernel32.FreeLibrary.call_count)

        mock_remove.assert_called_once()

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('pylink.library.open', new=mock.MagicMock())
    @mock.patch('pylink.library.ctypes')
    @mock.patch('os.remove')
    def test_unload_darwin_linux(self, mock_remove, mock_ctypes):
        """Tests unloading the library on Darwin and Linux platforms.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_remove (Mock): the mocked call to ``os.remove()``
          mock_ctypes (Mock): mocked ``ctypes`` module

        Returns:
          ``None``
        """
        lib = library.Library('')

        self.assertTrue(lib.unload())

        mock_remove.assert_called_once()

        self.assertEqual(None, lib._lib)
        self.assertEqual(None, lib._temp)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    def test_dll_getter(self, mock_load_library, mock_find_library, mock_open):
        """Tests that the ``.dll()`` getter returns the set ``DLL``.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): mock for mocking the
            ``ctypes.util.find_library()`` call
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = self.lib_path
        mock_load_library.return_value = 0xDEADBEEF

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)

        mock_open.assert_called_with(self.lib_path, 'rb')
        mock_load_library.assert_called_once()

        self.assertEqual(0xDEADBEEF, lib.dll())

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_darwin_4_98_e(self, mock_os, mock_load_library, mock_find_library, mock_open):
        """Tests finding the DLL on Darwin through the SEGGER application for V4.98E-.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/Applications/SEGGER/JLink 1/libjlinkarm.dylib'
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_load_library.call_count)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_darwin_5_0_0(self, mock_os, mock_load_library, mock_find_library, mock_open):
        """Tests finding the DLL on Darwin through the SEGGER application for V5.0.0+.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/Applications/SEGGER/JLink/libjlinkarm.5.12.10.dylib',
            '/Applications/SEGGER/JLink/libjlinkarm.5.dylib'
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_load_library.call_count)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_darwin_6_0_0(self, mock_os, mock_load_library, mock_find_library, mock_open):
        """Tests finding the DLL on Darwin through the SEGGER application for V6.0.0+.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/Applications/SEGGER/JLink/libjlinkarm.dylib'
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_load_library.call_count)

    @mock.patch('sys.platform', new='darwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_darwin_empty(self, mock_os, mock_load_library, mock_find_library, mock_open):
        """Tests finding the DLL on Darwin through the SEGGER application for V6.0.0+.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/Applications/SEGGER/JLink/'
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(0, mock_load_library.call_count)

    @mock.patch('sys.platform', new='windows')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('pylink.library.ctypes')
    @mock.patch('pylink.library.os')
    def test_windows_4_98_e(self, mock_os, mock_ctypes, mock_find_library, mock_open):
        """Tests finding the DLL on Windows through the SEGGER application for V4.98E-.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_ctypes (Mock): a mocked version of the ctypes library
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_windll = mock.Mock()
        mock_windll.__getitem__ = mock.Mock()

        mock_cdll = mock.Mock()
        mock_cdll.__getitem__ = mock.Mock()

        mock_ctypes.windll = mock_windll
        mock_ctypes.cdll = mock_cdll
        mock_find_library.return_value = None

        directories = [
            'C:\\Program Files\\SEGGER\\JLink_V49e\\JLinkARM.dll'
        ]

        self.mock_directories(mock_os, directories, '\\')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.WINDOWS_JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_windll.LoadLibrary.call_count)
        self.assertEqual(1, mock_cdll.LoadLibrary.call_count)

    @mock.patch('sys.platform', new='windows')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('pylink.library.ctypes')
    @mock.patch('pylink.library.os')
    def test_windows_5_10_0(self, mock_os, mock_ctypes, mock_find_library, mock_open):
        """Tests finding the DLL on Windows through the SEGGER application for V5.0.0+.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_ctypes (Mock): a mocked version of the ctypes library
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_windll = mock.Mock()
        mock_windll.__getitem__ = mock.Mock()

        mock_cdll = mock.Mock()
        mock_cdll.__getitem__ = mock.Mock()

        mock_ctypes.windll = mock_windll
        mock_ctypes.cdll = mock_cdll
        mock_find_library.return_value = None

        directories = [
            'C:\\Program Files (x86)\\SEGGER\\JLink_V510l\\JLinkARM.dll'
        ]

        self.mock_directories(mock_os, directories, '\\')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.WINDOWS_JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_windll.LoadLibrary.call_count)
        self.assertEqual(1, mock_cdll.LoadLibrary.call_count)

    @mock.patch('sys.platform', new='windows')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('pylink.library.ctypes')
    @mock.patch('pylink.library.os')
    def test_windows_jlinkarm(self, mock_os, mock_ctypes, mock_find_library, mock_open):
        """Tests finding the DLL on Windows through the SEGGER JLinkARM folder.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_ctypes (Mock): a mocked version of the ctypes library
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_windll = mock.Mock()
        mock_windll.__getitem__ = mock.Mock()

        mock_cdll = mock.Mock()
        mock_cdll.__getitem__ = mock.Mock()

        mock_ctypes.windll = mock_windll
        mock_ctypes.cdll = mock_cdll
        mock_find_library.return_value = None

        directories = [
            'C:\\Program Files (x86)\\SEGGER\\JLinkARM\\JLinkARM.dll'
        ]

        self.mock_directories(mock_os, directories, '\\')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.WINDOWS_JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_windll.LoadLibrary.call_count)
        self.assertEqual(1, mock_cdll.LoadLibrary.call_count)

    @mock.patch('sys.platform', new='windows')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('pylink.library.ctypes')
    @mock.patch('pylink.library.os')
    def test_windows_empty(self, mock_os, mock_ctypes, mock_find_library, mock_open):
        """Tests finding the DLL on Windows through the SEGGER application for V6.0.0+.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_ctypes (Mock): a mocked version of the ctypes library
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open``

        Returns:
          ``None``
        """
        mock_windll = mock.Mock()
        mock_windll.__getitem__ = mock.Mock()

        mock_cdll = mock.Mock()
        mock_cdll.__getitem__ = mock.Mock()

        mock_ctypes.windll = mock_windll
        mock_ctypes.cdll = mock_cdll
        mock_find_library.return_value = None

        directories = [
            'C:\\Program Files\\',
            'C:\\Program Files (x86)\\'
        ]

        self.mock_directories(mock_os, directories, '\\')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.WINDOWS_JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(0, mock_windll.LoadLibrary.call_count)
        self.assertEqual(0, mock_cdll.LoadLibrary.call_count)

    @mock.patch('sys.platform', new='cygwin')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_cygwin(self, mock_os, mock_load_library, mock_find_library, mock_open):
        """Tests finding the DLL when running within Cygwin.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None

        directories = [
            'C:\\Program Files (x86)\\SEGGER\\JLinkARM\\JLinkARM.dll',
            'C:\\Program Files (x86)\\SEGGER\\JLink_V500l\\JLinkARM.dll'
        ]

        self.mock_directories(mock_os, directories, '\\')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.WINDOWS_JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(1, mock_load_library.call_count)

    @mock.patch('sys.platform', new='linux')
    @mock.patch('pylink.util.is_os_64bit', return_value=False)
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_linux_4_98_e(self, mock_os, mock_load_library, mock_find_library, mock_open, mock_is_os_64bit):
        """Tests finding the DLL on Linux through the SEGGER application for V4.98E-.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/opt/SEGGER/JLink_Linux_V498e_i386/libjlinkarm.so',
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()
        load_library_args, load_libary_kwargs = mock_load_library.call_args
        self.assertEqual(directories[0], lib._path)

    @mock.patch('sys.platform', new='linux2')
    @mock.patch('pylink.util.is_os_64bit', return_value=False)
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_linux_6_10_0_32bit(self, mock_os, mock_load_library, mock_find_library, mock_open, mock_is_os_64bit):
        """Tests finding the DLL on Linux through the SEGGER application for V6.0.0+ on 32 bit linux.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``
          mock_is_os_64bit (Mock): mock for mocking the call to ``is_os_64bit``, returns False

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/opt/SEGGER/JLink_Linux_V610d_x86_64/libjlinkarm_x86.so.6.10',
            '/opt/SEGGER/JLink_Linux_V610d_x86_64/libjlinkarm.so.6.10',
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()
        load_library_args, load_libary_kwargs = mock_load_library.call_args
        self.assertEqual(directories[0], lib._path)

        directories = [
            '/opt/SEGGER/JLink_Linux_V610d_x86_64/libjlinkarm.so.6.10',
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()
        load_library_args, load_libary_kwargs = mock_load_library.call_args
        self.assertEqual(None, lib._path)

    @mock.patch('sys.platform', new='linux2')
    @mock.patch('pylink.util.is_os_64bit', return_value=True)
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_linux_6_10_0_64bit(self, mock_os, mock_load_library, mock_find_library, mock_open, mock_is_os_64bit):
        """Tests finding the DLL on Linux through the SEGGER application for V6.0.0+ on 64 bit linux.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``
          mock_is_os_64bit (Mock): mock for mocking the call to ``is_os_64bit``, returns True

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = [
            '/opt/SEGGER/JLink_Linux_V610d_x86_64/libjlinkarm_x86.so.6.10',
            '/opt/SEGGER/JLink_Linux_V610d_x86_64/libjlinkarm.so.6.10',
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()
        load_library_args, load_libary_kwargs = mock_load_library.call_args
        self.assertEqual(directories[1], lib._path)

        directories = [
            '/opt/SEGGER/JLink_Linux_V610d_x86_64/libjlinkarm_x86.so.6.10',
        ]

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()
        self.assertEqual(None, lib._path)

    @mock.patch('sys.platform', new='linux')
    @mock.patch('pylink.library.open')
    @mock.patch('os.remove', new=mock.Mock())
    @mock.patch('tempfile.NamedTemporaryFile', new=mock.Mock())
    @mock.patch('ctypes.util.find_library')
    @mock.patch('ctypes.cdll.LoadLibrary')
    @mock.patch('pylink.library.os')
    def test_linux_empty(self, mock_os, mock_load_library, mock_find_library, mock_open):
        """Tests finding the DLL on Linux through the SEGGER application for V6.0.0+.

        Args:
          self (TestLibrary): the ``TestLibrary`` instance
          mock_os (Mock): a mocked version of the ``os`` module
          mock_load_library (Mock): a mocked version of the library loader
          mock_find_library (Mock): a mocked call to ``ctypes`` find library
          mock_open (Mock): mock for mocking the call to ``open()``

        Returns:
          ``None``
        """
        mock_find_library.return_value = None
        directories = []

        self.mock_directories(mock_os, directories, '/')

        lib = library.Library()
        lib.unload = mock.Mock()

        mock_find_library.assert_called_once_with(library.Library.JLINK_SDK_NAME)
        self.assertEqual(1, mock_find_library.call_count)
        self.assertEqual(0, mock_load_library.call_count)
Esempio n. 4
0
    def test_wait_for_task(self):
        # Create some fake task outputs
        mocked_instance = mock.MagicMock(name='mocked_instance')
        mocked_instance.soul = {'name': 'fake_instance'}

        queued = mock.MagicMock(name='mock_output_queued')
        queued.soul = {'name': 'fake_task',
                       'summary': 'queued: still going'}

        success = mock.MagicMock(name='mock_output_success')
        success.soul = {'name': 'fake_task',
                        'summary': 'success: done'}

        completed = mock.MagicMock(name='mock_output_completed')
        completed.soul = {'name': 'fake_task',
                          'summary': 'completed: done'}

        failed = mock.MagicMock(name='mock_output_failed')
        failed.soul = {'name': 'fake_task',
                       'summary': 'failed: crap'}

        in_process = mock.MagicMock(name='mock_output_in_process')
        in_process.soul = {'name': 'fake_task',
                           'summary': '30%: in process'}

        unknown = mock.MagicMock(name='mock_output_unknown')
        unknown.soul = {'name': 'fake_task',
                        'summary': 'unknown return'}

        self.client.get_audit_logs = helper.mock_tornado([])
        # task succeeds
        mock_task = mock.MagicMock(name='fake task')
        mock_task.self.show.side_effect = [queued, in_process, success]
        mock_logger = mock.Mock()
        repeat_patcher = mock.patch.object(api.utils,
                                           'create_repeating_log')
        with repeat_patcher as repeat_mock:
            ret = yield self.client.wait_for_task(
                mock_task, task_name='ut-fake-task',
                sleep=0.01, loc_log=mock_logger)
        self.assertEquals(ret, True)
        mock_task.assert_has_calls(
            [mock.call.self.show(), mock.call.self.show(),
             mock.call.self.show()])

        repeat_mock.assert_called_with(
            mock_logger.info,
            'Still waiting on ut-fake-task',
            seconds=0.01)

        # task completed
        mock_task = mock.MagicMock(name='fake task')
        mock_task.self.show.side_effect = [queued, in_process, completed]
        ret = yield self.client.wait_for_task(mock_task, sleep=0.01)
        self.assertEquals(ret, True)
        mock_task.assert_has_calls(
            [mock.call.self.show(), mock.call.self.show(),
             mock.call.self.show()])

        # task fails (no instance)
        mock_task = mock.MagicMock(name='fake task')
        mock_task.self.show.side_effect = [queued, in_process, failed]
        ret = yield self.client.wait_for_task(mock_task, sleep=0.01)
        self.assertEquals(ret, False)

        # task fails
        mock_task = mock.MagicMock(name='fake task')
        mock_task.self.show.side_effect = [queued, in_process, failed]
        ret = yield self.client.wait_for_task(
            mock_task, sleep=0.01, instance=mocked_instance)
        self.assertEquals(ret, False)
        mock_task.assert_has_calls(
            [mock.call.self.show(), mock.call.self.show(),
             mock.call.self.show()])

        # task fails
        self.client.get_audit_logs = helper.mock_tornado(['log', 'log'])
        mock_task = mock.MagicMock(name='fake task')
        mock_task.self.show.side_effect = [queued, in_process, failed]
        ret = yield self.client.wait_for_task(
            mock_task, sleep=0.01, instance=mocked_instance)
        self.assertEquals(ret, False)
        mock_task.assert_has_calls(
            [mock.call.self.show(), mock.call.self.show(),
             mock.call.self.show()])

        # task is empty
        mock_task = None
        ret = yield self.client.wait_for_task(mock_task, sleep=0.01)
        self.assertEquals(ret, True)
Esempio n. 5
0
 def mock_config(self):
     self.mock(storage, 'get_config_hash', mock.Mock())
     self.mock(storage, 'get_config_by_hash', mock.Mock())
     storage.get_config_hash.return_value = 'deadbeef', 'abc0123'
     storage.get_config_by_hash.return_value = 'config text'
Esempio n. 6
0
 def setUp(self):
     super(ExclusiveLockDecoratorTestCase, self).setUp()
     self.task = mock.Mock(spec=task_manager.TaskManager)
     self.args_task_first = (self.task, 1, 2)
     self.args_task_second = (1, self.task, 2)
     self.kwargs = dict(cat='meow', dog='wuff')
 def __init__(self):
     super(NetworkSegmentRangeTestPlugin, self).__init__()
     self.type_manager = mock.Mock()
Esempio n. 8
0
 def _get_version(self, status):
     v = Version()
     v.all_files = [mock.Mock()]
     v.all_files[0].status = status
     return v
Esempio n. 9
0
 def test_setup_via_manager(self):
     self.assertIsNone(self._driver._setup_via_manager(mock.Mock()))
Esempio n. 10
0
class ZkTest(unittest.TestCase):
    """Mock test for treadmill.zk."""

    def setUp(self):
        os.environ['TREADMILL_MASTER_ROOT'] = '/'

    def test_sequence_watch(self):
        """Tests sequence watch."""
        events = []
        callback = lambda path, data, stat: events.append(path)
        watcher = zkutils.SequenceNodeWatch(kazoo.client.KazooClient(),
                                            callback,
                                            delim='-', pattern=None,
                                            include_data=False)

        # no delimieter, no events fired.
        for node in watcher.nodes(['aaa', 'bbb']):
            watcher.invoke_callback('/xxx', node)
        self.assertEqual(0, len(events))
        for node in watcher.nodes(['1-001', '1-002']):
            watcher.invoke_callback('/xxx', node)
        # events == [/001, /002] pop works from the end.
        self.assertEqual('/xxx/1-002', events.pop())
        self.assertEqual('/xxx/1-001', events.pop())

        # added new node, make sure only one event is called
        for node in watcher.nodes(['1-001', '1-002', '1-003']):
            watcher.invoke_callback('/xxx', node)
        self.assertEqual(1, len(events))
        self.assertEqual('/xxx/1-003', events.pop())

        # Check that order of children nodes does not matter, only seq number
        # counts.
        for node in watcher.nodes(['0-004', '1-003', '1-002', '0-001']):
            watcher.invoke_callback('/xxx', node)
        self.assertEqual(1, len(events))
        self.assertEqual('/xxx/0-004', events.pop())

        # Test that pattern is being filtered.
        watcher = zkutils.SequenceNodeWatch(kazoo.client.KazooClient(),
                                            callback, delim='-',
                                            pattern='foo',
                                            include_data=False)

        for node in watcher.nodes(['aaa', 'bbb', 'foo']):
            watcher.invoke_callback('/xxx', node)
        self.assertEqual(0, len(events))
        for node in watcher.nodes(['aaa', 'bbb', 'foo-1']):
            watcher.invoke_callback('/xxx', node)
        self.assertEqual(1, len(events))

    @mock.patch('kazoo.client.KazooClient.create', mock.Mock())
    def test_put(self):
        """Tests updating/creating node content."""
        client = kazoo.client.KazooClient()
        zkutils.put(client, '/foo/bar')
        kazoo.client.KazooClient.create.assert_called_with(
            '/foo/bar', b'', acl=mock.ANY, makepath=True,
            sequence=False, ephemeral=False)

    @mock.patch('kazoo.client.KazooClient.create', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.set', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.set_acls', mock.Mock())
    def test_put_existing(self):
        """Test update content of existing node."""
        def raise_exists(*args_unused, **kwargs_unused):
            """zk.create side effect, raising appropriate exception."""
            raise kazoo.client.NodeExistsError()

        client = kazoo.client.KazooClient()
        kazoo.client.KazooClient.create.side_effect = raise_exists
        zkutils.put(client, '/foo/bar')
        kazoo.client.KazooClient.set.assert_called_with('/foo/bar', b'')
        kazoo.client.KazooClient.set_acls.assert_called_with('/foo/bar',
                                                             mock.ANY)

    @mock.patch('kazoo.client.KazooClient.get', mock.Mock())
    def test_get(self):
        """Test zkutils.get parsing of YAML data."""
        client = kazoo.client.KazooClient()
        kazoo.client.KazooClient.get.return_value = ('{xxx: 123}', None)
        self.assertEqual({'xxx': 123}, zkutils.get(client, '/foo'))

        # parsing error
        kazoo.client.KazooClient.get.return_value = ('{xxx: 123', None)
        self.assertEqual('{xxx: 123', zkutils.get(client, '/foo',
                                                  strict=False))
        self.assertRaises(yaml.YAMLError, zkutils.get, client, '/foo')

        kazoo.client.KazooClient.get.return_value = (None, None)
        self.assertIsNone(zkutils.get(client, '/foo'))

    @mock.patch('kazoo.client.KazooClient.create', mock.Mock())
    def test_ensure_exists(self):
        """Tests updating/creating node content."""
        # with data
        client = kazoo.client.KazooClient()
        zkutils.ensure_exists(client, '/foo/bar', data='foo')
        kazoo.client.KazooClient.create.assert_called_with(
            '/foo/bar', b'foo', acl=mock.ANY, makepath=True,
            sequence=False)

        # non-data
        zkutils.ensure_exists(client, '/foo/bar')
        kazoo.client.KazooClient.create.assert_called_with(
            '/foo/bar', b'', acl=mock.ANY, makepath=True,
            sequence=False)

    @mock.patch('kazoo.client.KazooClient.set', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.create', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.set_acls', mock.Mock())
    def test_ensure_exists_existing(self):
        """Test update content of existing node."""
        def raise_exists(*args_unused, **kwargs_unused):
            """zk.create side effect, raising appropriate exception."""
            raise kazoo.client.NodeExistsError()

        client = kazoo.client.KazooClient()
        kazoo.client.KazooClient.create.side_effect = raise_exists
        zkutils.ensure_exists(client, '/foo/bar')
        kazoo.client.KazooClient.set_acls.assert_called_with('/foo/bar',
                                                             mock.ANY)

        # ensure with data
        zkutils.ensure_exists(client, '/foo/bar', data='foo')
        kazoo.client.KazooClient.set.assert_called_with('/foo/bar', b'foo')
        kazoo.client.KazooClient.set_acls.assert_called_with('/foo/bar',
                                                             mock.ANY)

    @mock.patch('kazoo.client.KazooClient.start', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.add_listener', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.exists',
                mock.Mock(return_value=False))
    @mock.patch('kazoo.client.KazooClient.create', mock.Mock())
    def test_connect_chroot(self):
        """Test connecting with chroot."""
        zkutils.connect('zookeeper://me@xxx:123,yyy:123,zzz:123/a/b/c')
        kazoo.client.KazooClient.create.assert_has_calls([
            mock.call('/a', '', makepath=True, acl=mock.ANY),
            mock.call('/a/b', '', makepath=True, acl=mock.ANY),
            mock.call('/a/b/c', '', makepath=True, acl=mock.ANY),
        ])

    @mock.patch('kazoo.client.KazooClient.set', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.set_acls', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.create', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.get', mock.Mock())
    def test_put_check_content(self):
        """Verifies put/update with check_content=True."""
        kazoo.client.KazooClient.create.side_effect = (
            kazoo.client.NodeExistsError)
        kazoo.client.KazooClient.get.return_value = (b'aaa', {})
        zkclient = kazoo.client.KazooClient()
        zkutils.put(zkclient, '/a', 'aaa', check_content=True)
        self.assertFalse(kazoo.client.KazooClient.set.called)

        zkutils.put(zkclient, '/a', 'bbb', check_content=True)
        kazoo.client.KazooClient.set.assert_called_with('/a', b'bbb')

    @mock.patch('kazoo.client.KazooClient.set', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.set_acls', mock.Mock())
    @mock.patch('kazoo.client.KazooClient.get', mock.Mock())
    def test_update_check_content(self):
        """Verifies put/update with check_content=True."""
        kazoo.client.KazooClient.get.return_value = (b'aaa', {})
        zkclient = kazoo.client.KazooClient()
        zkutils.update(zkclient, '/a', 'aaa', check_content=True)
        self.assertFalse(kazoo.client.KazooClient.set.called)

        zkutils.update(zkclient, '/a', 'bbb', check_content=True)
        kazoo.client.KazooClient.set.assert_called_with('/a', b'bbb')
Esempio n. 11
0
 def request_mock(host: str) -> Any:
     request = mock.Mock(spec=['get_host'])
     request.attach_mock(mock.Mock(return_value=host), 'get_host')
     return request
Esempio n. 12
0
 def test_initialize(self):
     request = mock.Mock()
     handler = FSMixin(self.get_app(), request)
     self.assertTrue(issubclass(handler.fs, PosixFS))
Esempio n. 13
0
class UtilTestCase(base.BaseTestCase):
    """TestCase for functions in util module"""
    def setUp(self):
        super(UtilTestCase, self).setUp()
        self.oslo_connection_mock = mock.Mock()
        patch = mock.patch('oslo_vmware.api.VMwareAPISession',
                           return_value=self.oslo_connection_mock)
        self.session_mock = patch.start()
        self.addCleanup(patch.stop)

    def test_empty_map_if_config_network_maps_is_empty(self):
        CONF.set_override('network_maps', [], 'ML2_VMWARE')
        self.assertDictEqual({},
                             dvs_util.create_network_map_from_config(
                                 CONF.ML2_VMWARE))

    @mock.patch('vmware_dvs.utils.dvs_util.DVSController._get_dvs',
                return_value=(mock.Mock(), 'datacenter1'))
    def test_creates_network_map_from_conf(self, *args):
        network_map = ['physnet1:dvSwitch', 'physnet2:dvSwitch1']
        CONF.set_override('network_maps', network_map, 'ML2_VMWARE')
        actual = dvs_util.create_network_map_from_config(CONF.ML2_VMWARE)

        self.assertEqual(len(network_map), len(actual))

        for net, dvs_name in [i.split(':') for i in network_map]:
            controller = actual[net]
            self.assertEqual(self.oslo_connection_mock, controller.connection)

        vmware_conf = config.CONF.ML2_VMWARE
        self.session_mock.assert_called_once_with(
            vmware_conf.vsphere_hostname,
            vmware_conf.vsphere_login,
            vmware_conf.vsphere_password,
            vmware_conf.api_retry_count,
            vmware_conf.task_poll_interval,
            pool_size=vmware_conf.connections_pool_size)

    def test_wrap_retry_w_login_unsuccessful(self):
        func = mock.Mock()

        def side_effect(*args, **kwargs):
            exception = vmware_exceptions.VMwareDriverException()
            exception.message = dvs_const.LOGIN_PROBLEM_TEXT
            raise exception

        func.side_effect = side_effect

        def double(*args, **kwargs):
            return func(*args, **kwargs)

        self.assertRaises(vmware_exceptions.VMwareDriverException,
                          dvs_util.wrap_retry(double))
        self.assertEqual(3, func.call_count)

    def test_wrap_retry_w_concurrent_modification(self):
        func = mock.Mock()
        func.side_effect = [
            exceptions.VMWareDVSException(
                message=dvs_const.CONCURRENT_MODIFICATION_TEXT,
                type='TestException',
                cause='Test cause'),
            exceptions.VMWareDVSException(message='Some exception text',
                                          type='TestException',
                                          cause='Test cause')
        ]

        def double(*args, **kwargs):
            return func(*args, **kwargs)

        self.assertRaises(exceptions.VMWareDVSException,
                          dvs_util.wrap_retry(double))
        self.assertEqual(2, func.call_count)
Esempio n. 14
0
 def setUp(self):
     super(SpecBuilderTestCase, self).setUp()
     self.spec = mock.Mock(name='spec')
     self.factory = mock.Mock(name='factory')
     self.factory.create.return_value = self.spec
     self.builder = spec_builder.SpecBuilder(self.factory)
Esempio n. 15
0
    def _test_configure_tenant_networks(self,
                                        client_mock,
                                        is_client_id=False,
                                        vif_int_info=False):
        upd_mock = mock.Mock()
        client_mock.return_value.update_port = upd_mock
        if vif_int_info:
            kwargs = {
                'internal_info': {
                    'tenant_vif_port_id': uuidutils.generate_uuid()
                }
            }
            self.port.internal_info = {
                'tenant_vif_port_id': self.port.extra['vif_port_id']
            }
            self.port.extra = {}
        else:
            kwargs = {'extra': {'vif_port_id': uuidutils.generate_uuid()}}
        second_port = utils.create_test_port(self.context,
                                             node_id=self.node.id,
                                             address='52:54:00:cf:2d:33',
                                             uuid=uuidutils.generate_uuid(),
                                             local_link_connection={
                                                 'switch_id':
                                                 '0a:1b:2c:3d:4e:ff',
                                                 'port_id': 'Ethernet1/1',
                                                 'switch_info': 'switch2'
                                             },
                                             **kwargs)
        if is_client_id:
            client_ids = (CLIENT_ID1, CLIENT_ID2)
            ports = (self.port, second_port)
            for port, client_id in zip(ports, client_ids):
                extra = port.extra
                extra['client-id'] = client_id
                port.extra = extra
                port.save()

        expected_body = {
            'port': {
                'device_owner': 'baremetal:none',
                'device_id': self.node.instance_uuid or self.node.uuid,
                'admin_state_up': True,
                'binding:vnic_type': 'baremetal',
                'binding:host_id': self.node.uuid,
            }
        }
        port1_body = copy.deepcopy(expected_body)
        port1_body['port']['binding:profile'] = {
            'local_link_information': [self.port.local_link_connection]
        }
        port2_body = copy.deepcopy(expected_body)
        port2_body['port']['binding:profile'] = {
            'local_link_information': [second_port.local_link_connection]
        }
        if is_client_id:
            port1_body['port']['extra_dhcp_opts'] = ([{
                'opt_name':
                'client-id',
                'opt_value':
                client_ids[0]
            }])
            port2_body['port']['extra_dhcp_opts'] = ([{
                'opt_name':
                'client-id',
                'opt_value':
                client_ids[1]
            }])
        with task_manager.acquire(self.context, self.node.id) as task:
            self.interface.configure_tenant_networks(task)
            client_mock.assert_called_once_with(task.context.auth_token)
        if vif_int_info:
            portid1 = self.port.internal_info['tenant_vif_port_id']
            portid2 = second_port.internal_info['tenant_vif_port_id']
        else:
            portid1 = self.port.extra['vif_port_id']
            portid2 = second_port.extra['vif_port_id']
        upd_mock.assert_has_calls(
            [mock.call(portid1, port1_body),
             mock.call(portid2, port2_body)],
            any_order=True)
Esempio n. 16
0
 def test_allow_deny_access_via_manager(self, op):
     self.assertRaises(NotImplementedError,
                       getattr(self._driver,
                               "_%s_access_via_manager" % op),
                       mock.Mock(), self.fake_context, self.fake_share,
                       self.fake_access, None)
Esempio n. 17
0
 def setUp(self):
     super(TaskManagerTestCase, self).setUp()
     self.host = 'test-host'
     self.config(host=self.host)
     self.context = mock.sentinel.context
     self.node = mock.Mock(spec_set=objects.Node)
Esempio n. 18
0
 def test_init_invalid(self):
     self.assertRaises(TypeError, layout.GlusterfsShareLayoutBase,
                       mock.Mock())
Esempio n. 19
0
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
os.environ['TENSORPACK_DOC_BUILDING'] = '1'


MOCK_MODULES = ['scipy', 'tabulate',
                'sklearn.datasets', 'sklearn',
                'scipy.misc', 'h5py', 'nltk',
                'cv2', 'scipy.io', 'dill', 'zmq', 'subprocess32', 'lmdb',
                'tornado.concurrent', 'tornado',
                'msgpack', 'msgpack_numpy',
                'gym', 'functools32']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = mock.Mock(name=mod_name)

import tensorpack

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.4'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.todo',
    'sphinx.ext.napoleon',
Esempio n. 20
0
    def test_subclass(self):
        fake_conf = mock.Mock()
        _layout = self.FakeLayout(self.fake_driver, configuration=fake_conf)

        self.assertEqual(fake_conf, _layout.configuration)
        self.assertRaises(NotImplementedError, _layout._update_share_stats)
Esempio n. 21
0
 def test_get_res_id(self):
     resource = mock.Mock()
     resource.self.path = '/foo/bar/12345'
     ret = self.client.get_res_id(resource)
     self.assertEquals(ret, 12345)
Esempio n. 22
0
 def _setup(self):
     fake_conf = config.Configuration(None)
     fake_layout = mock.Mock()
     self.mock_object(importutils, "import_object",
                      mock.Mock(return_value=fake_layout))
     return fake_conf, fake_layout
Esempio n. 23
0
 def test_get_branches_of_non_existent_project(self):
     self.mock(projects, 'get_branches', mock.Mock())
     projects.get_branches.return_value = None
     req = {'project_id': 'nonexistent'}
     with self.call_should_fail(httplib.NOT_FOUND):
         self.call_api('get_branches', req)
Esempio n. 24
0
 def test_add_task_with_multiple_args(self):
     task = mock.Mock(return_value='foobar')
     with mock.patch.object(self.runner.in_queue, 'put') as mock_put:
         self.runner.add_task(task, 1, 2)
         mock_put.assert_called_once_with((task, (1, 2), {}))
Esempio n. 25
0
 def mock_branches(self):
     self.mock(projects, 'get_branches', mock.Mock())
     projects.get_branches.return_value = [
         project_config_pb2.BranchesCfg.Branch(name='master'),
         project_config_pb2.BranchesCfg.Branch(name='release42'),
     ]
Esempio n. 26
0
 def test_add_task_with_kwargs(self):
     task = mock.Mock(return_value='foobar')
     with mock.patch.object(self.runner.in_queue, 'put') as mock_put:
         self.runner.add_task(task, foo='bar')
         mock_put.assert_called_once_with((task, (), {'foo': 'bar'}))
Esempio n. 27
0
 def test_remove_non_existing_node(self):
     self.use_manager()
     self.client.manager.remove_manager = mock.Mock(
         return_value=self.MANAGERS_LIST[0])
     self.assertRaises(ClickInvocationException, self.invoke,
                       'cfy cluster remove hostname_BlaBla')
 def test_get_rpc_callbacks(self):
     context = mock.Mock()
     agent = mock.Mock()
     sg_agent = mock.Mock()
     obj = self.mgr.get_rpc_callbacks(context, agent, sg_agent)
     self.assertIsInstance(obj, macvtap_neutron_agent.MacvtapRPCCallBack)
Esempio n. 29
0
 def _get_mock_network_operation_context():
     context = mock.Mock(current=FAKE_NETWORK.copy())
     return context
Esempio n. 30
0
 def setUp(self):
     super(UpdateSecurityGroupRulesTestCase, self).setUp()
     self.spec = mock.Mock()
     self.vim.client.factory.create.return_value = self.spec