How to use mock_exists method in Nose

Best Python code snippet using nose

ndk_stack_unittest.py

Source:ndk_stack_unittest.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright (C) 2019 The Android Open Source Project4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16#17"""Unittests for ndk-stack.py"""18from __future__ import print_function19import os.path20import sys21import textwrap22import unittest23from unittest import mock24from unittest.mock import patch25try:26 # Python 227 from cStringIO import StringIO28except ModuleNotFoundError: # pylint:disable=undefined-variable29 # Python 330 from io import StringIO31sys.path.insert(0, '../..')32ndk_stack = __import__('ndk-stack')33@patch('os.path.exists')34class PathTests(unittest.TestCase):35 """Tests of find_llvm_symbolizer() and find_readelf()."""36 def setUp(self):37 self.ndk_paths = ('/ndk_fake', '/ndk_fake/bin', 'linux-x86_64')38 exe_suffix = '.EXE' if os.name == 'nt' else ''39 self.llvm_symbolizer = 'llvm-symbolizer' + exe_suffix40 self.readelf = 'readelf' + exe_suffix41 def test_find_llvm_symbolizer_in_prebuilt(self, mock_exists):42 expected_path = os.path.join('/ndk_fake', 'toolchains', 'llvm',43 'prebuilt', 'linux-x86_64', 'bin',44 self.llvm_symbolizer)45 mock_exists.return_value = True46 self.assertEqual(expected_path,47 ndk_stack.find_llvm_symbolizer(*self.ndk_paths))48 mock_exists.assert_called_once_with(expected_path)49 def test_find_llvm_symbolizer_in_standalone_toolchain(self, mock_exists):50 prebuilt_path = os.path.join('/ndk_fake', 'toolchains', 'llvm',51 'prebuilt', 'linux-x86_64', 'bin',52 self.llvm_symbolizer)53 expected_path = os.path.join('/ndk_fake', 'bin', self.llvm_symbolizer)54 mock_exists.side_effect = [False, True]55 self.assertEqual(expected_path,56 ndk_stack.find_llvm_symbolizer(*self.ndk_paths))57 mock_exists.assert_has_calls(58 [mock.call(prebuilt_path),59 mock.call(expected_path)])60 def test_llvm_symbolizer_not_found(self, mock_exists):61 mock_exists.return_value = False62 with self.assertRaises(OSError) as cm:63 ndk_stack.find_llvm_symbolizer(*self.ndk_paths)64 self.assertEqual('Unable to find llvm-symbolizer', str(cm.exception))65 def test_find_readelf_in_prebuilt(self, mock_exists):66 expected_path = os.path.join(67 '/ndk_fake', 'toolchains', 'llvm', 'prebuilt', 'linux-x86_64',68 'x86_64-linux-android', 'bin', self.readelf)69 mock_exists.return_value = True70 self.assertEqual(expected_path,71 ndk_stack.find_readelf(*self.ndk_paths))72 mock_exists.assert_called_once_with(expected_path)73 def test_find_readelf_in_prebuilt_arm(self, mock_exists):74 expected_path = os.path.join(75 '/ndk_fake', 'toolchains', 'llvm', 'prebuilt', 'linux-arm',76 'arm-linux-androideabi', 'bin', self.readelf)77 mock_exists.return_value = True78 self.assertEqual(79 expected_path,80 ndk_stack.find_readelf('/ndk_fake', '/ndk_fake/bin', 'linux-arm'))81 mock_exists.assert_called_once_with(expected_path)82 def test_find_readelf_in_standalone_toolchain(self, mock_exists):83 for arch in [84 'aarch64-linux-android', 'arm-linux-androideabi',85 'i686-linux-android', 'x86_64-linux-android'86 ]:87 mock_exists.reset_mock()88 expected_path = os.path.join('/ndk_fake', arch, 'bin',89 self.readelf)90 mock_exists.side_effect = [False, True]91 os.path.exists = lambda path, exp=expected_path: path == exp92 self.assertEqual(expected_path,93 ndk_stack.find_readelf(*self.ndk_paths))94 def test_readelf_not_found(self, mock_exists):95 mock_exists.return_value = False96 self.assertFalse(ndk_stack.find_readelf(*self.ndk_paths))97class FrameTests(unittest.TestCase):98 """Test parsing of backtrace lines."""99 def test_line_with_map_name(self):100 line = ' #14 pc 00001000 /fake/libfake.so'101 frame_info = ndk_stack.FrameInfo.from_line(line)102 self.assertTrue(frame_info)103 self.assertEqual('#14', frame_info.num)104 self.assertEqual('00001000', frame_info.pc)105 self.assertEqual('/fake/libfake.so', frame_info.tail)106 self.assertEqual('/fake/libfake.so', frame_info.elf_file)107 self.assertFalse(frame_info.offset)108 self.assertFalse(frame_info.container_file)109 self.assertFalse(frame_info.build_id)110 def test_line_with_function(self):111 line = ' #08 pc 00001040 /fake/libfake.so (func())'112 frame_info = ndk_stack.FrameInfo.from_line(line)113 self.assertTrue(frame_info)114 self.assertEqual('#08', frame_info.num)115 self.assertEqual('00001040', frame_info.pc)116 self.assertEqual('/fake/libfake.so (func())', frame_info.tail)117 self.assertEqual('/fake/libfake.so', frame_info.elf_file)118 self.assertFalse(frame_info.offset)119 self.assertFalse(frame_info.container_file)120 self.assertFalse(frame_info.build_id)121 def test_line_with_offset(self):122 line = ' #04 pc 00002050 /fake/libfake.so (offset 0x2000)'123 frame_info = ndk_stack.FrameInfo.from_line(line)124 self.assertTrue(frame_info)125 self.assertEqual('#04', frame_info.num)126 self.assertEqual('00002050', frame_info.pc)127 self.assertEqual('/fake/libfake.so (offset 0x2000)', frame_info.tail)128 self.assertEqual('/fake/libfake.so', frame_info.elf_file)129 self.assertEqual(0x2000, frame_info.offset)130 self.assertFalse(frame_info.container_file)131 self.assertFalse(frame_info.build_id)132 def test_line_with_build_id(self):133 line = ' #03 pc 00002050 /fake/libfake.so (BuildId: d1d420a58366bf29f1312ec826f16564)'134 frame_info = ndk_stack.FrameInfo.from_line(line)135 self.assertTrue(frame_info)136 self.assertEqual('#03', frame_info.num)137 self.assertEqual('00002050', frame_info.pc)138 self.assertEqual(139 '/fake/libfake.so (BuildId: d1d420a58366bf29f1312ec826f16564)',140 frame_info.tail)141 self.assertEqual('/fake/libfake.so', frame_info.elf_file)142 self.assertFalse(frame_info.offset)143 self.assertFalse(frame_info.container_file)144 self.assertEqual('d1d420a58366bf29f1312ec826f16564',145 frame_info.build_id)146 def test_line_with_container_file(self):147 line = ' #10 pc 00003050 /fake/fake.apk!libc.so'148 frame_info = ndk_stack.FrameInfo.from_line(line)149 self.assertTrue(frame_info)150 self.assertEqual('#10', frame_info.num)151 self.assertEqual('00003050', frame_info.pc)152 self.assertEqual('/fake/fake.apk!libc.so', frame_info.tail)153 self.assertEqual('libc.so', frame_info.elf_file)154 self.assertFalse(frame_info.offset)155 self.assertEqual('/fake/fake.apk', frame_info.container_file)156 self.assertFalse(frame_info.build_id)157 def test_line_with_container_and_elf_equal(self):158 line = ' #12 pc 00004050 /fake/libc.so!lib/libc.so'159 frame_info = ndk_stack.FrameInfo.from_line(line)160 self.assertTrue(frame_info)161 self.assertEqual('#12', frame_info.num)162 self.assertEqual('00004050', frame_info.pc)163 self.assertEqual('/fake/libc.so!lib/libc.so', frame_info.tail)164 self.assertEqual('/fake/libc.so', frame_info.elf_file)165 self.assertFalse(frame_info.offset)166 self.assertFalse(frame_info.container_file)167 self.assertFalse(frame_info.build_id)168 def test_line_everything(self):169 line = (' #07 pc 00823fc /fake/fake.apk!libc.so (__start_thread+64) '170 '(offset 0x1000) (BuildId: 6a0c10d19d5bf39a5a78fa514371dab3)')171 frame_info = ndk_stack.FrameInfo.from_line(line)172 self.assertTrue(frame_info)173 self.assertEqual('#07', frame_info.num)174 self.assertEqual('00823fc', frame_info.pc)175 self.assertEqual(176 '/fake/fake.apk!libc.so (__start_thread+64) '177 '(offset 0x1000) (BuildId: 6a0c10d19d5bf39a5a78fa514371dab3)',178 frame_info.tail)179 self.assertEqual('libc.so', frame_info.elf_file)180 self.assertEqual(0x1000, frame_info.offset)181 self.assertEqual('/fake/fake.apk', frame_info.container_file)182 self.assertEqual('6a0c10d19d5bf39a5a78fa514371dab3',183 frame_info.build_id)184@patch.object(ndk_stack, 'get_build_id')185@patch('os.path.exists')186class VerifyElfFileTests(unittest.TestCase):187 """Tests of verify_elf_file()."""188 def create_frame_info(self):189 line = ' #03 pc 00002050 /fake/libfake.so'190 frame_info = ndk_stack.FrameInfo.from_line(line)191 self.assertTrue(frame_info)192 return frame_info193 def test_elf_file_does_not_exist(self, mock_exists, _):194 mock_exists.return_value = False195 frame_info = self.create_frame_info()196 self.assertFalse(197 frame_info.verify_elf_file(None, '/fake/libfake.so', 'libfake.so'))198 self.assertFalse(199 frame_info.verify_elf_file('readelf', '/fake/libfake.so',200 'libfake.so'))201 def test_elf_file_build_id_matches(self, mock_exists, mock_get_build_id):202 mock_exists.return_value = True203 frame_info = self.create_frame_info()204 frame_info.build_id = 'MOCKED_BUILD_ID'205 self.assertTrue(206 frame_info.verify_elf_file(None, '/mocked/libfake.so',207 'libfake.so'))208 mock_get_build_id.assert_not_called()209 mock_get_build_id.return_value = 'MOCKED_BUILD_ID'210 self.assertTrue(211 frame_info.verify_elf_file('readelf', '/mocked/libfake.so',212 'libfake.so'))213 mock_get_build_id.assert_called_once_with('readelf',214 '/mocked/libfake.so')215 def test_elf_file_build_id_does_not_match(self, mock_exists,216 mock_get_build_id):217 mock_exists.return_value = True218 mock_get_build_id.return_value = 'MOCKED_BUILD_ID'219 frame_info = self.create_frame_info()220 frame_info.build_id = 'DIFFERENT_BUILD_ID'221 with patch('sys.stdout', new_callable=StringIO) as mock_stdout:222 self.assertTrue(223 frame_info.verify_elf_file(None, '/mocked/libfake.so',224 'none.so'))225 self.assertFalse(226 frame_info.verify_elf_file('readelf', '/mocked/libfake.so',227 'display.so'))228 output = textwrap.dedent("""\229 WARNING: Mismatched build id for display.so230 WARNING: Expected DIFFERENT_BUILD_ID231 WARNING: Found MOCKED_BUILD_ID232 """)233 self.assertEqual(output, mock_stdout.getvalue())234class GetZipInfoFromOffsetTests(unittest.TestCase):235 """Tests of get_zip_info_from_offset()."""236 def setUp(self):237 self.mock_zip = mock.MagicMock()238 self.mock_zip.filename = '/fake/zip.apk'239 self.mock_zip.infolist.return_value = []240 def test_file_does_not_exist(self):241 with self.assertRaises(IOError):242 _ = ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x1000)243 @patch('os.stat')244 def test_offset_ge_file_size(self, mock_stat):245 mock_stat.return_value.st_size = 0x1000246 self.assertFalse(ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x1000))247 self.assertFalse(ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x1100))248 @patch('os.stat')249 def test_empty_infolist(self, mock_stat):250 mock_stat.return_value.st_size = 0x1000251 self.assertFalse(ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x900))252 @patch('os.stat')253 def test_zip_info_single_element(self, mock_stat):254 mock_stat.return_value.st_size = 0x2000255 mock_zip_info = mock.MagicMock()256 mock_zip_info.header_offset = 0x100257 self.mock_zip.infolist.return_value = [mock_zip_info]258 self.assertFalse(ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x50))259 self.assertFalse(ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x2000))260 zip_info = ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x200)261 self.assertEqual(0x100, zip_info.header_offset)262 @patch('os.stat')263 def test_zip_info_checks(self, mock_stat):264 mock_stat.return_value.st_size = 0x2000265 mock_zip_info1 = mock.MagicMock()266 mock_zip_info1.header_offset = 0x100267 mock_zip_info2 = mock.MagicMock()268 mock_zip_info2.header_offset = 0x1000269 self.mock_zip.infolist.return_value = [mock_zip_info1, mock_zip_info2]270 self.assertFalse(ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x50))271 zip_info = ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x200)272 self.assertEqual(0x100, zip_info.header_offset)273 zip_info = ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x100)274 self.assertEqual(0x100, zip_info.header_offset)275 zip_info = ndk_stack.get_zip_info_from_offset(self.mock_zip, 0x1000)276 self.assertEqual(0x1000, zip_info.header_offset)277class GetElfFileTests(unittest.TestCase):278 """Tests of FrameInfo.get_elf_file()."""279 def setUp(self):280 self.mock_zipfile = mock.MagicMock()281 self.mock_zipfile.extract.return_value = '/fake_tmp/libtest.so'282 self.mock_zipfile.__enter__.return_value = self.mock_zipfile283 self.mock_tmp = mock.MagicMock()284 self.mock_tmp.get_directory.return_value = '/fake_tmp'285 def create_frame_info(self, tail):286 line = ' #03 pc 00002050 ' + tail287 frame_info = ndk_stack.FrameInfo.from_line(line)288 self.assertTrue(frame_info)289 frame_info.verify_elf_file = mock.MagicMock()290 return frame_info291 def test_file_only(self):292 frame_info = self.create_frame_info('/fake/libfake.so')293 frame_info.verify_elf_file.return_value = True294 self.assertEqual(295 '/fake_dir/symbols/libfake.so',296 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))297 frame_info.verify_elf_file.reset_mock()298 frame_info.verify_elf_file.return_value = False299 self.assertFalse(300 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))301 self.assertEqual('/fake/libfake.so', frame_info.tail)302 def test_container_set_elf_in_symbol_dir(self):303 frame_info = self.create_frame_info('/fake/fake.apk!libtest.so')304 frame_info.verify_elf_file.return_value = True305 self.assertEqual(306 '/fake_dir/symbols/libtest.so',307 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))308 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)309 def test_container_set_elf_not_in_symbol_dir_apk_does_not_exist(self):310 frame_info = self.create_frame_info('/fake/fake.apk!libtest.so')311 frame_info.verify_elf_file.return_value = False312 with self.assertRaises(IOError):313 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp)314 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)315 @patch.object(ndk_stack, 'get_zip_info_from_offset')316 @patch('zipfile.ZipFile')317 def test_container_set_elf_not_in_apk(self, _,318 mock_get_zip_info):319 mock_get_zip_info.return_value = None320 frame_info = self.create_frame_info('/fake/fake.apk!libtest.so')321 frame_info.verify_elf_file.return_value = False322 self.assertFalse(323 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))324 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)325 @patch.object(ndk_stack, 'get_zip_info_from_offset')326 @patch('zipfile.ZipFile')327 def test_container_set_elf_in_apk(self, mock_zipclass, mock_get_zip_info):328 mock_zipclass.return_value = self.mock_zipfile329 mock_get_zip_info.return_value.filename = 'libtest.so'330 frame_info = self.create_frame_info('/fake/fake.apk!libtest.so')331 frame_info.verify_elf_file.side_effect = [False, True]332 self.assertEqual(333 '/fake_tmp/libtest.so',334 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))335 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)336 @patch.object(ndk_stack, 'get_zip_info_from_offset')337 @patch('zipfile.ZipFile')338 def test_container_set_elf_in_apk_verify_fails(self, mock_zipclass,339 mock_get_zip_info):340 mock_zipclass.return_value = self.mock_zipfile341 mock_get_zip_info.return_value.filename = 'libtest.so'342 frame_info = self.create_frame_info('/fake/fake.apk!libtest.so')343 frame_info.verify_elf_file.side_effect = [False, False]344 self.assertFalse(345 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))346 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)347 def test_in_apk_file_does_not_exist(self):348 frame_info = self.create_frame_info('/fake/fake.apk')349 frame_info.verify_elf_file.return_value = False350 with self.assertRaises(IOError):351 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp)352 self.assertEqual('/fake/fake.apk', frame_info.tail)353 @patch.object(ndk_stack, 'get_zip_info_from_offset')354 @patch('zipfile.ZipFile')355 def test_in_apk_elf_not_in_apk(self, _, mock_get_zip_info):356 mock_get_zip_info.return_value = None357 frame_info = self.create_frame_info('/fake/fake.apk')358 self.assertFalse(359 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))360 self.assertEqual('/fake/fake.apk', frame_info.tail)361 @patch.object(ndk_stack, 'get_zip_info_from_offset')362 @patch('zipfile.ZipFile')363 def test_in_apk_elf_in_symbol_dir(self, mock_zipclass, mock_get_zip_info):364 mock_zipclass.return_value = self.mock_zipfile365 mock_get_zip_info.return_value.filename = 'libtest.so'366 frame_info = self.create_frame_info('/fake/fake.apk')367 frame_info.verify_elf_file.return_value = True368 self.assertEqual(369 '/fake_dir/symbols/libtest.so',370 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))371 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)372 @patch.object(ndk_stack, 'get_zip_info_from_offset')373 @patch('zipfile.ZipFile')374 def test_in_apk_elf_in_apk(self, mock_zipclass, mock_get_zip_info):375 mock_zipclass.return_value = self.mock_zipfile376 mock_get_zip_info.return_value.filename = 'libtest.so'377 frame_info = self.create_frame_info('/fake/fake.apk')378 frame_info.verify_elf_file.side_effect = [False, True]379 self.assertEqual(380 '/fake_tmp/libtest.so',381 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))382 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)383 @patch.object(ndk_stack, 'get_zip_info_from_offset')384 @patch('zipfile.ZipFile')385 def test_in_apk_elf_in_apk_verify_fails(self, mock_zipclass,386 mock_get_zip_info):387 mock_zipclass.return_value = self.mock_zipfile388 mock_get_zip_info.return_value.filename = 'libtest.so'389 frame_info = self.create_frame_info('/fake/fake.apk')390 frame_info.verify_elf_file.side_effect = [False, False]391 self.assertFalse(392 frame_info.get_elf_file('/fake_dir/symbols', None, self.mock_tmp))393 self.assertEqual('/fake/fake.apk!libtest.so', frame_info.tail)394if __name__ == "__main__":...

Full Screen

Full Screen

test_edgeutils.py

Source:test_edgeutils.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

build_api_test.py

Source:build_api_test.py Github

copy

Full Screen

1"""2mbed SDK3Copyright (c) 2016 ARM Limited4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11See the License for the specific language governing permissions and12limitations under the License.13"""14import unittest15from collections import namedtuple16from mock import patch, MagicMock17from tools.build_api import prepare_toolchain, build_project, build_library,\18 scan_resources19from tools.toolchains import TOOLCHAINS20"""21Tests for build_api.py22"""23make_mock_target = namedtuple(24 "Target", "init_hooks name features core supported_toolchains")25class BuildApiTests(unittest.TestCase):26 """27 Test cases for Build Api28 """29 def setUp(self):30 """31 Called before each test case32 :return:33 """34 self.target = "K64F"35 self.src_paths = ['.']36 self.toolchain_name = "ARM"37 self.build_path = "build_path"38 def tearDown(self):39 """40 Called after each test case41 :return:42 """43 pass44 @patch('tools.toolchains.arm.ARM_STD.parse_dependencies',45 return_value=["foo"])46 @patch('tools.toolchains.mbedToolchain.need_update',47 side_effect=[i % 2 for i in range(3000)])48 @patch('os.mkdir')49 @patch('tools.toolchains.exists', return_value=True)50 @patch('tools.toolchains.mbedToolchain.dump_build_profile')51 @patch('tools.utils.run_cmd', return_value=("", "", 0))52 def test_always_complete_build(self, *_):53 with MagicMock() as notify:54 toolchain = prepare_toolchain(self.src_paths, self.build_path, self.target,55 self.toolchain_name, notify=notify)56 res = scan_resources(self.src_paths, toolchain)57 toolchain.RESPONSE_FILES=False58 toolchain.config_processed = True59 toolchain.config_file = "junk"60 toolchain.compile_sources(res)61 assert any('percent' in msg[0] and msg[0]['percent'] == 100.062 for _, msg, _ in notify.mock_calls if msg)63 @patch('tools.build_api.Config')64 def test_prepare_toolchain_app_config(self, mock_config_init):65 """66 Test that prepare_toolchain uses app_config correctly67 :param mock_config_init: mock of Config __init__68 :return:69 """70 app_config = "app_config"71 mock_target = make_mock_target(lambda _, __ : None,72 "Junk", [], "Cortex-M3", TOOLCHAINS)73 mock_config_init.return_value = namedtuple(74 "Config", "target has_regions name")(mock_target, False, None)75 prepare_toolchain(self.src_paths, None, self.target, self.toolchain_name,76 app_config=app_config)77 mock_config_init.assert_called_once_with(self.target, self.src_paths,78 app_config=app_config)79 @patch('tools.build_api.Config')80 def test_prepare_toolchain_no_app_config(self, mock_config_init):81 """82 Test that prepare_toolchain correctly deals with no app_config83 :param mock_config_init: mock of Config __init__84 :return:85 """86 mock_target = make_mock_target(lambda _, __ : None,87 "Junk", [], "Cortex-M3", TOOLCHAINS)88 mock_config_init.return_value = namedtuple(89 "Config", "target has_regions name")(mock_target, False, None)90 prepare_toolchain(self.src_paths, None, self.target, self.toolchain_name)91 mock_config_init.assert_called_once_with(self.target, self.src_paths,92 app_config=None)93 @patch('tools.build_api.scan_resources')94 @patch('tools.build_api.mkdir')95 @patch('os.path.exists')96 @patch('tools.build_api.prepare_toolchain')97 def test_build_project_app_config(self, mock_prepare_toolchain, mock_exists, _, __):98 """99 Test that build_project uses app_config correctly100 :param mock_prepare_toolchain: mock of function prepare_toolchain101 :param mock_exists: mock of function os.path.exists102 :param _: mock of function mkdir (not tested)103 :param __: mock of function scan_resources (not tested)104 :return:105 """106 app_config = "app_config"107 mock_exists.return_value = False108 mock_prepare_toolchain().link_program.return_value = 1, 2109 mock_prepare_toolchain().config = namedtuple(110 "Config", "has_regions name lib_config_data")(None, None, {})111 build_project(self.src_paths, self.build_path, self.target,112 self.toolchain_name, app_config=app_config)113 args = mock_prepare_toolchain.call_args114 self.assertTrue('app_config' in args[1],115 "prepare_toolchain was not called with app_config")116 self.assertEqual(args[1]['app_config'], app_config,117 "prepare_toolchain was called with an incorrect app_config")118 @patch('tools.build_api.scan_resources')119 @patch('tools.build_api.mkdir')120 @patch('os.path.exists')121 @patch('tools.build_api.prepare_toolchain')122 def test_build_project_no_app_config(self, mock_prepare_toolchain, mock_exists, _, __):123 """124 Test that build_project correctly deals with no app_config125 :param mock_prepare_toolchain: mock of function prepare_toolchain126 :param mock_exists: mock of function os.path.exists127 :param _: mock of function mkdir (not tested)128 :param __: mock of function scan_resources (not tested)129 :return:130 """131 mock_exists.return_value = False132 # Needed for the unpacking of the returned value133 mock_prepare_toolchain().link_program.return_value = 1, 2134 mock_prepare_toolchain().config = namedtuple(135 "Config", "has_regions name lib_config_data")(None, None, {})136 build_project(self.src_paths, self.build_path, self.target,137 self.toolchain_name)138 args = mock_prepare_toolchain.call_args139 self.assertTrue('app_config' in args[1],140 "prepare_toolchain was not called with app_config")141 self.assertEqual(args[1]['app_config'], None,142 "prepare_toolchain was called with an incorrect app_config")143 @patch('tools.build_api.scan_resources')144 @patch('tools.build_api.mkdir')145 @patch('os.path.exists')146 @patch('tools.build_api.prepare_toolchain')147 def test_build_library_app_config(self, mock_prepare_toolchain, mock_exists, _, __):148 """149 Test that build_library uses app_config correctly150 :param mock_prepare_toolchain: mock of function prepare_toolchain151 :param mock_exists: mock of function os.path.exists152 :param _: mock of function mkdir (not tested)153 :param __: mock of function scan_resources (not tested)154 :return:155 """156 app_config = "app_config"157 mock_exists.return_value = False158 build_library(self.src_paths, self.build_path, self.target,159 self.toolchain_name, app_config=app_config)160 args = mock_prepare_toolchain.call_args161 self.assertTrue('app_config' in args[1],162 "prepare_toolchain was not called with app_config")163 self.assertEqual(args[1]['app_config'], app_config,164 "prepare_toolchain was called with an incorrect app_config")165 @patch('tools.build_api.scan_resources')166 @patch('tools.build_api.mkdir')167 @patch('os.path.exists')168 @patch('tools.build_api.prepare_toolchain')169 def test_build_library_no_app_config(self, mock_prepare_toolchain, mock_exists, _, __):170 """171 Test that build_library correctly deals with no app_config172 :param mock_prepare_toolchain: mock of function prepare_toolchain173 :param mock_exists: mock of function os.path.exists174 :param _: mock of function mkdir (not tested)175 :param __: mock of function scan_resources (not tested)176 :return:177 """178 mock_exists.return_value = False179 build_library(self.src_paths, self.build_path, self.target,180 self.toolchain_name)181 args = mock_prepare_toolchain.call_args182 self.assertTrue('app_config' in args[1],183 "prepare_toolchain was not called with app_config")184 self.assertEqual(args[1]['app_config'], None,185 "prepare_toolchain was called with an incorrect app_config")186if __name__ == '__main__':...

Full Screen

Full Screen

test_artifact.py

Source:test_artifact.py Github

copy

Full Screen

1import pytest2from mock import (3 Mock,4 patch,5 call6)7from requests.exceptions import HTTPError8from jenkinsapi.artifact import Artifact9from jenkinsapi.jenkinsbase import JenkinsBase10from jenkinsapi.fingerprint import Fingerprint11from jenkinsapi.custom_exceptions import ArtifactBroken12try:13 import unittest2 as unittest14except ImportError:15 import unittest16@pytest.fixture()17def artifact(mocker):18 return Artifact(19 'artifact.zip', 'http://foo/job/TestJob/1/artifact/artifact.zip',20 mocker.MagicMock()21 )22def test_verify_download_valid_positive(artifact, monkeypatch):23 def fake_md5(cls, fspath): # pylint: disable=unused-argument24 return '097c42989a9e5d9dcced7b35ec4b0486'25 monkeypatch.setattr(Artifact, '_md5sum', fake_md5)26 def fake_poll(cls, tree=None): # pylint: disable=unused-argument27 return {}28 monkeypatch.setattr(JenkinsBase, '_poll', fake_poll)29 def fake_validate(cls, filename, # pylint: disable=unused-argument30 job, build): # pylint: disable=unused-argument31 return True32 monkeypatch.setattr(Fingerprint, 'validate_for_build', fake_validate)33 assert artifact._verify_download('/tmp/artifact.zip',34 strict_validation=False)35def test_verify_download_valid_positive_with_rename(artifact, monkeypatch):36 def fake_md5(cls, fspath): # pylint: disable=unused-argument37 return '097c42989a9e5d9dcced7b35ec4b0486'38 monkeypatch.setattr(Artifact, '_md5sum', fake_md5)39 def fake_poll(cls, tree=None): # pylint: disable=unused-argument40 return {}41 monkeypatch.setattr(JenkinsBase, '_poll', fake_poll)42 def fake_validate(cls, filename, # pylint: disable=unused-argument43 job, build): # pylint: disable=unused-argument44 return filename == 'artifact.zip'45 monkeypatch.setattr(Fingerprint, 'validate_for_build', fake_validate)46 assert artifact._verify_download('/tmp/temporary_filename',47 strict_validation=False)48def test_verify_download_valid_negative(artifact, monkeypatch):49 def fake_md5(cls, fspath): # pylint: disable=unused-argument50 return '097c42989a9e5d9dcced7b35ec4b0486'51 monkeypatch.setattr(Artifact, '_md5sum', fake_md5)52 class FakeResponse(object):53 status_code = 40454 text = '{}'55 class FakeHTTPError(HTTPError):56 def __init__(self):57 self.response = FakeResponse()58 def fake_poll(cls, tree=None): # pylint: disable=unused-argument59 raise FakeHTTPError()60 monkeypatch.setattr(JenkinsBase, '_poll', fake_poll)61 def fake_validate(cls, filename, # pylint: disable=unused-argument62 job, build): # pylint: disable=unused-argument63 return True64 monkeypatch.setattr(Fingerprint, 'validate_for_build', fake_validate)65 assert artifact._verify_download('/tmp/artifact.zip',66 strict_validation=False)67def test_verify_dl_valid_negative_strict(artifact, monkeypatch):68 def fake_md5(cls, fspath): # pylint: disable=unused-argument69 return '097c42989a9e5d9dcced7b35ec4b0486'70 monkeypatch.setattr(Artifact, '_md5sum', fake_md5)71 class FakeResponse(object):72 status_code = 40473 text = '{}'74 class FakeHTTPError(HTTPError):75 def __init__(self):76 self.response = FakeResponse()77 def fake_poll(cls, tree=None): # pylint: disable=unused-argument78 raise FakeHTTPError()79 monkeypatch.setattr(JenkinsBase, '_poll', fake_poll)80 with pytest.raises(ArtifactBroken) as ab:81 artifact._verify_download('/tmp/artifact.zip',82 strict_validation=True)83 assert 'Artifact 097c42989a9e5d9dcced7b35ec4b0486 seems to be broken' \84 in str(ab.value)85def test_verify_download_invalid(artifact, monkeypatch):86 def fake_md5(cls, fspath): # pylint: disable=unused-argument87 return '097c42989a9e5d9dcced7b35ec4b0486'88 monkeypatch.setattr(Artifact, '_md5sum', fake_md5)89 def fake_poll(cls, tree=None): # pylint: disable=unused-argument90 return {}91 monkeypatch.setattr(JenkinsBase, '_poll', fake_poll)92 def fake_validate(cls, filename, # pylint: disable=unused-argument93 job, build): # pylint: disable=unused-argument94 return False95 monkeypatch.setattr(Fingerprint, 'validate_for_build', fake_validate)96 with pytest.raises(ArtifactBroken) as ab:97 artifact._verify_download('/tmp/artifact.zip',98 strict_validation=True)99 assert 'Artifact 097c42989a9e5d9dcced7b35ec4b0486 seems to be broken' \100 in str(ab.value)101class ArtifactTest(unittest.TestCase):102 def setUp(self):103 self._build = build = Mock()104 build.buildno = 9999105 job = self._build.job106 job.jenkins.baseurl = 'http://localhost'107 job.name = 'TestJob'108 self._artifact = Artifact(109 'artifact.zip',110 'http://localhost/job/TestJob/9999/artifact/artifact.zip', build)111 @patch('jenkinsapi.artifact.os.path.exists', spec=True, return_value=True)112 def test_save_has_valid_local_copy(self, mock_exists):113 artifact = self._artifact114 artifact._verify_download = Mock(return_value=True)115 assert artifact.save('/tmp/artifact.zip') == \116 '/tmp/artifact.zip'117 mock_exists.assert_called_once_with('/tmp/artifact.zip')118 artifact._verify_download.assert_called_once_with(119 '/tmp/artifact.zip', False)120 @patch('jenkinsapi.artifact.os.path.exists', spec=True, return_value=True)121 def test_save_has_invalid_local_copy_dl_again(self, mock_exists):122 artifact = self._artifact123 artifact._verify_download = Mock(side_effect=[ArtifactBroken, True])124 artifact._do_download = Mock(return_value='/tmp/artifact.zip')125 assert artifact.save('/tmp/artifact.zip', True) == \126 '/tmp/artifact.zip'127 mock_exists.assert_called_once_with('/tmp/artifact.zip')128 artifact._do_download.assert_called_once_with('/tmp/artifact.zip')129 assert artifact._verify_download.mock_calls == \130 [call('/tmp/artifact.zip', True)] * 2131 @patch('jenkinsapi.artifact.os.path.exists', spec=True, return_value=True)132 def test_has_invalid_lcl_copy_dl_but_invalid(133 self, mock_exists):134 artifact = self._artifact135 artifact._verify_download = Mock(136 side_effect=[ArtifactBroken, ArtifactBroken])137 artifact._do_download = Mock(return_value='/tmp/artifact.zip')138 with pytest.raises(ArtifactBroken):139 artifact.save('/tmp/artifact.zip', True)140 mock_exists.assert_called_once_with('/tmp/artifact.zip')141 artifact._do_download.assert_called_once_with('/tmp/artifact.zip')142 assert artifact._verify_download.mock_calls == \143 [call('/tmp/artifact.zip', True)] * 2144 @patch('jenkinsapi.artifact.os.path.exists', spec=True, return_value=False)145 def test_save_has_no_local_copy(self, mock_exists):146 artifact = self._artifact147 artifact._do_download = Mock(return_value='/tmp/artifact.zip')148 artifact._verify_download = Mock(return_value=True)149 assert artifact.save('/tmp/artifact.zip') == \150 '/tmp/artifact.zip'151 mock_exists.assert_called_once_with('/tmp/artifact.zip')152 artifact._do_download.assert_called_once_with('/tmp/artifact.zip')153 artifact._verify_download.assert_called_once_with(...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nose automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful