Best Python code snippet using nose
test_set_config.py
Source:test_set_config.py
1# Licensed under the Apache License, Version 2.0 (the "License");2# you may not use this file except in compliance with the License.3# You may obtain a copy of the License at4#5# http://www.apache.org/licenses/LICENSE-2.06#7# Unless required by applicable law or agreed to in writing, software8# distributed under the License is distributed on an "AS IS" BASIS,9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10# See the License for the specific language governing permissions and11# limitations under the License.12import collections13import copy14import imp15import json16import mock17import os.path18import sys19from oslotest import base20# nasty: to import set_config (not a part of the kolla package)21this_dir = os.path.dirname(sys.modules[__name__].__file__)22set_configs_file = os.path.abspath(23 os.path.join(this_dir, '..',24 'docker', 'base', 'set_configs.py'))25set_configs = imp.load_source('set_configs', set_configs_file)26class LoadFromFile(base.BaseTestCase):27 def test_load_ok(self):28 in_config = json.dumps({'command': '/bin/true',29 'config_files': {}})30 mo = mock.mock_open(read_data=in_config)31 with mock.patch.object(set_configs, 'open', mo):32 config = set_configs.load_config()33 set_configs.copy_config(config)34 self.assertEqual([35 mock.call('/var/lib/kolla/config_files/config.json'),36 mock.call().__enter__(),37 mock.call().read(),38 mock.call().__exit__(None, None, None),39 mock.call('/run_command', 'w+'),40 mock.call().__enter__(),41 mock.call().write(u'/bin/true'),42 mock.call().__exit__(None, None, None)], mo.mock_calls)43class LoadFromEnv(base.BaseTestCase):44 def test_load_ok(self):45 in_config = json.dumps({'command': '/bin/true',46 'config_files': {}})47 mo = mock.mock_open()48 with mock.patch.object(set_configs, 'open', mo):49 with mock.patch.dict('os.environ', {'KOLLA_CONFIG': in_config}):50 config = set_configs.load_config()51 set_configs.copy_config(config)52 self.assertEqual([mock.call('/run_command', 'w+'),53 mock.call().__enter__(),54 mock.call().write(u'/bin/true'),55 mock.call().__exit__(None, None, None)],56 mo.mock_calls)57FAKE_CONFIG_FILES = [58 set_configs.ConfigFile(59 '/var/lib/kolla/config_files/bar.conf',60 '/foo/bar.conf', 'user1', '0644')61]62FAKE_CONFIG_FILE = FAKE_CONFIG_FILES[0]63class ConfigFileTest(base.BaseTestCase):64 @mock.patch('os.path.exists', return_value=False)65 def test_delete_path_not_exists(self, mock_exists):66 config_file = copy.deepcopy(FAKE_CONFIG_FILE)67 config_file._delete_path(config_file.dest)68 mock_exists.assert_called_with(config_file.dest)69 @mock.patch('os.path.exists', return_value=True)70 @mock.patch('os.path.isdir', return_value=True)71 @mock.patch('shutil.rmtree')72 def test_delete_path_exist_dir(self,73 mock_rmtree,74 mock_isdir,75 mock_exists):76 config_file = copy.deepcopy(FAKE_CONFIG_FILE)77 config_file._delete_path(config_file.dest)78 mock_exists.assert_called_with(config_file.dest)79 mock_isdir.assert_called_with(config_file.dest)80 mock_rmtree.assert_called_with(config_file.dest)81 @mock.patch('os.path.exists', return_value=True)82 @mock.patch('os.path.isdir', return_value=False)83 @mock.patch('os.remove')84 def test_delete_path_exist_file(self,85 mock_remove,86 mock_isdir,87 mock_exists):88 config_file = copy.deepcopy(FAKE_CONFIG_FILE)89 config_file._delete_path(config_file.dest)90 mock_exists.assert_called_with(config_file.dest)91 mock_isdir.assert_called_with(config_file.dest)92 mock_remove.assert_called_with(config_file.dest)93 @mock.patch('os.chmod')94 @mock.patch('os.chown')95 @mock.patch('pwd.getpwnam')96 def test_set_permission(self,97 mock_getpwnam,98 mock_chown,99 mock_chmod):100 User = collections.namedtuple('User', ['pw_uid', 'pw_gid'])101 user = User(3333, 4444)102 mock_getpwnam.return_value = user103 config_file = copy.deepcopy(FAKE_CONFIG_FILE)104 config_file._set_permission(config_file.dest)105 mock_getpwnam.assert_called_with(config_file.owner)106 mock_chown.assert_called_with(config_file.dest, 3333, 4444)107 mock_chmod.assert_called_with(config_file.dest, 420)108 @mock.patch('glob.glob', return_value=[])109 def test_copy_no_source_not_optional(self,110 mock_glob):111 config_file = copy.deepcopy(FAKE_CONFIG_FILE)112 self.assertRaises(set_configs.MissingRequiredSource,113 config_file.copy)114 @mock.patch('glob.glob', return_value=[])115 def test_copy_no_source_optional(self, mock_glob):116 config_file = copy.deepcopy(FAKE_CONFIG_FILE)117 config_file.optional = True118 config_file.copy()119 mock_glob.assert_called_with(config_file.source)120 @mock.patch.object(set_configs.ConfigFile, '_copy_file')121 @mock.patch('os.path.isdir', return_value=False)122 @mock.patch.object(set_configs.ConfigFile, '_create_parent_dirs')123 @mock.patch.object(set_configs.ConfigFile, '_delete_path')124 @mock.patch('glob.glob')125 def test_copy_one_source_file(self, mock_glob, mock_delete_path,126 mock_create_parent_dirs, mock_isdir,127 mock_copy_file):128 config_file = copy.deepcopy(FAKE_CONFIG_FILE)129 mock_glob.return_value = [config_file.source]130 config_file.copy()131 mock_glob.assert_called_with(config_file.source)132 mock_delete_path.assert_called_with(config_file.dest)133 mock_create_parent_dirs.assert_called_with(config_file.dest)134 mock_isdir.assert_called_with(config_file.source)135 mock_copy_file.assert_called_with(config_file.source,136 config_file.dest)137 @mock.patch.object(set_configs.ConfigFile, '_copy_dir')138 @mock.patch('os.path.isdir', return_value=True)139 @mock.patch.object(set_configs.ConfigFile, '_create_parent_dirs')140 @mock.patch.object(set_configs.ConfigFile, '_delete_path')141 @mock.patch('glob.glob')142 def test_copy_one_source_dir(self, mock_glob, mock_delete_path,143 mock_create_parent_dirs, mock_isdir,144 mock_copy_dir):145 config_file = copy.deepcopy(FAKE_CONFIG_FILE)146 mock_glob.return_value = [config_file.source]147 config_file.copy()148 mock_glob.assert_called_with(config_file.source)149 mock_delete_path.assert_called_with(config_file.dest)150 mock_create_parent_dirs.assert_called_with(config_file.dest)151 mock_isdir.assert_called_with(config_file.source)152 mock_copy_dir.assert_called_with(config_file.source,153 config_file.dest)154 @mock.patch.object(set_configs.ConfigFile, '_copy_file')155 @mock.patch('os.path.isdir', return_value=False)156 @mock.patch.object(set_configs.ConfigFile, '_create_parent_dirs')157 @mock.patch.object(set_configs.ConfigFile, '_delete_path')158 @mock.patch('glob.glob')159 def test_copy_glob_source_file(self, mock_glob, mock_delete_path,160 mock_create_parent_dirs, mock_isdir,161 mock_copy_file):162 config_file = set_configs.ConfigFile(163 '/var/lib/kolla/config_files/bar.*', '/foo/', 'user1', '0644')164 mock_glob.return_value = ['/var/lib/kolla/config_files/bar.conf',165 '/var/lib/kolla/config_files/bar.yml']166 config_file.copy()167 mock_glob.assert_called_with(config_file.source)168 self.assertEqual(mock_delete_path.mock_calls,169 [mock.call('/foo/bar.conf'),170 mock.call('/foo/bar.yml')])171 self.assertEqual(mock_create_parent_dirs.mock_calls,172 [mock.call('/foo/bar.conf'),173 mock.call('/foo/bar.yml')])174 self.assertEqual(mock_isdir.mock_calls,175 [mock.call('/var/lib/kolla/config_files/bar.conf'),176 mock.call('/var/lib/kolla/config_files/bar.yml')])177 self.assertEqual(mock_copy_file.mock_calls,178 [mock.call('/var/lib/kolla/config_files/bar.conf',179 '/foo/bar.conf'),180 mock.call('/var/lib/kolla/config_files/bar.yml',181 '/foo/bar.yml')])182 @mock.patch.object(set_configs.ConfigFile, '_cmp_file')183 @mock.patch('os.path.isdir', return_value=False)184 @mock.patch('glob.glob')185 def test_check_glob_source_file(self, mock_glob, mock_isdir,186 mock_cmp_file):187 config_file = set_configs.ConfigFile(188 '/var/lib/kolla/config_files/bar.*', '/foo/', 'user1', '0644')189 mock_glob.return_value = ['/var/lib/kolla/config_files/bar.conf',190 '/var/lib/kolla/config_files/bar.yml']191 mock_cmp_file.return_value = True192 config_file.check()193 self.assertEqual(mock_isdir.mock_calls,194 [mock.call('/var/lib/kolla/config_files/bar.conf'),195 mock.call('/var/lib/kolla/config_files/bar.yml')])196 self.assertEqual(mock_cmp_file.mock_calls,197 [mock.call('/var/lib/kolla/config_files/bar.conf',198 '/foo/bar.conf'),199 mock.call('/var/lib/kolla/config_files/bar.yml',200 '/foo/bar.yml')])201 @mock.patch.object(set_configs.ConfigFile, '_cmp_file')202 @mock.patch('os.path.isdir', return_value=False)203 @mock.patch('glob.glob')204 def test_check_glob_source_file_no_equal(self, mock_glob, mock_isdir,205 mock_cmp_file):206 config_file = set_configs.ConfigFile(207 '/var/lib/kolla/config_files/bar.*', '/foo/', 'user1', '0644')208 mock_glob.return_value = ['/var/lib/kolla/config_files/bar.conf',209 '/var/lib/kolla/config_files/bar.yml']210 mock_cmp_file.side_effect = [True, False]211 self.assertRaises(set_configs.ConfigFileBadState,212 config_file.check)213 self.assertEqual(mock_isdir.mock_calls,214 [mock.call('/var/lib/kolla/config_files/bar.conf'),215 mock.call('/var/lib/kolla/config_files/bar.yml')])216 self.assertEqual(mock_cmp_file.mock_calls,217 [mock.call('/var/lib/kolla/config_files/bar.conf',218 '/foo/bar.conf'),219 mock.call('/var/lib/kolla/config_files/bar.yml',...
test_globmatch.py
Source:test_globmatch.py
1# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-2#3# Copyright 2002 Ben Escoto <ben@emerose.org>4# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>5# Copyright 2014 Aaron Whitehouse <aaron@whitehouse.kiwi.nz>6#7# This file is part of duplicity.8#9# Duplicity is free software; you can redistribute it and/or modify it10# under the terms of the GNU General Public License as published by the11# Free Software Foundation; either version 2 of the License, or (at your12# option) any later version.13#14# Duplicity is distributed in the hope that it will be useful, but15# WITHOUT ANY WARRANTY; without even the implied warranty of16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU17# General Public License for more details.18#19# You should have received a copy of the GNU General Public License20# along with duplicity; if not, write to the Free Software Foundation,21# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA22import sys23from duplicity.globmatch import *24from duplicity.path import *25from . import UnitTestCase26from mock import patch27import unittest28class MatchingTest(UnitTestCase):29 """Test matching of file names against various selection functions"""30 def test_glob_re(self):31 """test_glob_re - test translation of shell pattern to regular exp"""32 assert glob_to_regex("hello") == "hello"33 assert glob_to_regex(".e?ll**o") == "\\.e[^/]ll.*o"34 r = glob_to_regex("[abc]el[^de][!fg]h")35 assert r == "[abc]el[^de][^fg]h", r36 r = glob_to_regex("/usr/*/bin/")37 assert r == "\\/usr\\/[^/]*\\/bin\\/", r38 assert glob_to_regex("[a.b/c]") == "[a.b/c]"39 r = glob_to_regex("[a*b-c]e[!]]")40 assert r == "[a*b-c]e[^]]", r41class TestDoubleAsteriskOnIncludesExcludes(UnitTestCase):42 """Test ** on includes and exclude patterns"""43 def test_double_asterisk_include(self):44 """Test a few globbing patterns, including **"""45 self.assertEqual(46 path_matches_glob_fn("**", 1)(Path("foo.txt")), 1)47 with patch('duplicity.path.Path.isdir') as mock_isdir:48 mock_isdir.return_value = True49 self.assertEqual(50 path_matches_glob_fn("**", 1)(Path("folder")), 1)51 def test_double_asterisk_extension_include(self):52 """Test **.py"""53 self.assertEqual(54 path_matches_glob_fn("**.py", 1)(Path("what/ever.py")), 1)55 self.assertEqual(56 path_matches_glob_fn("**.py", 1)(Path("what/ever.py/foo")), 1)57 with patch('duplicity.path.Path.isdir') as mock_isdir:58 mock_isdir.return_value = True59 self.assertEqual(60 path_matches_glob_fn("**.py", 1)(Path("foo")), 2)61 self.assertEqual(62 path_matches_glob_fn("**.py", 1)(Path("usr/local/bin")), 2)63 self.assertEqual(64 path_matches_glob_fn("**.py", 1)(Path("/usr/local/bin")), 2)65class TestTrailingSlash(UnitTestCase):66 """Test glob matching where the glob has a trailing slash"""67 def test_trailing_slash_matches_only_dirs(self):68 """Test matching where glob includes a trailing slash"""69 with patch('duplicity.path.Path.isdir') as mock_isdir:70 mock_isdir.return_value = True71 self.assertEqual(72 path_matches_glob_fn("fold*/", 1)(Path("folder")), 1)73 # Test the file named "folder" is not included if it is not a dir74 mock_isdir.return_value = False75 self.assertEqual(76 path_matches_glob_fn("fold*/", 1)(Path("folder")), None)77 # Test the file named "folder" is not included if it is not a dir78 mock_isdir.return_value = False79 self.assertEqual(80 path_matches_glob_fn("folder/", 1)(Path("folder")), None)81 mock_isdir.return_value = False82 self.assertEqual(83 path_matches_glob_fn("fo*/", 1)(Path("foo.txt")), None)84 def test_included_files_are_matched_no_slash(self):85 """Test that files within an included folder are matched"""86 with patch('duplicity.path.Path.isdir') as mock_isdir:87 mock_isdir.return_value = False88 self.assertEqual(89 path_matches_glob_fn("fold*", 1)(Path("folder/file.txt")), 1)90 with patch('duplicity.path.Path.isdir') as mock_isdir:91 mock_isdir.return_value = False92 self.assertEqual(93 path_matches_glob_fn("fold*", 1)(Path("folder/2/file.txt")), 1)94 def test_included_files_are_matched_no_slash_2(self):95 """Test that files within an included folder are matched"""96 with patch('duplicity.path.Path.isdir') as mock_isdir:97 mock_isdir.return_value = False98 self.assertEqual(99 path_matches_glob_fn("folder", 1)(Path("folder/file.txt")), 1)100 with patch('duplicity.path.Path.isdir') as mock_isdir:101 mock_isdir.return_value = False102 self.assertEqual(103 path_matches_glob_fn("folder/2", 1)(Path("folder/2/file.txt")), 1)104 def test_included_files_are_matched_slash(self):105 """Test that files within an included folder are matched with /"""106 # Bug #1624725107 # https://bugs.launchpad.net/duplicity/+bug/1624725108 with patch('duplicity.path.Path.isdir') as mock_isdir:109 mock_isdir.return_value = False110 self.assertEqual(111 path_matches_glob_fn("folder/", 1)(Path("folder/file.txt")), 1)112 def test_included_files_are_matched_slash_2(self):113 """Test that files within an included folder are matched with /"""114 # Bug #1624725115 # https://bugs.launchpad.net/duplicity/+bug/1624725116 with patch('duplicity.path.Path.isdir') as mock_isdir:117 mock_isdir.return_value = False118 self.assertEqual(119 path_matches_glob_fn("testfiles/select2/1/1sub1/1sub1sub1/", 1)120 (Path("testfiles/select2/1/1sub1/1sub1sub1/1sub1sub1_file.txt")121 ), 1)122 def test_included_files_are_matched_slash_2_parents(self):123 """Test that duplicity will scan parent of glob/"""124 # Bug #1624725125 # https://bugs.launchpad.net/duplicity/+bug/1624725126 with patch('duplicity.path.Path.isdir') as mock_isdir:127 mock_isdir.return_value = True128 self.assertEqual(129 path_matches_glob_fn("testfiles/select2/1/1sub1/1sub1sub1/", 1)130 (Path("testfiles/select2/1/1sub1/1sub1sub1")131 ), 1)132 self.assertEqual(133 path_matches_glob_fn("testfiles/select2/1/1sub1/1sub1sub1/", 1)134 (Path("testfiles/select2/1/1sub1")135 ), 2)136 def test_included_files_are_matched_slash_wildcard(self):137 """Test that files within an included folder are matched with /"""138 # Bug #1624725139 # https://bugs.launchpad.net/duplicity/+bug/1624725140 with patch('duplicity.path.Path.isdir') as mock_isdir:141 mock_isdir.return_value = False142 self.assertEqual(143 path_matches_glob_fn("fold*/", 1)(Path("folder/file.txt")), 1)144 #145 # def test_slash_matches_everything(self):146 # """Test / matches everything"""147 # # ToDo: Not relevant at this stage, as "/" would not go through148 # # globmatch because it has no special characters, but it should be149 # # made to work150 # with patch('duplicity.path.Path.isdir') as mock_isdir:151 # mock_isdir.return_value = True152 # self.assertEqual(153 # path_matches_glob_fn("/",154 # 1)(Path("/tmp/testfiles/select/1/2")), 1)155 # self.assertEqual(156 # path_matches_glob_fn("/",157 # 1)(Path("/test/random/path")), 1)158 # self.assertEqual(159 # path_matches_glob_fn("/",160 # 1)(Path("/")), 1)161 # self.assertEqual(162 # path_matches_glob_fn("/",163 # 1)(Path("/var/log")), 1)164 # self.assertEqual(165 # path_matches_glob_fn("/",166 # 1)(Path("/var/log/log.txt")), 1)167 def test_slash_star_scans_folder(self):168 """Test that folder/* scans folder/"""169 # This behaviour is a bit ambiguous - either include or scan could be170 # argued as most appropriate here, but only an empty folder is at stake171 # so long as test_slash_star_includes_folder_contents passes.172 with patch('duplicity.path.Path.isdir') as mock_isdir:173 mock_isdir.return_value = True174 self.assertEqual(175 path_matches_glob_fn("folder/*", 1)(Path("folder")), 2)176 def test_slash_star_includes_folder_contents(self):177 """Test that folder/* includes folder contents"""178 self.assertEqual(path_matches_glob_fn("folder/*", 1)179 (Path("folder/file.txt")), 1)180 self.assertEqual(path_matches_glob_fn("folder/*", 1)181 (Path("folder/other_file.log")), 1)182 def test_slash_star_star_includes_folder(self):183 """Test that folder/** includes folder/"""184 with patch('duplicity.path.Path.isdir') as mock_isdir:185 mock_isdir.return_value = True186 def test_simple_trailing_slash_match(self):187 """Test that a normal folder string ending in / matches that path"""188 with patch('duplicity.path.Path.isdir') as mock_isdir:189 mock_isdir.return_value = True190 test_path = "testfiles/select/1/2/1"191 self.assertEqual(192 path_matches_glob_fn(test_path, 1)(Path(test_path)), 1)193 def test_double_asterisk_string_slash(self):194 """Test string starting with ** and ending in /"""195 with patch('duplicity.path.Path.isdir') as mock_isdir:196 mock_isdir.return_value = True197 self.assertEqual(198 path_matches_glob_fn("**/1/2/",199 1)(Path("testfiles/select/1/2")), 1)200 def test_string_double_asterisk_string_slash(self):201 """Test string ** string /"""202 with patch('duplicity.path.Path.isdir') as mock_isdir:203 mock_isdir.return_value = True204 self.assertEqual(205 path_matches_glob_fn("testfiles**/2/",206 1)(Path("testfiles/select/1/2")), 1)207class TestDoubleAsterisk(UnitTestCase):208 """Test glob matching where the glob finishes with a **"""209 def test_simple_trailing_slash_match(self):210 """Test that a folder string ending in /** matches that path"""211 with patch('duplicity.path.Path.isdir') as mock_isdir:212 mock_isdir.return_value = True213 self.assertEqual(214 path_matches_glob_fn("/test/folder/**", 1)(215 Path("/test/foo")), None)216 def test_simple_trailing_slash_match_2(self):217 """Test folder string ending in */**"""218 with patch('duplicity.path.Path.isdir') as mock_isdir:219 mock_isdir.return_value = True220 self.assertEqual(221 path_matches_glob_fn("fold*/**", 1)(...
arguments_test.py
Source:arguments_test.py
1"""Test suite for arguments.py"""2from mock import patch3import pytest4from ocrcode import arguments5class TestArgumentParser:6 """ Test class for arguments.argument_parser """7 @pytest.mark.parametrize(8 "params_in, expected",9 [10 (["file.jpg"], ["file.jpg"]),11 (["file.jpg", "-v"], ["file.jpg"]),12 (["file.jpg", "--verbose"], ["file.jpg"]),13 (["file.jpg", "-s", "dir"], ["file.jpg"]),14 (["file.jpg", "--save", "dir"], ["file.jpg"]),15 (["file.jpg", "-s", "dir", "-v"], ["file.jpg"]),16 (["file.jpg", "file2.jpg"], ["file.jpg", "file2.jpg"]),17 ([], []),18 (["-v"], []),19 (["-s", "dir", "-v", "-t", "dir2"], []),20 ],21 )22 def test_files_to_process_added_to_list(self, params_in, expected):23 files, _, _, _ = arguments.argument_parser(params_in)24 assert files == expected25 @pytest.mark.parametrize(26 "params_in, expected",27 [28 (["file.jpg", "-v"], None),29 (["file.jpg", "--verbose"], None),30 (["file.jpg", "-s", "dir", "-v"], "dir"),31 (["file.jpg", "-s", "dir", "--verbose", "-t", "dir2"], "dir"),32 (["file.jpg", "--save", "dir"], "dir"),33 (["file.jpg"], None),34 ],35 )36 def test_save_flag_returns_save_path_if_given(self, params_in, expected):37 _, save_path, _, _ = arguments.argument_parser(params_in)38 if save_path is None:39 assert save_path is expected40 else:41 assert save_path == expected42 @pytest.mark.parametrize(43 "params_in, expected",44 [45 (["file.jpg", "-v"], True),46 (["file.jpg", "--verbose"], True),47 (["file.jpg", "-s", "dir", "-v"], True),48 (["file.jpg", "-s", "dir", "--verbose"], True),49 (["file.jpg", "-s", "dir", "-t", "dir"], False),50 (["file.jpg"], False),51 ],52 )53 def test_verbose_flag_returns_verbose_true(self, params_in, expected):54 _, _, verbose, _ = arguments.argument_parser(params_in)55 assert verbose == expected56 @pytest.mark.parametrize(57 "params_in, expected",58 [59 (["file.jpg", "-v"], None),60 (["file.jpg", "-s", "dir", "--verbose"], None),61 (["file.jpg", "--tesseract", "dir"], "dir"),62 (["file.jpg", "-t", "dir"], "dir"),63 (["file.jpg", "-s", "dir", "--verbose", "-t", "dir"], "dir"),64 ],65 )66 def test_tesseract_flag_returns_tesseract_path(self, params_in, expected):67 _, _, _, tesseract = arguments.argument_parser(params_in)68 assert tesseract == expected69class TestPathsToFiles:70 """ Test class for arguments.paths_to_files """71 @patch("os.path.isdir")72 @patch("os.path.isfile")73 def test_returns_empty_list_for_invalid_file(self, mock_isfile, mock_isdir):74 mock_isdir.return_value = False75 mock_isfile.return_value = False76 with pytest.raises(FileNotFoundError):77 arguments.paths_to_files(["invalid"])78 @patch("os.path.isdir")79 @patch("os.path.isfile")80 def test_raises_error_if_not_image(self, mock_isfile, mock_isdir):81 mock_isdir.return_value = False82 mock_isfile.return_value = True83 with pytest.raises(FileNotFoundError):84 arguments.paths_to_files(["valid.txt"])85 @patch("os.path.isdir")86 @patch("os.path.isfile")87 def test_returns_list_if_valid_image(self, mock_isfile, mock_isdir):88 mock_isdir.return_value = False89 mock_isfile.return_value = True90 assert arguments.paths_to_files(["valid.jpg"]) == ["valid.jpg"]91 @patch("os.listdir")92 @patch("os.path.isdir")93 @patch("os.path.isfile")94 def test_returns_list_if_valid_dir(95 self, mock_isfile, mock_isdir, mock_listdir,96 ):97 mock_isdir.return_value = True98 mock_isfile.return_value = True99 mock_listdir.return_value = ["valid.jpg", "other.txt"]100 assert arguments.paths_to_files(["dir/"]) == ["dir/valid.jpg"]101 @patch("os.listdir")102 @patch("os.path.isdir")103 @patch("os.path.isfile")104 def test_returns_empty_list_if_valid_dir_but_not_image(105 self, mock_isfile, mock_isdir, mock_listdir,106 ):107 mock_isdir.return_value = True108 mock_isfile.return_value = True109 mock_listdir.return_value = ["valid.txt"]110 with pytest.raises(FileNotFoundError):111 arguments.paths_to_files(["dir/"])112class TestValidateSave:113 """ Test class for arguments.validate_save """114 @patch("os.path.isdir")115 @patch("os.getcwd")116 def test_returns_none_when_no_save(self, mock_getcwd, mock_isdir):117 mock_getcwd.return_value = "cwd"118 mock_isdir.return_value = False119 assert arguments.validate_save(save_path=None) is None120 @patch("os.path.isdir")121 @patch("os.getcwd")122 def test_returns_cwd_when_no_parameter(self, mock_getcwd, mock_isdir):123 mock_getcwd.return_value = "cwd"124 mock_isdir.return_value = False125 assert arguments.validate_save(save_path="||cwd||") == "cwd"126 @patch("os.path.isdir")127 @patch("os.getcwd")128 def test_returns_valid_path(self, mock_getcwd, mock_isdir):129 mock_getcwd.return_value = "cwd"130 mock_isdir.return_value = True131 assert arguments.validate_save(save_path="valid") == "valid"132 @patch("os.path.isdir")133 @patch("os.getcwd")134 def test_raises_exception_for_invalid_path(self, mock_getcwd, mock_isdir):135 mock_getcwd.return_value = "cwd"136 mock_isdir.return_value = False137 with pytest.raises(Exception):138 arguments.validate_save(save_path="invalid")139class TestValidateTesseract:140 """ Test class for arguments.validate_tesseract """141 @patch("os.path.isfile")142 def test_returns_none_when_passed_none(self, mock_isfile):143 mock_isfile.return_value = False144 assert arguments.validate_tesseract(None) is None145 @patch("os.path.isfile")146 def test_returns_valid_tesseract_path(self, mock_isfile):147 mock_isfile.return_value = True148 input = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"149 expected = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"150 assert arguments.validate_tesseract(input) == expected151 @patch("os.path.isfile")152 def test_raises_error_for_invalid_path(self, mock_isfile):153 mock_isfile.return_value = False154 with pytest.raises(FileNotFoundError):155 arguments.validate_tesseract("invalid")156 @patch("os.path.isfile")157 def test_raises_error_for_non_tesseract_path(self, mock_isfile):158 mock_isfile.return_value = True159 with pytest.raises(FileNotFoundError):...
config_validator_scanner_test.py
Source:config_validator_scanner_test.py
1# Copyright 2020 The Forseti Security Authors. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14import unittest.mock as mock15from unittest.mock import patch16from tests.unittest_utils import ForsetiTestCase17from google.cloud.forseti.scanner.scanners.config_validator_scanner import (18 ConfigValidatorScanner)19from google.cloud.forseti.scanner.scanners.config_validator_util import (20 errors)21class ConfigValidatorScannerTest(ForsetiTestCase):22 """Tests for the Config Validator Scanner."""23 def setUp(self):24 self.scanner = ConfigValidatorScanner({},25 {},26 mock.MagicMock(),27 'ScannerBuilderTestModel',28 '20201237T121212Z',29 '')30 @patch('os.listdir')31 @patch('os.path.isdir')32 def test_verify_policy_library_empty_constraints_raises_exception(self,33 mock_isdir,34 mock_listdir):35 mock_isdir.side_effect = [True, True, True]36 mock_listdir.side_effect = [[], ['file1']]37 self.assertRaises(errors.ConfigValidatorPolicyLibraryError, self.scanner.verify_policy_library)38 self.assertEqual(mock_listdir.call_count, 1)39 @patch('os.listdir')40 @patch('os.path.isdir')41 def test_verify_policy_library_empty_lib_raises_exception(self,42 mock_isdir,43 mock_listdir):44 mock_isdir.side_effect = [True, True, True]45 mock_listdir.side_effect = [['file1'], []]46 self.assertRaises(errors.ConfigValidatorPolicyLibraryError, self.scanner.verify_policy_library)47 self.assertEqual(mock_listdir.call_count, 2)48 @patch('os.listdir')49 @patch('os.path.isdir')50 def test_verify_policy_library_missing_constraints_raises_exception(self,51 mock_isdir,52 mock_listdir):53 mock_isdir.side_effect = [True, False, True]54 mock_listdir.side_effect = [['file1'], ['file1']]55 self.assertRaises(errors.ConfigValidatorPolicyLibraryError, self.scanner.verify_policy_library)56 self.assertEqual(mock_isdir.call_count, 2)57 @patch('os.listdir')58 @patch('os.path.isdir')59 def test_verify_policy_library_missing_lib_raises_exception(self,60 mock_isdir,61 mock_listdir):62 mock_isdir.side_effect = [True, True, False]63 mock_listdir.side_effect = [['file1'], ['file1']]64 self.assertRaises(errors.ConfigValidatorPolicyLibraryError, self.scanner.verify_policy_library)65 self.assertEqual(mock_isdir.call_count, 3)66 @patch('os.listdir')67 @patch('os.path.isdir')68 def test_verify_policy_library_missing_library_raises_exception(self,69 mock_isdir,70 mock_listdir):71 mock_isdir.side_effect = [False, True, True]72 mock_listdir.side_effect = [['file1'], ['file1']]73 self.assertRaises(errors.ConfigValidatorPolicyLibraryError, self.scanner.verify_policy_library)74 self.assertEqual(mock_isdir.call_count, 1)75 @patch('os.listdir')76 @patch('os.path.isdir')77 def test_verify_policy_library_success(self, mock_isdir, mock_listdir):78 mock_listdir.side_effect = [['file1'], ['file1']]79 mock_isdir.side_effect = [True, True, True]80 self.scanner.verify_policy_library()81 self.assertEqual(mock_listdir.call_count, 2)...
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!!