<commit_before># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
    :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details
    :license: Apache 2.0, see LICENSE for more details.

    tests.unit.modules.virtualenv_test
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''

# Import python libraries
import warnings
import os
import sys

# Import Salt Testing libs
from salttesting import skipIf, TestCase
from salttesting.helpers import (
    ensure_in_syspath,
    TestsLoggingHandler,
    ForceImportErrorOn
)
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, patch
ensure_in_syspath('../../')

# Import salt libs
from salt.modules import virtualenv_mod
from salt.exceptions import CommandExecutionError

virtualenv_mod.__salt__ = {}
virtualenv_mod.__opts__['venv_bin'] = 'virtualenv'
base_virtualenv_mock = MagicMock()
base_virtualenv_mock.__version__ = '1.9.1'

@skipIf(NO_MOCK, NO_MOCK_REASON)
@patch('salt.utils.which', lambda bin_name: bin_name)
@patch.dict('sys.modules', {'virtualenv': base_virtualenv_mock})
class VirtualenvTestCase(TestCase):

    def test_issue_6029_deprecated_distribute(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod._install_script = MagicMock(
                return_value={
                    'retcode': 0,
                    'stdout': 'Installed script!',
                    'stderr': ''
                }
            )
            virtualenv_mod.create(
                '/tmp/foo', system_site_packages=True, distribute=True
            )
            mock.assert_called_once_with(
                'virtualenv --distribute --system-site-packages /tmp/foo',
                runas=None
            )

        with TestsLoggingHandler() as handler:
            # Let's fake a higher virtualenv version
            virtualenv_mock = MagicMock()
            virtualenv_mock.__version__ = '1.10rc1'
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                with patch.dict('sys.modules',
                                {'virtualenv': virtualenv_mock}):
                    virtualenv_mod.create(
                        '/tmp/foo', system_site_packages=True, distribute=True
                    )
                    mock.assert_called_once_with(
                        'virtualenv --system-site-packages /tmp/foo',
                        runas=None
                    )

                # Are we logging the deprecation information?
                self.assertIn(
                    'INFO:The virtualenv \'--distribute\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'distribute\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.',
                    handler.messages
                )

    def test_issue_6030_deprecated_never_download(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', never_download=True
            )
            mock.assert_called_once_with(
                'virtualenv --never-download /tmp/foo',
                runas=None
            )

        with TestsLoggingHandler() as handler:
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            # Let's fake a higher virtualenv version
            virtualenv_mock = MagicMock()
            virtualenv_mock.__version__ = '1.10rc1'
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                with patch.dict('sys.modules',
                                {'virtualenv': virtualenv_mock}):
                    virtualenv_mod.create(
                        '/tmp/foo', never_download=True
                    )
                    mock.assert_called_once_with('virtualenv /tmp/foo',
                                                 runas=None)

                # Are we logging the deprecation information?
                self.assertIn(
                    'INFO:The virtualenv \'--never-download\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'never_download\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.',
                    handler.messages
                )

    def test_issue_6031_multiple_extra_search_dirs(self):
        extra_search_dirs = [
            '/tmp/bar-1',
            '/tmp/bar-2',
            '/tmp/bar-3'
        ]

        # Passing extra_search_dirs as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', extra_search_dir=extra_search_dirs
            )
            mock.assert_called_once_with(
                'virtualenv '
                '--extra-search-dir=/tmp/bar-1 '
                '--extra-search-dir=/tmp/bar-2 '
                '--extra-search-dir=/tmp/bar-3 '
                '/tmp/foo',
                runas=None
            )

        # Passing extra_search_dirs as comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', extra_search_dir=','.join(extra_search_dirs)
            )
            mock.assert_called_once_with(
                'virtualenv '
                '--extra-search-dir=/tmp/bar-1 '
                '--extra-search-dir=/tmp/bar-2 '
                '--extra-search-dir=/tmp/bar-3 '
                '/tmp/foo',
                runas=None
            )

    def test_system_site_packages_and_no_site_packages_mutual_exclusion(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                no_site_packages=True,
                system_site_packages=True
            )

    def test_no_site_packages_deprecation(self):
        # We *always* want *all* warnings thrown on this module
        warnings.resetwarnings()
        warnings.filterwarnings('always', '', DeprecationWarning, __name__)

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            with warnings.catch_warnings(record=True) as w:
                virtualenv_mod.create(
                    '/tmp/foo', no_site_packages=True
                )
                self.assertEqual(
                    '\'no_site_packages\' has been deprecated. Please '
                    'start using \'system_site_packages=False\' which '
                    'means exactly the same as \'no_site_packages=True\'. '
                    'This warning and respective workaround will be removed '
                    'in Salt Helium (Unreleased)',
                    str(w[-1].message)
                )

    def test_unapplicable_options(self):
        # ----- Virtualenv using pyvenv options ----------------------------->
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='virtualenv',
                upgrade=True
            )

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='virtualenv',
                symlinks=True
            )
        # <---- Virtualenv using pyvenv options ------------------------------

        # ----- pyvenv using virtualenv options ----------------------------->
        virtualenv_mod.__salt__ = {'cmd.which_bin': lambda _: 'pyvenv'}

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                no_site_packages=True
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                python='python2.7'
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                prompt='PY Prompt'
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                never_download=True
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                extra_search_dir='/tmp/bar'
            )
        # <---- pyvenv using virtualenv options ------------------------------

    def test_get_virtualenv_version_from_shell(self):
        with ForceImportErrorOn('virtualenv'):

            # ----- virtualenv binary not available ------------------------->
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                self.assertRaises(
                    CommandExecutionError,
                    virtualenv_mod.create,
                    '/tmp/foo',
                )
            # <---- virtualenv binary not available --------------------------

            # ----- virtualenv binary present but > 0 exit code ------------->
            mock = MagicMock(side_effect=[
                {'retcode': 1, 'stdout': '', 'stderr': 'This is an error'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                self.assertRaises(
                    CommandExecutionError,
                    virtualenv_mod.create,
                    '/tmp/foo',
                    venv_bin='virtualenv',
                )
            # <---- virtualenv binary present but > 0 exit code --------------

            # ----- virtualenv binary returns 1.9.1 as it's version --------->
            mock = MagicMock(side_effect=[
                {'retcode': 0, 'stdout': '1.9.1'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create(
                    '/tmp/foo', never_download=True
                )
                mock.assert_called_with(
                    'virtualenv --never-download /tmp/foo',
                    runas=None
                )
            # <---- virtualenv binary returns 1.9.1 as it's version ----------

            # ----- virtualenv binary returns 1.10rc1 as it's version ------->
            mock = MagicMock(side_effect=[
                {'retcode': 0, 'stdout': '1.10rc1'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create(
                    '/tmp/foo', never_download=True
                )
                mock.assert_called_with(
                    'virtualenv /tmp/foo',
                    runas=None
                )
            # <---- virtualenv binary returns 1.10rc1 as it's version --------

    def test_python_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', python=sys.executable,
            )
            mock.assert_called_once_with(
                'virtualenv --python={0} /tmp/foo'.format(sys.executable),
                runas=None
            )

    def test_prompt_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='PY Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt=\'PY Prompt\' /tmp/foo',
                runas=None
            )

        # Now with some quotes on the mix
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='\'PY\' Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt="\'PY\' Prompt" /tmp/foo',
                runas=None
            )

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='"PY" Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt=\'"PY" Prompt\' /tmp/foo',
                runas=None
            )

    def test_clear_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', clear=True)
            mock.assert_called_once_with(
                'virtualenv --clear /tmp/foo', runas=None
            )

    def test_upgrade_argument(self):
        # We test for pyvenv only because with virtualenv this is un
        # unsupported option.
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', venv_bin='pyvenv', upgrade=True)
            mock.assert_called_once_with(
                'pyvenv --upgrade /tmp/foo', runas=None
            )

    def test_symlinks_argument(self):
        # We test for pyvenv only because with virtualenv this is un
        # unsupported option.
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', venv_bin='pyvenv', symlinks=True)
            mock.assert_called_once_with(
                'pyvenv --symlinks /tmp/foo', runas=None
            )

if __name__ == '__main__':
    from integration import run_tests
    run_tests(VirtualenvTestCase, needs_daemon=False)
<commit_msg>Remove unused imports<commit_after># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
    :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details
    :license: Apache 2.0, see LICENSE for more details.

    tests.unit.modules.virtualenv_test
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'''

# Import python libraries
import warnings
import sys

# Import Salt Testing libs
from salttesting import skipIf, TestCase
from salttesting.helpers import (
    ensure_in_syspath,
    TestsLoggingHandler,
    ForceImportErrorOn
)
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, patch
ensure_in_syspath('../../')

# Import salt libs
from salt.modules import virtualenv_mod
from salt.exceptions import CommandExecutionError

virtualenv_mod.__salt__ = {}
virtualenv_mod.__opts__['venv_bin'] = 'virtualenv'
base_virtualenv_mock = MagicMock()
base_virtualenv_mock.__version__ = '1.9.1'

@skipIf(NO_MOCK, NO_MOCK_REASON)
@patch('salt.utils.which', lambda bin_name: bin_name)
@patch.dict('sys.modules', {'virtualenv': base_virtualenv_mock})
class VirtualenvTestCase(TestCase):

    def test_issue_6029_deprecated_distribute(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod._install_script = MagicMock(
                return_value={
                    'retcode': 0,
                    'stdout': 'Installed script!',
                    'stderr': ''
                }
            )
            virtualenv_mod.create(
                '/tmp/foo', system_site_packages=True, distribute=True
            )
            mock.assert_called_once_with(
                'virtualenv --distribute --system-site-packages /tmp/foo',
                runas=None
            )

        with TestsLoggingHandler() as handler:
            # Let's fake a higher virtualenv version
            virtualenv_mock = MagicMock()
            virtualenv_mock.__version__ = '1.10rc1'
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                with patch.dict('sys.modules',
                                {'virtualenv': virtualenv_mock}):
                    virtualenv_mod.create(
                        '/tmp/foo', system_site_packages=True, distribute=True
                    )
                    mock.assert_called_once_with(
                        'virtualenv --system-site-packages /tmp/foo',
                        runas=None
                    )

                # Are we logging the deprecation information?
                self.assertIn(
                    'INFO:The virtualenv \'--distribute\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'distribute\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.',
                    handler.messages
                )

    def test_issue_6030_deprecated_never_download(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', never_download=True
            )
            mock.assert_called_once_with(
                'virtualenv --never-download /tmp/foo',
                runas=None
            )

        with TestsLoggingHandler() as handler:
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            # Let's fake a higher virtualenv version
            virtualenv_mock = MagicMock()
            virtualenv_mock.__version__ = '1.10rc1'
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                with patch.dict('sys.modules',
                                {'virtualenv': virtualenv_mock}):
                    virtualenv_mod.create(
                        '/tmp/foo', never_download=True
                    )
                    mock.assert_called_once_with('virtualenv /tmp/foo',
                                                 runas=None)

                # Are we logging the deprecation information?
                self.assertIn(
                    'INFO:The virtualenv \'--never-download\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'never_download\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.',
                    handler.messages
                )

    def test_issue_6031_multiple_extra_search_dirs(self):
        extra_search_dirs = [
            '/tmp/bar-1',
            '/tmp/bar-2',
            '/tmp/bar-3'
        ]

        # Passing extra_search_dirs as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', extra_search_dir=extra_search_dirs
            )
            mock.assert_called_once_with(
                'virtualenv '
                '--extra-search-dir=/tmp/bar-1 '
                '--extra-search-dir=/tmp/bar-2 '
                '--extra-search-dir=/tmp/bar-3 '
                '/tmp/foo',
                runas=None
            )

        # Passing extra_search_dirs as comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', extra_search_dir=','.join(extra_search_dirs)
            )
            mock.assert_called_once_with(
                'virtualenv '
                '--extra-search-dir=/tmp/bar-1 '
                '--extra-search-dir=/tmp/bar-2 '
                '--extra-search-dir=/tmp/bar-3 '
                '/tmp/foo',
                runas=None
            )

    def test_system_site_packages_and_no_site_packages_mutual_exclusion(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                no_site_packages=True,
                system_site_packages=True
            )

    def test_no_site_packages_deprecation(self):
        # We *always* want *all* warnings thrown on this module
        warnings.resetwarnings()
        warnings.filterwarnings('always', '', DeprecationWarning, __name__)

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            with warnings.catch_warnings(record=True) as w:
                virtualenv_mod.create(
                    '/tmp/foo', no_site_packages=True
                )
                self.assertEqual(
                    '\'no_site_packages\' has been deprecated. Please '
                    'start using \'system_site_packages=False\' which '
                    'means exactly the same as \'no_site_packages=True\'. '
                    'This warning and respective workaround will be removed '
                    'in Salt Helium (Unreleased)',
                    str(w[-1].message)
                )

    def test_unapplicable_options(self):
        # ----- Virtualenv using pyvenv options ----------------------------->
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='virtualenv',
                upgrade=True
            )

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='virtualenv',
                symlinks=True
            )
        # <---- Virtualenv using pyvenv options ------------------------------

        # ----- pyvenv using virtualenv options ----------------------------->
        virtualenv_mod.__salt__ = {'cmd.which_bin': lambda _: 'pyvenv'}

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                no_site_packages=True
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                python='python2.7'
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                prompt='PY Prompt'
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                never_download=True
            )

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                virtualenv_mod.create,
                '/tmp/foo',
                venv_bin='pyvenv',
                extra_search_dir='/tmp/bar'
            )
        # <---- pyvenv using virtualenv options ------------------------------

    def test_get_virtualenv_version_from_shell(self):
        with ForceImportErrorOn('virtualenv'):

            # ----- virtualenv binary not available ------------------------->
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                self.assertRaises(
                    CommandExecutionError,
                    virtualenv_mod.create,
                    '/tmp/foo',
                )
            # <---- virtualenv binary not available --------------------------

            # ----- virtualenv binary present but > 0 exit code ------------->
            mock = MagicMock(side_effect=[
                {'retcode': 1, 'stdout': '', 'stderr': 'This is an error'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                self.assertRaises(
                    CommandExecutionError,
                    virtualenv_mod.create,
                    '/tmp/foo',
                    venv_bin='virtualenv',
                )
            # <---- virtualenv binary present but > 0 exit code --------------

            # ----- virtualenv binary returns 1.9.1 as it's version --------->
            mock = MagicMock(side_effect=[
                {'retcode': 0, 'stdout': '1.9.1'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create(
                    '/tmp/foo', never_download=True
                )
                mock.assert_called_with(
                    'virtualenv --never-download /tmp/foo',
                    runas=None
                )
            # <---- virtualenv binary returns 1.9.1 as it's version ----------

            # ----- virtualenv binary returns 1.10rc1 as it's version ------->
            mock = MagicMock(side_effect=[
                {'retcode': 0, 'stdout': '1.10rc1'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create(
                    '/tmp/foo', never_download=True
                )
                mock.assert_called_with(
                    'virtualenv /tmp/foo',
                    runas=None
                )
            # <---- virtualenv binary returns 1.10rc1 as it's version --------

    def test_python_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create(
                '/tmp/foo', python=sys.executable,
            )
            mock.assert_called_once_with(
                'virtualenv --python={0} /tmp/foo'.format(sys.executable),
                runas=None
            )

    def test_prompt_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='PY Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt=\'PY Prompt\' /tmp/foo',
                runas=None
            )

        # Now with some quotes on the mix
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='\'PY\' Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt="\'PY\' Prompt" /tmp/foo',
                runas=None
            )

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='"PY" Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt=\'"PY" Prompt\' /tmp/foo',
                runas=None
            )

    def test_clear_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', clear=True)
            mock.assert_called_once_with(
                'virtualenv --clear /tmp/foo', runas=None
            )

    def test_upgrade_argument(self):
        # We test for pyvenv only because with virtualenv this is un
        # unsupported option.
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', venv_bin='pyvenv', upgrade=True)
            mock.assert_called_once_with(
                'pyvenv --upgrade /tmp/foo', runas=None
            )

    def test_symlinks_argument(self):
        # We test for pyvenv only because with virtualenv this is un
        # unsupported option.
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', venv_bin='pyvenv', symlinks=True)
            mock.assert_called_once_with(
                'pyvenv --symlinks /tmp/foo', runas=None
            )

if __name__ == '__main__':
    from integration import run_tests
    run_tests(VirtualenvTestCase, needs_daemon=False)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Import Salt Libs
from salt.utils.validate import net

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import NO_MOCK, NO_MOCK_REASON
from salttesting.helpers import ensure_in_syspath

ensure_in_syspath('../../')

@skipIf(NO_MOCK, NO_MOCK_REASON)
class ValidateNetTestCase(TestCase):
    '''
    TestCase for salt.utils.validate.net module
    '''

    def __ip_addr(self, true_addrs, false_addrs):
        for addr in true_addrs:
            self.assertTrue(net.ipv4_addr(addr))

        for addr in false_addrs:
            self.assertFalse(net.ipv4_addr(addr))

    def test_ipv4_addr(self):
        '''
        Test IPv4 address validation
        '''
        true_addrs = [
            '127.0.0.1',
            '127.0.0.1',
            '127.0.0.19',
            '1.1.1.1/28',
            '127.0.0.11/32',
        ]

        false_addrs = [
            '127.0.0.911',
            '127.0.0911',
            '127.0.011',
            '127.0.011/32',
            '::1',
            '::1/128',
            '::1/28',
        ]

        self.__ip_addr(true_addrs, false_addrs)

    def test_ipv6_addr(self):
        '''
        Test IPv6 address validation
        '''
        true_addrs = [
            '::1',
            '::1/32',
            '::1/32',
            '::1/128',
            '2a03:4000:c:10aa:1017:f00d:aaaa:a',
        ]

        false_addrs = [
            '1.1.1.1',
            '::1/0',
            '::1/32d',
            '::1/129',
        ]

        self.__ip_addr(true_addrs, false_addrs)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ValidateNetTestCase, needs_daemon=False)
<commit_msg>improve test tests/unit/utils/validate_net_test.py useability<commit_after># -*- coding: utf-8 -*-

# Import Salt Libs
from salt.utils.validate import net

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import NO_MOCK, NO_MOCK_REASON
from salttesting.helpers import ensure_in_syspath

ensure_in_syspath('../../')

@skipIf(NO_MOCK, NO_MOCK_REASON)
class ValidateNetTestCase(TestCase):
    '''
    TestCase for salt.utils.validate.net module
    '''

    def test_ipv4_addr(self):
        '''
        Test IPv4 address validation
        '''
        self.assertTrue(net.ipv4_addr('127.0.0.1'))
        self.assertTrue(net.ipv4_addr('127.0.0.1'))
        self.assertTrue(net.ipv4_addr('127.0.0.19'))
        self.assertTrue(net.ipv4_addr('1.1.1.1/28'))
        self.assertTrue(net.ipv4_addr('127.0.0.11/32'))

        self.assertFalse(net.ipv4_addr('127.0.0.911'))
        self.assertFalse(net.ipv4_addr('127.0.0911'))
        self.assertFalse(net.ipv4_addr('127.0.011'))
        self.assertFalse(net.ipv4_addr('127.0.011/32'))
        self.assertFalse(net.ipv4_addr('::1'))
        self.assertFalse(net.ipv4_addr('::1/128'))
        self.assertFalse(net.ipv4_addr('::1/28'))

    def test_ipv6_addr(self):
        '''
        Test IPv6 address validation
        '''
        self.assertTrue(net.ipv6_addr('::1'))
        self.assertTrue(net.ipv6_addr('::1/32'))
        self.assertTrue(net.ipv6_addr('::1/32'))
        self.assertTrue(net.ipv6_addr('::1/128'))
        self.assertTrue(net.ipv6_addr('2a03:4000:c:10aa:1017:f00d:aaaa:a'))

        self.assertFalse(net.ipv6_addr('1.1.1.1'))
        self.assertFalse(net.ipv6_addr('::1/0'))
        self.assertFalse(net.ipv6_addr('::1/32d'))
        self.assertFalse(net.ipv6_addr('::1/129'))

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ValidateNetTestCase, needs_daemon=False)
<|endoftext|>


<commit_before>#!/usr/bin/env python
"""
Copyright 2015 Brocade Communications Inc.

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 unittest
import xml.etree.ElementTree as ET
import pynos.versions.base.interface as interface
import pynos.utilities

class TestInterface(unittest.TestCase):
    """
    Interface unit tests. Compare expected XML to generated XML.
    """
    def setUp(self):
        self.interface = interface.Interface(pynos.utilities.return_xml)
        self.namespace = 'urn:brocade.com:mgmt:brocade-interface'
        self.phys_int_type = 'gigabitethernet'
        self.phys_name = '1/0/0'
        self.vlan_id = '40'
        self.sec_vlan = '50'

    def test_description(self):
        expected = '<config>'\
                   '<interface xmlns="{}"><gigabitethernet>'\
                   '<name>1/0/0</name>'\
                   '<description>Hodor</description>'\
                   '</gigabitethernet></interface>'\
                   '</config>'.format(self.namespace)
        description = 'Hodor'
        result = self.interface.description(int_type=self.phys_int_type,
                                            name=self.phys_name,
                                            desc=description)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_description_exception(self):
        with self.assertRaises(KeyError):
            self.interface.description(int_type=self.phys_int_type,
                                       desc='Hodor')

    def test_private_vlan_type(self):
        expected = '<config>'\
                   '<interface-vlan xmlns="{}"><interface>'\
                   '<vlan><name>40</name><private-vlan>'\
                   '<pvlan-type-leaf>isolated</pvlan-type-leaf>'\
                   '</private-vlan></vlan></interface></interface-vlan>'\
                   '</config>'.format(self.namespace)
        result = self.interface.private_vlan_type(name=self.vlan_id,
                                                  pvlan_type='isolated')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_private_vlan_type_exception(self):
        with self.assertRaises(KeyError):
            self.interface.private_vlan_type(name=self.vlan_id)

    def test_vlan_pvlan_association_add(self):
        expected = '<config><interface-vlan xmlns="{}"><interface><vlan>'\
                   '<name>{}</name><private-vlan><association>'\
                   '<sec-assoc-add>{}</sec-assoc-add></association>'\
                   '</private-vlan></vlan></interface></interface-vlan>'\
                   '</config>'.format(self.namespace,
                                      self.vlan_id,
                                      self.sec_vlan)
        interface = self.interface
        result = interface.vlan_pvlan_association_add(name=self.vlan_id,
                                                      sec_vlan=self.sec_vlan)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_vlan_pvlan_association_add_exception(self):
        with self.assertRaises(KeyError):
            self.interface.vlan_pvlan_association_add(name=self.vlan_id)

    def test_pvlan_host_association(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><private-vlan><host-association>'\
                   '<host-pri-pvlan>{3}</host-pri-pvlan>'\
                   '<host-sec-pvlan>{4}</host-sec-pvlan></host-association>'\
                   '</private-vlan></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id,
                                      self.sec_vlan)
        interface = self.interface
        result = interface.pvlan_host_association(int_type=self.phys_int_type,
                                                  name=self.phys_name,
                                                  pri_vlan=self.vlan_id,
                                                  sec_vlan=self.sec_vlan)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_pvlan_host_association_exception(self):
        with self.assertRaises(KeyError):
            self.interface.pvlan_host_association(name=self.vlan_id)

    def test_admin_state_disabled(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<shutdown /></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.admin_state(int_type=self.phys_int_type,
                                            name=self.phys_name,
                                            enabled=False)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_admin_state_enabled(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<shutdown operation="delete" /></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.admin_state(int_type=self.phys_int_type,
                                            name=self.phys_name,
                                            enabled=True)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_admin_state_exception(self):
        with self.assertRaises(KeyError):
            self.interface.admin_state(name=self.phys_name)

    def test_trunk_allowed_vlan_add(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><add>{3}</add></vlan>'\
                   '</allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='add')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_remove(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><remove>{3}</remove>'\
                   '</vlan></allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='remove')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_all(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><all /></vlan>'\
                   '</allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='all')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_none(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><none /></vlan>'\
                   '</allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='none')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_add_ctag(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><trunk-vlan-classification><allowed>'\
                   '<vlan><add><trunk-vlan-id>{3}</trunk-vlan-id>'\
                   '<trunk-ctag-range>{4}</trunk-ctag-range></add></vlan>'\
                   '</allowed></trunk-vlan-classification></trunk>'\
                   '</switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id,
                                      self.sec_vlan)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   ctag=self.sec_vlan,
                                                   action='add')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_remove_ctag(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><trunk-vlan-classification><allowed>'\
                   '<vlan><remove><trunk-vlan-id>{3}</trunk-vlan-id>'\
                   '<trunk-ctag-range>{4}</trunk-ctag-range></remove></vlan>'\
                   '</allowed></trunk-vlan-classification></trunk>'\
                   '</switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id,
                                      self.sec_vlan)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   ctag=self.sec_vlan,
                                                   action='remove')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_exception(self):
        with self.assertRaises(KeyError):
            self.interface.trunk_allowed_vlan(name=self.phys_name)

    def test_mtu(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<mtu>1666</mtu></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.mtu(int_type=self.phys_int_type,
                                    name=self.phys_name,
                                    mtu='1666')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_mtu_exception(self):
        with self.assertRaises(KeyError):
            self.interface.mtu(name=self.phys_name)
<commit_msg>[PYNOS-3] Add unit tests for spanning_tree_state<commit_after>#!/usr/bin/env python
"""
Copyright 2015 Brocade Communications Inc.

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 unittest
import xml.etree.ElementTree as ET
import pynos.versions.base.interface as interface
import pynos.utilities

class TestInterface(unittest.TestCase):
    """
    Interface unit tests. Compare expected XML to generated XML.
    """
    def setUp(self):
        self.interface = interface.Interface(pynos.utilities.return_xml)
        self.namespace = 'urn:brocade.com:mgmt:brocade-interface'
        self.phys_int_type = 'gigabitethernet'
        self.phys_name = '1/0/0'
        self.vlan_id = '40'
        self.sec_vlan = '50'

    def test_description(self):
        expected = '<config>'\
                   '<interface xmlns="{}"><gigabitethernet>'\
                   '<name>1/0/0</name>'\
                   '<description>Hodor</description>'\
                   '</gigabitethernet></interface>'\
                   '</config>'.format(self.namespace)
        description = 'Hodor'
        result = self.interface.description(int_type=self.phys_int_type,
                                            name=self.phys_name,
                                            desc=description)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_description_exception(self):
        with self.assertRaises(KeyError):
            self.interface.description(int_type=self.phys_int_type,
                                       desc='Hodor')

    def test_private_vlan_type(self):
        expected = '<config>'\
                   '<interface-vlan xmlns="{}"><interface>'\
                   '<vlan><name>40</name><private-vlan>'\
                   '<pvlan-type-leaf>isolated</pvlan-type-leaf>'\
                   '</private-vlan></vlan></interface></interface-vlan>'\
                   '</config>'.format(self.namespace)
        result = self.interface.private_vlan_type(name=self.vlan_id,
                                                  pvlan_type='isolated')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_private_vlan_type_exception(self):
        with self.assertRaises(KeyError):
            self.interface.private_vlan_type(name=self.vlan_id)

    def test_vlan_pvlan_association_add(self):
        expected = '<config><interface-vlan xmlns="{}"><interface><vlan>'\
                   '<name>{}</name><private-vlan><association>'\
                   '<sec-assoc-add>{}</sec-assoc-add></association>'\
                   '</private-vlan></vlan></interface></interface-vlan>'\
                   '</config>'.format(self.namespace,
                                      self.vlan_id,
                                      self.sec_vlan)
        interface = self.interface
        result = interface.vlan_pvlan_association_add(name=self.vlan_id,
                                                      sec_vlan=self.sec_vlan)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_vlan_pvlan_association_add_exception(self):
        with self.assertRaises(KeyError):
            self.interface.vlan_pvlan_association_add(name=self.vlan_id)

    def test_pvlan_host_association(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><private-vlan><host-association>'\
                   '<host-pri-pvlan>{3}</host-pri-pvlan>'\
                   '<host-sec-pvlan>{4}</host-sec-pvlan></host-association>'\
                   '</private-vlan></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id,
                                      self.sec_vlan)
        interface = self.interface
        result = interface.pvlan_host_association(int_type=self.phys_int_type,
                                                  name=self.phys_name,
                                                  pri_vlan=self.vlan_id,
                                                  sec_vlan=self.sec_vlan)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_pvlan_host_association_exception(self):
        with self.assertRaises(KeyError):
            self.interface.pvlan_host_association(name=self.vlan_id)

    def test_admin_state_disabled(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<shutdown /></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.admin_state(int_type=self.phys_int_type,
                                            name=self.phys_name,
                                            enabled=False)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_admin_state_enabled(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<shutdown operation="delete" /></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.admin_state(int_type=self.phys_int_type,
                                            name=self.phys_name,
                                            enabled=True)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_admin_state_exception(self):
        with self.assertRaises(KeyError):
            self.interface.admin_state(name=self.phys_name)

    def test_trunk_allowed_vlan_add(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><add>{3}</add></vlan>'\
                   '</allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='add')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_remove(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><remove>{3}</remove>'\
                   '</vlan></allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='remove')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_all(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><all /></vlan>'\
                   '</allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='all')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_none(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><allowed><vlan><none /></vlan>'\
                   '</allowed></trunk></switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   action='none')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_add_ctag(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><trunk-vlan-classification><allowed>'\
                   '<vlan><add><trunk-vlan-id>{3}</trunk-vlan-id>'\
                   '<trunk-ctag-range>{4}</trunk-ctag-range></add></vlan>'\
                   '</allowed></trunk-vlan-classification></trunk>'\
                   '</switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id,
                                      self.sec_vlan)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   ctag=self.sec_vlan,
                                                   action='add')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_remove_ctag(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<switchport><trunk><trunk-vlan-classification><allowed>'\
                   '<vlan><remove><trunk-vlan-id>{3}</trunk-vlan-id>'\
                   '<trunk-ctag-range>{4}</trunk-ctag-range></remove></vlan>'\
                   '</allowed></trunk-vlan-classification></trunk>'\
                   '</switchport></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name, self.vlan_id,
                                      self.sec_vlan)
        result = self.interface.trunk_allowed_vlan(int_type=self.phys_int_type,
                                                   name=self.phys_name,
                                                   vlan=self.vlan_id,
                                                   ctag=self.sec_vlan,
                                                   action='remove')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_trunk_allowed_vlan_exception(self):
        with self.assertRaises(KeyError):
            self.interface.trunk_allowed_vlan(name=self.phys_name)

    def test_mtu(self):
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<mtu>1666</mtu></{1}></interface>'\
                   '</config>'.format(self.namespace, self.phys_int_type,
                                      self.phys_name)
        result = self.interface.mtu(int_type=self.phys_int_type,
                                    name=self.phys_name,
                                    mtu='1666')
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_mtu_exception(self):
        with self.assertRaises(KeyError):
            self.interface.mtu(name=self.phys_name)

    def test_spanning_tree_state_phys_enabled(self):
        stp_namespace = 'urn:brocade.com:mgmt:brocade-xstp'
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<spanning-tree xmlns="{3}">'\
                   '<shutdown operation="delete" /></spanning-tree></{1}>'\
                   '</interface></config>'.format(self.namespace,
                                                  self.phys_int_type,
                                                  self.phys_name,
                                                  stp_namespace)
        interface = self.interface
        result = interface.spanning_tree_state(int_type=self.phys_int_type,
                                               name=self.phys_name,
                                               enabled=True)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_spanning_tree_state_phys_disabled(self):
        stp_namespace = 'urn:brocade.com:mgmt:brocade-xstp'
        expected = '<config><interface xmlns="{0}"><{1}><name>{2}</name>'\
                   '<spanning-tree xmlns="{3}"><shutdown /></spanning-tree>'\
                   '</{1}></interface></config>'.format(self.namespace,
                                                        self.phys_int_type,
                                                        self.phys_name,
                                                        stp_namespace)
        interface = self.interface
        result = interface.spanning_tree_state(int_type=self.phys_int_type,
                                               name=self.phys_name,
                                               enabled=False)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_spanning_tree_state_vlan_enabled(self):
        stp_namespace = 'urn:brocade.com:mgmt:brocade-xstp'
        expected = '<config><interface-vlan xmlns="{0}"><interface><vlan>'\
                   '<name>{1}</name><spanning-tree xmlns="{2}">'\
                   '<stp-shutdown operation="delete" /></spanning-tree>'\
                   '</vlan></interface></interface-vlan>'\
                   '</config>'.format(self.namespace, self.vlan_id,
                                      stp_namespace)
        interface = self.interface
        result = interface.spanning_tree_state(int_type='vlan',
                                               name=self.vlan_id,
                                               enabled=True)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_spanning_tree_state_vlan_disabled(self):
        stp_namespace = 'urn:brocade.com:mgmt:brocade-xstp'
        expected = '<config><interface-vlan xmlns="{0}"><interface><vlan>'\
                   '<name>{1}</name><spanning-tree xmlns="{2}">'\
                   '<stp-shutdown /></spanning-tree>'\
                   '</vlan></interface></interface-vlan>'\
                   '</config>'.format(self.namespace, self.vlan_id,
                                      stp_namespace)
        interface = self.interface
        result = interface.spanning_tree_state(int_type='vlan',
                                               name=self.vlan_id,
                                               enabled=False)
        result = ET.tostring(result)
        self.assertEquals(expected, result)

    def test_spanning_tree_state_exception(self):
        with self.assertRaises(KeyError):
            self.interface.spanning_tree_state(name=self.phys_name)
<|endoftext|>


<commit_before>########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.

__author__ = 'idanmo'

import uuid
import time
from testenv import undeploy_application as undeploy
from workflow_tests.testenv import TestCase
from workflow_tests.testenv import get_resource as resource
from workflow_tests.testenv import deploy_application as deploy
from workflow_tests.testenv import timeout
from workflow_tests.testenv import run_search as search
from workflow_tests.testenv import get_blueprint
from workflow_tests.testenv import delete_blueprint
from workflow_tests.testenv import get_deployment
from workflow_tests.testenv import delete_deployment
from workflow_tests.testenv import publish_blueprint
from workflow_tests.testenv import update_execution_status
from workflow_tests.testenv import get_deployment_executions
from workflow_tests.testenv import get_execution
from workflow_tests.testenv import update_node_instance
from testenv import get_node_instance
from testenv import get_deployment_nodes
from cosmo_manager_rest_client.cosmo_manager_rest_client \
    import CosmoManagerRestClient, CosmoManagerRestCallError

class BasicWorkflowsTest(TestCase):

    def test_execute_operation(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment, _ = deploy(dsl_path, blueprint_id=blueprint_id)

        self.assertEqual(blueprint_id, deployment.blueprintId)

        from plugins.cloudmock.tasks import get_machines
        result = self.send_task(get_machines)
        machines = result.get(timeout=10)

        self.assertEquals(1, len(machines))

    def test_dependencies_order_with_two_nodes(self):
        dsl_path = resource("dsl/dependencies-order-with-two-nodes.yaml")
        deployment, _ = deploy(dsl_path)

        self.assertEquals('mock_app', deployment.blueprintId)

        from plugins.testmockoperations.tasks import get_state as \
            testmock_get_state
        states = self.send_task(testmock_get_state) \
            .get(timeout=10)
        self.assertEquals(2, len(states))
        self.assertTrue('host_node' in states[0]['id'])
        self.assertTrue('db_node' in states[1]['id'])

    @timeout(seconds=120)
    def test_execute_operation_failure(self):
        from plugins.cloudmock.tasks import set_raise_exception_on_start
        self.send_task(set_raise_exception_on_start).get(timeout=10)
        dsl_path = resource("dsl/basic.yaml")
        try:
            deploy(dsl_path)
            self.fail('expected exception')
        except Exception:
            pass

    def test_cloudify_runtime_properties_injection(self):
        dsl_path = resource("dsl/dependencies-order-with-two-nodes.yaml")
        deploy(dsl_path)

        from plugins.testmockoperations.tasks import get_state as \
            testmock_get_state
        states = self.send_task(testmock_get_state).get(timeout=10)
        node_runtime_props = None
        for k, v in states[1]['capabilities'].iteritems():
            if 'host_node' in k:
                node_runtime_props = v
                break
        self.assertEquals('value1', node_runtime_props['property1'])
        self.assertEquals(1,
                          len(node_runtime_props.runtime_properties),
                          msg='Expected 2 but contains: {0}'.format(
                              node_runtime_props.runtime_properties))

    def test_non_existing_operation_exception(self):
        dsl_path = resource("dsl/wrong_operation_name.yaml")
        self.assertRaises(RuntimeError, deploy, dsl_path)

    def test_inject_properties_to_operation(self):
        dsl_path = resource("dsl/hardcoded-operation-properties.yaml")
        deploy(dsl_path)
        from plugins.testmockoperations.tasks import get_state as \
            testmock_get_state
        states = self.send_task(testmock_get_state).get(timeout=10)
        from plugins.testmockoperations.tasks import \
            get_mock_operation_invocations as testmock_get__invocations
        invocations = self.send_task(testmock_get__invocations).get(timeout=10)
        self.assertEqual(1, len(invocations))
        invocation = invocations[0]
        self.assertEqual('mockpropvalue', invocation['mockprop'])
        self.assertEqual('mockpropvalue2', invocation['properties']
                                                     ['mockprop2'])
        self.assertEqual(states[0]['id'], invocation['id'])

    def test_plugin_get_resource(self):
        dsl_path = resource("dsl/get_resource_in_plugin.yaml")
        deploy(dsl_path)
        from plugins.testmockoperations.tasks import \
            get_resource_operation_invocations as testmock_get_invocations
        invocations = self.send_task(testmock_get_invocations).get(
            timeout=10)
        self.assertEquals(1, len(invocations))
        invocation = invocations[0]
        with open(resource("dsl/basic.yaml")) as f:
            basic_data = f.read()

        # checking the resources are the correct data
        self.assertEquals(basic_data, invocation['res1_data'])
        self.assertEquals(basic_data, invocation['res2_data'])

        # checking the custom filepath provided is indeed where the second
        # resource was saved
        self.assertEquals(invocation['custom_filepath'],
                          invocation['res2_path'])

    def test_search(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment, _ = deploy(dsl_path, blueprint_id=blueprint_id)

        self.assertEqual(blueprint_id, deployment.blueprintId)

        from plugins.cloudmock.tasks import get_machines
        result = self.send_task(get_machines)
        machines = result.get(timeout=10)

        self.assertEquals(1, len(machines))
        result = search('')
        hits = map(lambda x: x['_source'], result['hits']['hits'])

        # expecting 4 results - 1 blueprint, 1 deployment, 1 execution, 1 node.
        self.assertEquals(4, len(hits))

    def test_get_blueprint(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment, _ = deploy(dsl_path, blueprint_id=blueprint_id)

        self.assertEqual(blueprint_id, deployment.blueprintId)
        blueprint = get_blueprint(blueprint_id)
        self.assertEqual(blueprint_id, blueprint.id)
        self.assertTrue(len(blueprint.plan) > 0)
        self.assertEqual('None', blueprint.source)

    def test_delete_blueprint(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = publish_blueprint(dsl_path)
        # verifying blueprint exists
        result = get_blueprint(blueprint_id)
        self.assertEqual(blueprint_id, result.id)
        # deleting blueprint
        deleted_bp_id = delete_blueprint(blueprint_id).id
        self.assertEqual(blueprint_id, deleted_bp_id)
        # verifying blueprint does no longer exist
        try:
            get_blueprint(blueprint_id)
            self.fail("Got blueprint {0} successfully even though it "
                      "wasn't expected to exist".format(blueprint_id))
        except CosmoManagerRestCallError:
            pass
        # trying to delete a nonexistent blueprint
        try:
            delete_blueprint(blueprint_id)
            self.fail("Deleted blueprint {0} successfully even though it "
                      "wasn't expected to exist".format(blueprint_id))
        except CosmoManagerRestCallError:
            pass

    def test_delete_deployment(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment_id = 'my_new_deployment'

        def change_execution_status(execution_id, status):
            update_execution_status(execution_id, status)
            time.sleep(5)  # waiting for elasticsearch to update...
            executions = get_deployment_executions(deployment_id)
            self.assertEqual(status, executions[0].status)

        # verifying a deletion of a new deployment, i.e. one which hasn't
        # been installed yet, and therefore all its nodes are still in
        # 'uninitialized' state.
        client = CosmoManagerRestClient('localhost')
        client.publish_blueprint(dsl_path, blueprint_id)
        client.create_deployment(blueprint_id, deployment_id)
        delete_deployment(deployment_id, False)
        time.sleep(5)  # waiting for elasticsearch to clear deployment...
        delete_blueprint(blueprint_id)

        # recreating the deployment, this time actually deploying it too
        _, execution_id = deploy(dsl_path,
                                 blueprint_id=blueprint_id,
                                 deployment_id=deployment_id,
                                 wait_for_execution=True)

        # execution is supposed to be 'terminated' anyway, but verifying it
        # anyway (plus elasticsearch might need time to update..)
        change_execution_status(execution_id, 'terminated')

        # verifying deployment exists
        result = get_deployment(deployment_id)
        self.assertEqual(deployment_id, result.id)

        # retrieving deployment nodes
        nodes = get_deployment_nodes(deployment_id, True).nodes
        self.assertTrue(len(nodes) > 0)
        nodes_ids = [node.id for node in nodes]

        # setting one node's state to 'started' (making it a 'live' node)
        update_node_instance(nodes[0].id, nodes[0].stateVersion,
                             state='started')

        # setting the execution's status to 'launched' so it'll prevent the
        # deployment deletion
        change_execution_status(execution_id, 'launched')

        # attempting to delete the deployment - should fail because the
        # execution is active
        try:
            delete_deployment(deployment_id, False)

            self.fail("Deleted deployment {0} successfully even though it "
                      "should have had a running execution"
                      .format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('running executions' in str(e))

        # setting the execution's status to 'terminated' so it won't prevent
        #  the deployment deletion
        change_execution_status(execution_id, 'terminated')

        # attempting to delete deployment - should fail because there are
        # live nodes for this deployment
        try:
            delete_deployment(deployment_id, False)
            self.fail("Deleted deployment {0} successfully even though it "
                      "should have had live nodes and the ignore_live_nodes "
                      "flag was set to False".format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('live nodes' in str(e))

        # deleting deployment - this time there's no execution running,
        # and using the ignore_live_nodes parameter to force deletion
        deleted_deployment_id = delete_deployment(deployment_id, True).id
        self.assertEqual(deployment_id, deleted_deployment_id)

        # verifying deployment does no longer exist
        try:
            get_deployment(deployment_id)
            self.fail("Got deployment {0} successfully even though it "
                      "wasn't expected to exist".format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('not found' in str(e))

        # verifying deployment's execution does no longer exist
        try:
            get_execution(execution_id)
            self.fail('execution {0} still exists even though it should have '
                      'been deleted when its deployment was deleted'
                      .format(execution_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('not found' in str(e))

        # verifying deployment's nodes do no longer exist
        for node_id in nodes_ids:
            try:
                get_node_instance(node_id)
                self.fail('node {0} still exists even though it should have '
                          'been deleted when its deployment was deleted'
                          .format(node_id))
            except CosmoManagerRestCallError, e:
                self.assertTrue('not found' in str(e))

        # trying to delete a nonexistent deployment
        try:
            delete_deployment(deployment_id)
            self.fail("Deleted deployment {0} successfully even though it "
                      "wasn't expected to exist".format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('not found' in str(e))

    def test_node_state_uninitialized(self):
        dsl_path = resource('dsl/node_states.yaml')
        _id = uuid.uuid1()
        blueprint_id = 'blueprint_{0}'.format(_id)
        deployment_id = 'deployment_{0}'.format(_id)
        client = CosmoManagerRestClient('localhost')
        client.publish_blueprint(dsl_path, blueprint_id)
        client.create_deployment(blueprint_id, deployment_id)
        deployment_nodes = get_deployment_nodes(deployment_id)
        self.assertEqual(1, len(deployment_nodes.nodes))
        node_id = deployment_nodes.nodes[0].id
        node_instance = get_node_instance(node_id)
        self.assertEqual('uninitialized', node_instance['state'])

    def test_node_states(self):
        dsl_path = resource('dsl/node_states.yaml')
        _id = uuid.uuid1()
        blueprint_id = 'blueprint_{0}'.format(_id)
        deployment_id = 'deployment_{0}'.format(_id)
        deployment, _ = deploy(dsl_path,
                               blueprint_id=blueprint_id,
                               deployment_id=deployment_id)

        from plugins.testmockoperations.tasks import get_node_states
        node_states = self.send_task(get_node_states).get(timeout=10)

        self.assertEquals(node_states, [
            'creating', 'configuring', 'starting'
        ])

        deployment_nodes = get_deployment_nodes(deployment_id)
        self.assertEqual(1, len(deployment_nodes.nodes))
        node_id = deployment_nodes.nodes[0].id
        node_instance = get_node_instance(node_id)
        self.assertEqual('started', node_instance['state'])
<commit_msg>CFY-642 flake8 fix<commit_after>########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# 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.

__author__ = 'idanmo'

import uuid
import time
from workflow_tests.testenv import TestCase
from workflow_tests.testenv import get_resource as resource
from workflow_tests.testenv import deploy_application as deploy
from workflow_tests.testenv import timeout
from workflow_tests.testenv import run_search as search
from workflow_tests.testenv import get_blueprint
from workflow_tests.testenv import delete_blueprint
from workflow_tests.testenv import get_deployment
from workflow_tests.testenv import delete_deployment
from workflow_tests.testenv import publish_blueprint
from workflow_tests.testenv import update_execution_status
from workflow_tests.testenv import get_deployment_executions
from workflow_tests.testenv import get_execution
from workflow_tests.testenv import update_node_instance
from testenv import get_node_instance
from testenv import get_deployment_nodes
from cosmo_manager_rest_client.cosmo_manager_rest_client \
    import CosmoManagerRestClient, CosmoManagerRestCallError

class BasicWorkflowsTest(TestCase):

    def test_execute_operation(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment, _ = deploy(dsl_path, blueprint_id=blueprint_id)

        self.assertEqual(blueprint_id, deployment.blueprintId)

        from plugins.cloudmock.tasks import get_machines
        result = self.send_task(get_machines)
        machines = result.get(timeout=10)

        self.assertEquals(1, len(machines))

    def test_dependencies_order_with_two_nodes(self):
        dsl_path = resource("dsl/dependencies-order-with-two-nodes.yaml")
        deployment, _ = deploy(dsl_path)

        self.assertEquals('mock_app', deployment.blueprintId)

        from plugins.testmockoperations.tasks import get_state as \
            testmock_get_state
        states = self.send_task(testmock_get_state) \
            .get(timeout=10)
        self.assertEquals(2, len(states))
        self.assertTrue('host_node' in states[0]['id'])
        self.assertTrue('db_node' in states[1]['id'])

    @timeout(seconds=120)
    def test_execute_operation_failure(self):
        from plugins.cloudmock.tasks import set_raise_exception_on_start
        self.send_task(set_raise_exception_on_start).get(timeout=10)
        dsl_path = resource("dsl/basic.yaml")
        try:
            deploy(dsl_path)
            self.fail('expected exception')
        except Exception:
            pass

    def test_cloudify_runtime_properties_injection(self):
        dsl_path = resource("dsl/dependencies-order-with-two-nodes.yaml")
        deploy(dsl_path)

        from plugins.testmockoperations.tasks import get_state as \
            testmock_get_state
        states = self.send_task(testmock_get_state).get(timeout=10)
        node_runtime_props = None
        for k, v in states[1]['capabilities'].iteritems():
            if 'host_node' in k:
                node_runtime_props = v
                break
        self.assertEquals('value1', node_runtime_props['property1'])
        self.assertEquals(1,
                          len(node_runtime_props.runtime_properties),
                          msg='Expected 2 but contains: {0}'.format(
                              node_runtime_props.runtime_properties))

    def test_non_existing_operation_exception(self):
        dsl_path = resource("dsl/wrong_operation_name.yaml")
        self.assertRaises(RuntimeError, deploy, dsl_path)

    def test_inject_properties_to_operation(self):
        dsl_path = resource("dsl/hardcoded-operation-properties.yaml")
        deploy(dsl_path)
        from plugins.testmockoperations.tasks import get_state as \
            testmock_get_state
        states = self.send_task(testmock_get_state).get(timeout=10)
        from plugins.testmockoperations.tasks import \
            get_mock_operation_invocations as testmock_get__invocations
        invocations = self.send_task(testmock_get__invocations).get(timeout=10)
        self.assertEqual(1, len(invocations))
        invocation = invocations[0]
        self.assertEqual('mockpropvalue', invocation['mockprop'])
        self.assertEqual('mockpropvalue2', invocation['properties']
                                                     ['mockprop2'])
        self.assertEqual(states[0]['id'], invocation['id'])

    def test_plugin_get_resource(self):
        dsl_path = resource("dsl/get_resource_in_plugin.yaml")
        deploy(dsl_path)
        from plugins.testmockoperations.tasks import \
            get_resource_operation_invocations as testmock_get_invocations
        invocations = self.send_task(testmock_get_invocations).get(
            timeout=10)
        self.assertEquals(1, len(invocations))
        invocation = invocations[0]
        with open(resource("dsl/basic.yaml")) as f:
            basic_data = f.read()

        # checking the resources are the correct data
        self.assertEquals(basic_data, invocation['res1_data'])
        self.assertEquals(basic_data, invocation['res2_data'])

        # checking the custom filepath provided is indeed where the second
        # resource was saved
        self.assertEquals(invocation['custom_filepath'],
                          invocation['res2_path'])

    def test_search(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment, _ = deploy(dsl_path, blueprint_id=blueprint_id)

        self.assertEqual(blueprint_id, deployment.blueprintId)

        from plugins.cloudmock.tasks import get_machines
        result = self.send_task(get_machines)
        machines = result.get(timeout=10)

        self.assertEquals(1, len(machines))
        result = search('')
        hits = map(lambda x: x['_source'], result['hits']['hits'])

        # expecting 4 results - 1 blueprint, 1 deployment, 1 execution, 1 node.
        self.assertEquals(4, len(hits))

    def test_get_blueprint(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment, _ = deploy(dsl_path, blueprint_id=blueprint_id)

        self.assertEqual(blueprint_id, deployment.blueprintId)
        blueprint = get_blueprint(blueprint_id)
        self.assertEqual(blueprint_id, blueprint.id)
        self.assertTrue(len(blueprint.plan) > 0)
        self.assertEqual('None', blueprint.source)

    def test_delete_blueprint(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = publish_blueprint(dsl_path)
        # verifying blueprint exists
        result = get_blueprint(blueprint_id)
        self.assertEqual(blueprint_id, result.id)
        # deleting blueprint
        deleted_bp_id = delete_blueprint(blueprint_id).id
        self.assertEqual(blueprint_id, deleted_bp_id)
        # verifying blueprint does no longer exist
        try:
            get_blueprint(blueprint_id)
            self.fail("Got blueprint {0} successfully even though it "
                      "wasn't expected to exist".format(blueprint_id))
        except CosmoManagerRestCallError:
            pass
        # trying to delete a nonexistent blueprint
        try:
            delete_blueprint(blueprint_id)
            self.fail("Deleted blueprint {0} successfully even though it "
                      "wasn't expected to exist".format(blueprint_id))
        except CosmoManagerRestCallError:
            pass

    def test_delete_deployment(self):
        dsl_path = resource("dsl/basic.yaml")
        blueprint_id = 'my_new_blueprint'
        deployment_id = 'my_new_deployment'

        def change_execution_status(execution_id, status):
            update_execution_status(execution_id, status)
            time.sleep(5)  # waiting for elasticsearch to update...
            executions = get_deployment_executions(deployment_id)
            self.assertEqual(status, executions[0].status)

        # verifying a deletion of a new deployment, i.e. one which hasn't
        # been installed yet, and therefore all its nodes are still in
        # 'uninitialized' state.
        client = CosmoManagerRestClient('localhost')
        client.publish_blueprint(dsl_path, blueprint_id)
        client.create_deployment(blueprint_id, deployment_id)
        delete_deployment(deployment_id, False)
        time.sleep(5)  # waiting for elasticsearch to clear deployment...
        delete_blueprint(blueprint_id)

        # recreating the deployment, this time actually deploying it too
        _, execution_id = deploy(dsl_path,
                                 blueprint_id=blueprint_id,
                                 deployment_id=deployment_id,
                                 wait_for_execution=True)

        # execution is supposed to be 'terminated' anyway, but verifying it
        # anyway (plus elasticsearch might need time to update..)
        change_execution_status(execution_id, 'terminated')

        # verifying deployment exists
        result = get_deployment(deployment_id)
        self.assertEqual(deployment_id, result.id)

        # retrieving deployment nodes
        nodes = get_deployment_nodes(deployment_id, True).nodes
        self.assertTrue(len(nodes) > 0)
        nodes_ids = [node.id for node in nodes]

        # setting one node's state to 'started' (making it a 'live' node)
        update_node_instance(nodes[0].id, nodes[0].stateVersion,
                             state='started')

        # setting the execution's status to 'launched' so it'll prevent the
        # deployment deletion
        change_execution_status(execution_id, 'launched')

        # attempting to delete the deployment - should fail because the
        # execution is active
        try:
            delete_deployment(deployment_id, False)

            self.fail("Deleted deployment {0} successfully even though it "
                      "should have had a running execution"
                      .format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('running executions' in str(e))

        # setting the execution's status to 'terminated' so it won't prevent
        #  the deployment deletion
        change_execution_status(execution_id, 'terminated')

        # attempting to delete deployment - should fail because there are
        # live nodes for this deployment
        try:
            delete_deployment(deployment_id, False)
            self.fail("Deleted deployment {0} successfully even though it "
                      "should have had live nodes and the ignore_live_nodes "
                      "flag was set to False".format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('live nodes' in str(e))

        # deleting deployment - this time there's no execution running,
        # and using the ignore_live_nodes parameter to force deletion
        deleted_deployment_id = delete_deployment(deployment_id, True).id
        self.assertEqual(deployment_id, deleted_deployment_id)

        # verifying deployment does no longer exist
        try:
            get_deployment(deployment_id)
            self.fail("Got deployment {0} successfully even though it "
                      "wasn't expected to exist".format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('not found' in str(e))

        # verifying deployment's execution does no longer exist
        try:
            get_execution(execution_id)
            self.fail('execution {0} still exists even though it should have '
                      'been deleted when its deployment was deleted'
                      .format(execution_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('not found' in str(e))

        # verifying deployment's nodes do no longer exist
        for node_id in nodes_ids:
            try:
                get_node_instance(node_id)
                self.fail('node {0} still exists even though it should have '
                          'been deleted when its deployment was deleted'
                          .format(node_id))
            except CosmoManagerRestCallError, e:
                self.assertTrue('not found' in str(e))

        # trying to delete a nonexistent deployment
        try:
            delete_deployment(deployment_id)
            self.fail("Deleted deployment {0} successfully even though it "
                      "wasn't expected to exist".format(deployment_id))
        except CosmoManagerRestCallError, e:
            self.assertTrue('not found' in str(e))

    def test_node_state_uninitialized(self):
        dsl_path = resource('dsl/node_states.yaml')
        _id = uuid.uuid1()
        blueprint_id = 'blueprint_{0}'.format(_id)
        deployment_id = 'deployment_{0}'.format(_id)
        client = CosmoManagerRestClient('localhost')
        client.publish_blueprint(dsl_path, blueprint_id)
        client.create_deployment(blueprint_id, deployment_id)
        deployment_nodes = get_deployment_nodes(deployment_id)
        self.assertEqual(1, len(deployment_nodes.nodes))
        node_id = deployment_nodes.nodes[0].id
        node_instance = get_node_instance(node_id)
        self.assertEqual('uninitialized', node_instance['state'])

    def test_node_states(self):
        dsl_path = resource('dsl/node_states.yaml')
        _id = uuid.uuid1()
        blueprint_id = 'blueprint_{0}'.format(_id)
        deployment_id = 'deployment_{0}'.format(_id)
        deployment, _ = deploy(dsl_path,
                               blueprint_id=blueprint_id,
                               deployment_id=deployment_id)

        from plugins.testmockoperations.tasks import get_node_states
        node_states = self.send_task(get_node_states).get(timeout=10)

        self.assertEquals(node_states, [
            'creating', 'configuring', 'starting'
        ])

        deployment_nodes = get_deployment_nodes(deployment_id)
        self.assertEqual(1, len(deployment_nodes.nodes))
        node_id = deployment_nodes.nodes[0].id
        node_instance = get_node_instance(node_id)
        self.assertEqual('started', node_instance['state'])
<|endoftext|>