Best Python code snippet using nose
test_edgeutils.py
Source:test_edgeutils.py
1"""Implementation of tests for module `edgectl.utils.edgeutils.py`."""2from __future__ import print_function3import errno4import re5import stat6import unittest7import mock8from edgectl.utils import EdgeUtils9# pylint: disable=C010310# disables invalid method name warning which is triggered because the test names are long11# pylint: disable=R020112# disables Method could be a function (no-self-use)13# pylint: disable=W021214# disables Access to a protected member15# pylint: disable=R090416# disables Too many public methods17class TestEdgeUtilAPIs(unittest.TestCase):18 """Unit tests for EdgeUtils APIs"""19 @mock.patch('shutil.rmtree')20 @mock.patch('os.path.exists')21 def test_delete_dir_when_dir_exists(self, mock_exists, mock_rmtree):22 """ Test a valid invocation of API delete_dir when dir to be deleted exists"""23 # arrange24 dir_path = 'blah'25 mock_exists.return_value = True26 # act27 EdgeUtils.delete_dir(dir_path)28 # assert29 mock_exists.assert_called_with(dir_path)30 mock_rmtree.assert_called_with(dir_path, onerror=EdgeUtils._remove_readonly_callback)31 @mock.patch('os.unlink')32 @mock.patch('os.chmod')33 def test_delete_dir_execute_onerror_callback(self, mock_chmod, mock_unlink):34 """ Test rmtree onerror callback invocation"""35 # arrange36 dir_path = 'blah'37 ignored = 038 # act39 EdgeUtils._remove_readonly_callback(ignored, dir_path, ignored)40 # assert41 mock_chmod.assert_called_with(dir_path, stat.S_IWRITE)42 mock_unlink.assert_called_with(dir_path)43 @mock.patch('shutil.rmtree')44 @mock.patch('os.path.exists')45 def test_delete_dir_when_dir_does_not_exist(self, mock_exists, mock_rmtree):46 """ Test a valid invocation of API delete_dir when dir to be deleted does not exist"""47 # arrange48 dir_path = 'blah'49 mock_exists.return_value = False50 # act51 EdgeUtils.delete_dir(dir_path)52 # assert53 mock_exists.assert_called_with(dir_path)54 mock_rmtree.assert_not_called()55 @mock.patch('shutil.rmtree')56 @mock.patch('os.path.exists')57 def test_delete_dir_raises_oserror_when_rmtree_fails(self, mock_exists, mock_rmtree):58 """ Tests invocation of API delete_dir raises OSError when rmtree raises OSError"""59 # arrange60 dir_path = 'blah'61 mock_exists.return_value = True62 mock_rmtree.side_effect = OSError('rmtree error')63 # act, assert64 with self.assertRaises(OSError):65 EdgeUtils.delete_dir(dir_path)66 @mock.patch('os.makedirs')67 def test_mkdir_if_needed_when_dir_does_not_exist(self, mock_mkdirs):68 """ Test a valid invocation of API mkdir_if_needed when dir to be made does not exist """69 # arrange70 dir_path = 'blah'71 # act72 EdgeUtils.mkdir_if_needed(dir_path)73 # assert74 mock_mkdirs.assert_called_with(dir_path)75 @mock.patch('os.makedirs')76 def test_mkdir_if_needed_when_dir_exists(self, mock_mkdirs):77 """ Test a valid invocation of API mkdir_if_needed when dir to be made already exists """78 # arrange79 dir_path = 'blah'80 mock_mkdirs.side_effect = OSError(errno.EEXIST, 'Directory exists.')81 # act82 EdgeUtils.mkdir_if_needed(dir_path)83 # assert84 mock_mkdirs.assert_called_with(dir_path)85 @mock.patch('os.makedirs')86 def test_mkdir_if_needed_raises_oserror_when_mkdir_fails(self, mock_mkdirs):87 """ Tests invocation of API mkdir_if_needed raises OSError when makedirs raises OSError"""88 # arrange89 dir_path = 'blah'90 mock_mkdirs.side_effect = OSError(errno.EACCES, 'Directory permission error')91 # act, assert92 with self.assertRaises(OSError):93 EdgeUtils.mkdir_if_needed(dir_path)94 @mock.patch('os.path.isfile')95 @mock.patch('os.path.exists')96 def test_check_if_file_exists_returns_true(self, mock_exists, mock_isfile):97 """ Test a valid invocation of API check_if_file_exists """98 # arrange #199 file_path = 'blah'100 mock_exists.return_value = True101 mock_isfile.return_value = True102 # act103 result = EdgeUtils.check_if_file_exists(file_path)104 # assert105 mock_exists.assert_called_with(file_path)106 mock_isfile.assert_called_with(file_path)107 self.assertTrue(result)108 @mock.patch('os.path.isfile')109 @mock.patch('os.path.exists')110 def test_check_if_file_exists_returns_false_if_exists_returns_false(self,111 mock_exists, mock_isfile):112 """ Test a valid invocation of API check_if_file_exists """113 # arrange114 file_path = 'blah'115 mock_exists.return_value = False116 # act117 result = EdgeUtils.check_if_file_exists(file_path)118 # assert119 mock_exists.assert_called_with(file_path)120 mock_isfile.assert_not_called()121 self.assertFalse(result)122 @mock.patch('os.path.isfile')123 @mock.patch('os.path.exists')124 def test_check_if_file_exists_returns_false_if_isfile_returns_false(self,125 mock_exists, mock_isfile):126 """ Test a valid invocation of API check_if_file_exists """127 # arrange128 file_path = 'blah'129 mock_exists.return_value = True130 mock_isfile.return_value = False131 # act132 result = EdgeUtils.check_if_file_exists(file_path)133 # assert134 mock_exists.assert_called_with(file_path)135 mock_isfile.assert_called_with(file_path)136 self.assertFalse(result)137 @mock.patch('os.path.isfile')138 @mock.patch('os.path.exists')139 def test_check_if_file_exists_returns_false_path_is_none(self, mock_exists, mock_isfile):140 """ Test a valid invocation of API check_if_file_exists """141 # arrange142 file_path = None143 # act144 result = EdgeUtils.check_if_file_exists(file_path)145 # assert146 mock_exists.assert_not_called()147 mock_isfile.assert_not_called()148 self.assertFalse(result)149 @mock.patch('os.path.isdir')150 @mock.patch('os.path.exists')151 def test_check_if_dir_exists_returns_true(self, mock_exists, mock_isdir):152 """ Test a valid invocation of API check_if_directory_exists """153 # arrange #1154 dir_path = 'blah'155 mock_exists.return_value = True156 mock_isdir.return_value = True157 # act158 result = EdgeUtils.check_if_directory_exists(dir_path)159 # assert160 mock_exists.assert_called_with(dir_path)161 mock_isdir.assert_called_with(dir_path)162 self.assertTrue(result)163 @mock.patch('os.path.isdir')164 @mock.patch('os.path.exists')165 def test_check_if_dir_exists_returns_false_if_exists_returns_false(self,166 mock_exists, mock_isdir):167 """ Test a valid invocation of API check_if_directory_exists """168 # arrange169 dir_path = 'blah'170 mock_exists.return_value = False171 # act172 result = EdgeUtils.check_if_directory_exists(dir_path)173 # assert174 mock_exists.assert_called_with(dir_path)175 mock_isdir.assert_not_called()176 self.assertFalse(result)177 @mock.patch('os.path.isdir')178 @mock.patch('os.path.exists')179 def test_check_if_dir_exists_returns_false_if_isdir_returns_false(self,180 mock_exists, mock_isdir):181 """ Test a valid invocation of API check_if_directory_exists """182 # arrange183 dir_path = 'blah'184 mock_exists.return_value = True185 mock_isdir.return_value = False186 # act187 result = EdgeUtils.check_if_directory_exists(dir_path)188 # assert189 mock_exists.assert_called_with(dir_path)190 mock_isdir.assert_called_with(dir_path)191 self.assertFalse(result)192 @mock.patch('os.path.isdir')193 @mock.patch('os.path.exists')194 def test_check_if_dir_exists_returns_false_path_is_none(self, mock_exists, mock_isdir):195 """ Test a valid invocation of API check_if_directory_exists """196 # arrange197 dir_path = None198 # act199 result = EdgeUtils.check_if_directory_exists(dir_path)200 # assert201 mock_exists.assert_not_called()202 mock_isdir.assert_not_called()203 self.assertFalse(result)204 @mock.patch('shutil.copy2')205 def test_copy_files_valid(self, mock_copy):206 """ Test a valid invocation of API copy_files """207 # arrange208 src_path = 'src'209 dest_path = 'dest'210 # act211 EdgeUtils.copy_files(src_path, dest_path)212 # assert213 mock_copy.assert_called_with(src_path, dest_path)214 @mock.patch('shutil.copy2')215 def test_copy_files_raises_oserror_when_cop2_raises_oserror(self, mock_copy):216 """ Tests invocation of API copy_files raises OSError when copy2 raises OSError"""217 # arrange218 src_path = 'src'219 dest_path = 'dest'220 mock_copy.side_effect = OSError('copy2 OS error')221 # act, assert222 with self.assertRaises(OSError):223 EdgeUtils.copy_files(src_path, dest_path)224 @mock.patch('socket.getfqdn')225 def test_get_hostname_valid(self, mock_hostname):226 """ Test a valid invocation of API get_hostname """227 # arrange228 hostname = 'test_hostname'229 mock_hostname.return_value = hostname230 # act231 result = EdgeUtils.get_hostname()232 # assert233 mock_hostname.assert_called_with()234 self.assertEqual(hostname, result)235 @mock.patch('socket.getfqdn')236 def test_get_hostname_raises_ioerror_when_getfqdn_raises_ioerror(self, mock_hostname):237 """ Tests invocation of API get_hostname raises IOError when getfqdn raises IOError"""238 # arrange239 mock_hostname.side_effect = IOError('getfqdn IO error')240 # act, assert241 with self.assertRaises(IOError):242 EdgeUtils.get_hostname()243 def test_sanitize_registry(self):244 """ Test a valid invocation of API sanitize_registry_data """245 result = EdgeUtils.sanitize_registry_data('test_address', 'test_username', 'test_password')246 pattern = re.compile(r'^Address: test_address, Username: test_username, Password:[\*]+$')247 self.assertTrue(pattern.match(result))248 def test_sanitize_connection_string(self):249 """ Test a valid invocation of API sanitize_connection_string """250 result = EdgeUtils.sanitize_connection_string('HostName=aa;DeviceId=bb;SharedAccessKey=cc')251 pattern = re.compile(r'^HostName=aa;DeviceId=bb;SharedAccessKey=[\*]+$')252 self.assertTrue(pattern.match(result))253 result = EdgeUtils.sanitize_connection_string('HostName=aa;DeviceId=bb;sharedaccesskey=cc')254 pattern = re.compile(r'^HostName=aa;DeviceId=bb;sharedaccesskey=[\*]+$')255 self.assertTrue(pattern.match(result))256 result = EdgeUtils.sanitize_connection_string('HostName=aaa;DeviceId=bbb')257 pattern = re.compile(r'^HostName=aaa;DeviceId=bbb+$')258 self.assertTrue(pattern.match(result))259 @mock.patch('getpass.getpass')260 def test_prompt_password(self, mock_getpass):261 """ Test a valid invocation of API prompt_password """262 valid_pass = 'aaaaa'263 mock_getpass.return_value = valid_pass264 result = EdgeUtils.prompt_password('test password', 5, 8)265 self.assertTrue(valid_pass, result)266if __name__ == '__main__':267 test_classes = [268 TestEdgeUtilAPIs,269 ]270 suites_list = []271 for test_class in test_classes:272 suite = unittest.TestLoader().loadTestsFromTestCase(test_class)273 suites_list.append(suite)274 SUITE = unittest.TestSuite(suites_list)...
test_util.py
Source:test_util.py
1"""2util tests3"""4import os5import sys6from mock import Mock, patch7from nose.tools import eq_, assert_raises8from pip.exceptions import BadCommand9from pip.util import egg_link_path, Inf, get_installed_distributions, find_command10from tests.lib import reset_env, mkdir, write_file11class Tests_EgglinkPath:12 "util.egg_link_path() tests"13 def setup(self):14 project = 'foo'15 self.mock_dist = Mock(project_name=project)16 self.site_packages = 'SITE_PACKAGES'17 self.user_site = 'USER_SITE'18 self.user_site_egglink = os.path.join(self.user_site,'%s.egg-link' % project)19 self.site_packages_egglink = os.path.join(self.site_packages,'%s.egg-link' % project)20 #patches21 from pip import util22 self.old_site_packages = util.site_packages23 self.mock_site_packages = util.site_packages = 'SITE_PACKAGES'24 self.old_running_under_virtualenv = util.running_under_virtualenv25 self.mock_running_under_virtualenv = util.running_under_virtualenv = Mock()26 self.old_virtualenv_no_global = util.virtualenv_no_global27 self.mock_virtualenv_no_global = util.virtualenv_no_global = Mock()28 self.old_user_site = util.user_site29 self.mock_user_site = util.user_site = self.user_site30 from os import path31 self.old_isfile = path.isfile32 self.mock_isfile = path.isfile = Mock()33 def teardown(self):34 from pip import util35 util.site_packages = self.old_site_packages36 util.running_under_virtualenv = self.old_running_under_virtualenv37 util.virtualenv_no_global = self.old_virtualenv_no_global38 util.user_site = self.old_user_site39 from os import path40 path.isfile = self.old_isfile41 def eggLinkInUserSite(self,egglink):42 return egglink==self.user_site_egglink43 def eggLinkInSitePackages(self,egglink):44 return egglink==self.site_packages_egglink45 #########################46 ## egglink in usersite ##47 #########################48 def test_egglink_in_usersite_notvenv(self):49 self.mock_virtualenv_no_global.return_value = False50 self.mock_running_under_virtualenv.return_value = False51 self.mock_isfile.side_effect = self.eggLinkInUserSite52 eq_(egg_link_path(self.mock_dist), self.user_site_egglink)53 def test_egglink_in_usersite_venv_noglobal(self):54 self.mock_virtualenv_no_global.return_value = True55 self.mock_running_under_virtualenv.return_value = True56 self.mock_isfile.side_effect = self.eggLinkInUserSite57 eq_(egg_link_path(self.mock_dist), None)58 def test_egglink_in_usersite_venv_global(self):59 self.mock_virtualenv_no_global.return_value = False60 self.mock_running_under_virtualenv.return_value = True61 self.mock_isfile.side_effect = self.eggLinkInUserSite62 eq_(egg_link_path(self.mock_dist), self.user_site_egglink)63 #########################64 ## egglink in sitepkgs ##65 #########################66 def test_egglink_in_sitepkgs_notvenv(self):67 self.mock_virtualenv_no_global.return_value = False68 self.mock_running_under_virtualenv.return_value = False69 self.mock_isfile.side_effect = self.eggLinkInSitePackages70 eq_(egg_link_path(self.mock_dist), self.site_packages_egglink)71 def test_egglink_in_sitepkgs_venv_noglobal(self):72 self.mock_virtualenv_no_global.return_value = True73 self.mock_running_under_virtualenv.return_value = True74 self.mock_isfile.side_effect = self.eggLinkInSitePackages75 eq_(egg_link_path(self.mock_dist), self.site_packages_egglink)76 def test_egglink_in_sitepkgs_venv_global(self):77 self.mock_virtualenv_no_global.return_value = False78 self.mock_running_under_virtualenv.return_value = True79 self.mock_isfile.side_effect = self.eggLinkInSitePackages80 eq_(egg_link_path(self.mock_dist), self.site_packages_egglink)81 ####################################82 ## egglink in usersite & sitepkgs ##83 ####################################84 def test_egglink_in_both_notvenv(self):85 self.mock_virtualenv_no_global.return_value = False86 self.mock_running_under_virtualenv.return_value = False87 self.mock_isfile.return_value = True88 eq_(egg_link_path(self.mock_dist), self.user_site_egglink)89 def test_egglink_in_both_venv_noglobal(self):90 self.mock_virtualenv_no_global.return_value = True91 self.mock_running_under_virtualenv.return_value = True92 self.mock_isfile.return_value = True93 eq_(egg_link_path(self.mock_dist), self.site_packages_egglink)94 def test_egglink_in_both_venv_global(self):95 self.mock_virtualenv_no_global.return_value = False96 self.mock_running_under_virtualenv.return_value = True97 self.mock_isfile.return_value = True98 eq_(egg_link_path(self.mock_dist), self.site_packages_egglink)99 ################100 ## no egglink ##101 ################102 def test_noegglink_in_sitepkgs_notvenv(self):103 self.mock_virtualenv_no_global.return_value = False104 self.mock_running_under_virtualenv.return_value = False105 self.mock_isfile.return_value = False106 eq_(egg_link_path(self.mock_dist), None)107 def test_noegglink_in_sitepkgs_venv_noglobal(self):108 self.mock_virtualenv_no_global.return_value = True109 self.mock_running_under_virtualenv.return_value = True110 self.mock_isfile.return_value = False111 eq_(egg_link_path(self.mock_dist), None)112 def test_noegglink_in_sitepkgs_venv_global(self):113 self.mock_virtualenv_no_global.return_value = False114 self.mock_running_under_virtualenv.return_value = True115 self.mock_isfile.return_value = False116 eq_(egg_link_path(self.mock_dist), None)117def test_Inf_greater():118 """Test Inf compares greater."""119 assert Inf > object()120def test_Inf_equals_Inf():121 """Test Inf compares greater."""122 assert Inf == Inf123class Tests_get_installed_distributions:124 """test util.get_installed_distributions"""125 workingset = [126 Mock(test_name="global"),127 Mock(test_name="editable"),128 Mock(test_name="normal")129 ]130 def dist_is_editable(self, dist):131 return dist.test_name == "editable"132 def dist_is_local(self, dist):133 return dist.test_name != "global"134 @patch('pip.util.dist_is_local')135 @patch('pip.util.dist_is_editable')136 @patch('pkg_resources.working_set', workingset)137 def test_editables_only(self, mock_dist_is_editable, mock_dist_is_local):138 mock_dist_is_editable.side_effect = self.dist_is_editable139 mock_dist_is_local.side_effect = self.dist_is_local140 dists = get_installed_distributions(editables_only=True)141 assert len(dists) == 1, dists142 assert dists[0].test_name == "editable"143 @patch('pip.util.dist_is_local')144 @patch('pip.util.dist_is_editable')145 @patch('pkg_resources.working_set', workingset)146 def test_exclude_editables(self, mock_dist_is_editable, mock_dist_is_local):147 mock_dist_is_editable.side_effect = self.dist_is_editable148 mock_dist_is_local.side_effect = self.dist_is_local149 dists = get_installed_distributions(include_editables=False)150 assert len(dists) == 1151 assert dists[0].test_name == "normal"152 @patch('pip.util.dist_is_local')153 @patch('pip.util.dist_is_editable')154 @patch('pkg_resources.working_set', workingset)155 def test_include_globals(self, mock_dist_is_editable, mock_dist_is_local):156 mock_dist_is_editable.side_effect = self.dist_is_editable157 mock_dist_is_local.side_effect = self.dist_is_local158 dists = get_installed_distributions(local_only=False)159 assert len(dists) == 3160def test_find_command_folder_in_path():161 """162 If a folder named e.g. 'git' is in PATH, and find_command is looking for163 the 'git' executable, it should not match the folder, but rather keep164 looking.165 """166 env = reset_env()167 mkdir('path_one')168 path_one = env.scratch_path/'path_one'169 mkdir(path_one/'foo')170 mkdir('path_two')171 path_two = env.scratch_path/'path_two'172 write_file(path_two/'foo', '# nothing')173 found_path = find_command('foo', map(str, [path_one, path_two]))174 assert found_path == path_two/'foo'175def test_does_not_find_command_because_there_is_no_path():176 """177 Test calling `pip.utils.find_command` when there is no PATH env variable178 """179 environ_before = os.environ180 os.environ = {}181 try:182 try:183 find_command('anycommand')184 except BadCommand:185 e = sys.exc_info()[1]186 assert e.args == ("Cannot find command 'anycommand'",)187 else:188 raise AssertionError("`find_command` should raise `BadCommand`")189 finally:190 os.environ = environ_before191@patch('os.pathsep', ':')192@patch('pip.util.get_pathext')193@patch('os.path.isfile')194def test_find_command_trys_all_pathext(mock_isfile, getpath_mock):195 """196 If no pathext should check default list of extensions, if file does not197 exist.198 """199 mock_isfile.return_value = False200 getpath_mock.return_value = os.pathsep.join([".COM", ".EXE"])201 paths = [os.path.join('path_one', f) for f in ['foo.com', 'foo.exe', 'foo']]202 expected = [((p,),) for p in paths]203 assert_raises(BadCommand, find_command, 'foo', 'path_one')204 assert mock_isfile.call_args_list == expected, "Actual: %s\nExpected %s" % (mock_isfile.call_args_list, expected)205 assert getpath_mock.called, "Should call get_pathext"206@patch('os.pathsep', ':')207@patch('pip.util.get_pathext')208@patch('os.path.isfile')209def test_find_command_trys_supplied_pathext(mock_isfile, getpath_mock):210 """211 If pathext supplied find_command should use all of its list of extensions to find file.212 """213 mock_isfile.return_value = False214 getpath_mock.return_value = ".FOO"215 pathext = os.pathsep.join([".RUN", ".CMD"])216 paths = [os.path.join('path_one', f) for f in ['foo.run', 'foo.cmd', 'foo']]217 expected = [((p,),) for p in paths]218 assert_raises(BadCommand, find_command, 'foo', 'path_one', pathext)219 assert mock_isfile.call_args_list == expected, "Actual: %s\nExpected %s" % (mock_isfile.call_args_list, expected)...
test_process_args.py
Source:test_process_args.py
1import unittest2from unittest.mock import patch, MagicMock3import src.md2site as md2site4import pathlib5class test_process_args(unittest.TestCase):6 @patch("os.path.isfile")7 @patch("os.path.isdir")8 def test_paths_only_valid_files(self, mock_isdir: MagicMock, mock_isfile: MagicMock):9 args = [10 "foo/bar.md",11 "foo/baz.md",12 "foo.md"13 ]14 mock_isfile.return_value = True15 mock_isdir.return_value = False16 paths, options = md2site.process_args(args)17 self.assertEqual(len(paths), len(args))18 self.assertEqual(len(options), 0)19 @patch("os.path.isfile")20 @patch("os.path.isdir")21 def test_paths_only_valid_directories(self, mock_isdir: MagicMock, mock_isfile: MagicMock):22 args = [23 "foo/bar/",24 "foo/baz/",25 "foo/"26 ]27 mock_isfile.return_value = False28 mock_isdir.return_value = True29 paths, options = md2site.process_args(args)30 self.assertEqual(len(paths), len(args))31 self.assertEqual(len(options), 0)32 @patch("os.path.isfile")33 @patch("os.path.isdir")34 def test_paths_only_valid_directories_and_files(self, mock_isdir: MagicMock, mock_isfile: MagicMock):35 args = [36 "foo/bar.md",37 "foo/baz.md",38 "foo.md",39 "foo/bar/",40 "foo/baz/",41 "foo/"42 ]43 mock_isfile.return_value = True44 mock_isdir.return_value = True45 paths, options = md2site.process_args(args)46 self.assertEqual(len(paths), len(args))47 self.assertEqual(len(options), 0)48 @patch("os.path.isfile")49 @patch("os.path.isdir")50 def test_invalid_path(self, mock_isdir: MagicMock, mock_isfile: MagicMock):51 arg = "foo/bar.md"52 mock_isfile.return_value = False53 mock_isdir.return_value = False54 with self.assertRaises(ValueError, msg="provided path is invalid: {}".format(arg)):55 md2site.process_args([arg])56 @patch("os.path.isfile")57 def test_template_file_option_with_valid_file(self, mock_isfile: MagicMock):58 template_file = "foo/bar.html"59 args = [60 "--template-file",61 template_file62 ]63 mock_isfile.return_value = True64 paths, options = md2site.process_args(args)65 self.assertEqual(len(paths), 0)66 self.assertEqual(len(options), 1)67 self.assertEqual(options.get("template_file"), template_file)68 @patch("os.path.isfile")69 def test_template_file_option_with_invalid_file(self, mock_isfile: MagicMock):70 template_file = "foo/bar.html"71 args = [72 "--template-file",73 template_file74 ]75 mock_isfile.return_value = False76 with self.assertRaises(ValueError, msg="path to template file is invalid"):77 md2site.process_args(args)78 def test_primary_lang_option_with_valid_value(self):79 primary_lang = "lang"80 args = [81 "--primary-lang",82 primary_lang83 ]84 paths, options = md2site.process_args(args)85 self.assertEqual(len(paths), 0)86 self.assertEqual(len(options), 1)87 self.assertEqual(options.get("primary_lang"), primary_lang)88 def test_primary_lang_option_with_invalid_value(self):89 primary_lang = "####"90 args = [91 "--primary-lang",92 primary_lang93 ]94 with self.assertRaises(ValueError, msg="primary language does not match to regex \"[a-zA-Z]+\""):95 md2site.process_args(args)96 def test_output_ext_option_with_valid_value(self):97 output_ext = "ext"98 args = [99 "--output-ext",100 output_ext101 ]102 paths, options = md2site.process_args(args)103 self.assertEqual(len(paths), 0)104 self.assertEqual(len(options), 1)105 self.assertEqual(options.get("output_ext"), output_ext)106 def test_output_ext_option_with_invalid_value(self):107 output_ext = "####"108 args = [109 "--output-ext",110 output_ext111 ]112 with self.assertRaises(ValueError, msg="output extension does not match to regex \"[a-zA-Z0-9]+\""):113 md2site.process_args(args)114 def test_output_directory_option_with_valid_path(self):115 output_directory = "foo/bar"116 args = [117 "--output-directory",118 output_directory119 ]120 paths, options = md2site.process_args(args)121 self.assertEqual(len(paths), 0)122 self.assertEqual(len(options), 1)123 self.assertEqual(options.get("output_directory"), output_directory)124 def test_multiple_options(self):125 output_directory = "foo/bar"126 primary_lang = "lang"127 output_ext = "ext"128 args = [129 "--output-directory",130 output_directory,131 "--primary-lang",132 primary_lang,133 "--output-ext",134 output_ext135 ]136 paths, options = md2site.process_args(args)137 self.assertEqual(len(paths), 0)138 self.assertEqual(len(options), 3)139 self.assertEqual(options.get("output_directory"), output_directory)140 self.assertEqual(options.get("output_ext"), output_ext)141 self.assertEqual(options.get("primary_lang"), primary_lang)142 @patch("os.path.isfile")143 @patch("os.path.isdir")144 def test_multiple_options_mixed_with_paths(self, mock_isdir: MagicMock, mock_isfile: MagicMock):145 output_directory = "foo/bar"146 primary_lang = "lang"147 output_ext = "ext"148 args = [149 "--output-directory",150 output_directory,151 "foo/bar",152 "--primary-lang",153 primary_lang,154 "foo/baz",155 "--output-ext",156 output_ext,157 "foo/"158 ]159 mock_isdir = True160 mock_isfile = False161 paths, options = md2site.process_args(args)162 self.assertEqual(len(paths), 3)163 self.assertEqual(len(options), 3)164 self.assertEqual(options.get("output_directory"), output_directory)165 self.assertEqual(options.get("output_ext"), output_ext)...
test_cisco_anyconnect.py
Source:test_cisco_anyconnect.py
1import os2import unittest3from cisco_anyconnect_cli.cisco_anyconnect import CiscoAnyConnect4from unittest.mock import patch5if os.name == 'nt':6 executable = "vpncli.exe"7elif os.name == 'posix':8 executable = "vpn"9class CiscoAnyConnectTest(unittest.TestCase):10 @patch('os.path.exists')11 @patch('os.path.isfile')12 def test_detect_binary_throws_exception_when_not_found(self, mock_isfile, mock_exists):13 mock_exists.side_effect = lambda path: False14 mock_isfile.side_effect = lambda file: False15 self.assertRaises(Exception, CiscoAnyConnect)16 @patch('os.path.isfile')17 def test_detect_binary_cwd(self, mock_isfile):18 expected = os.path.join(os.getcwd(), executable)19 mock_isfile.side_effect = lambda file: os.path.normpath(file) == os.path.normpath(expected)20 cisco = CiscoAnyConnect(None)21 print("Actual: " + cisco.bin)22 print("Expected: " + expected)23 assert cisco.bin == expected24 @patch('os.path.isfile')25 def test_detect_binary_ProgramFiles(self, mock_isfile):26 expected = os.path.join("C:\\Program Files\\Cisco\\Cisco AnyConnect Secure Mobility Client", executable)27 mock_isfile.side_effect = lambda file: os.path.normpath(file) == os.path.normpath(expected)28 cisco = CiscoAnyConnect(None)29 print("Actual: " + cisco.bin)30 print("Expected: " + expected)31 assert cisco.bin == expected32 @patch('os.path.isfile')33 def test_detect_binary_ProgramFilesX86(self, mock_isfile):34 expected = os.path.join("C:\\Program Files (x86)\\Cisco\\Cisco AnyConnect Secure Mobility Client", executable)35 mock_isfile.side_effect = lambda file: os.path.normpath(file) == os.path.normpath(expected)36 cisco = CiscoAnyConnect(None)37 print("Actual: " + cisco.bin)38 print("Expected: " + expected)39 assert cisco.bin == expected40 @patch('os.path.isfile')41 def test_detect_binary_ProgramFilesX86(self, mock_isfile):42 expected = os.path.join("/opt/cisco/anyconnect/bin", executable)43 mock_isfile.side_effect = lambda file: os.path.normpath(file) == os.path.normpath(expected)44 cisco = CiscoAnyConnect(None)45 print("Actual: " + cisco.bin)46 print("Expected: " + expected)47 assert cisco.bin == expected48 @patch('os.path.isfile')49 def test_detect_binary_given_path(self, mock_isfile):50 expected_dir = "c:\\my\\custom\\path"51 expected = os.path.join(expected_dir, executable)52 mock_isfile.side_effect = lambda path: path is not None and os.path.normpath(path) == os.path.normpath(expected)53 cisco = CiscoAnyConnect(expected_dir)54 print("Actual: " + cisco.bin)55 print("Expected: " + expected)56 assert cisco.bin == expected57 @patch('os.path.isfile')58 def test_detect_binary_given_file(self, mock_isfile):59 expected = os.path.join("c:\\my\\custom\\path", executable)60 mock_isfile.side_effect = lambda file: os.path.normpath(file) == os.path.normpath(expected)61 cisco = CiscoAnyConnect(expected)62 print("Actual: " + cisco.bin)63 print("Expected: " + expected)64 assert cisco.bin == expected65 @patch('os.path.isfile')66 @patch('shutil.which')67 def test_detect_binary_given_path_variable(self, mock_which, mock_isfile):68 expected = os.path.join("c:\\path", executable)69 mock_isfile.side_effect = lambda file: os.path.normpath(file) == os.path.normpath(expected)70 mock_which.side_effect = lambda path: expected71 cisco = CiscoAnyConnect(None)72 print("Actual: " + cisco.bin)73 print("Expected: " + expected)74 assert cisco.bin == expected75 @patch('os.path.isfile')76 @patch.dict(os.environ, {"CISCO_ANYCONNECT_HOME": "c:\\path"})77 def test_detect_binary_given_environment_variable(self, mock_isfile):78 print(os.environ.get("CISCO_ANYCONNECT_HOME"))79 expected = os.path.join("c:\\path", executable)80 def isfile(file):81 print(file)82 print(os.path.normpath(file))83 print(os.path.normpath(expected))84 return os.path.normpath(file) == os.path.normpath(expected)85 mock_isfile.side_effect = isfile86 cisco = CiscoAnyConnect(None)87 print("Actual: " + cisco.bin)88 print("Expected: " + expected)89 assert cisco.bin == expected90if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!