def test_rotate_image(self): mock_img = Mock() mock_img.__enter__().height = 200 mock_img.__enter__().width = 800 autorotate.wand.image.Image = Mock(return_value=mock_img) autorotate.rotate_image('foo.jpg', 90) assert mock_img.__enter__().rotate.call_args_list == [call(90)] assert mock_img.__enter__().save.call_args_list == [ call(filename='foo.jpg')]
def test_rotate_image(self): mock_img = Mock() mock_img.__enter__().height = 200 mock_img.__enter__().width = 800 autorotate.wand.image.Image = Mock(return_value=mock_img) with patch('spreadsplug.autorotate.subprocess.check_output'): autorotate.rotate_image('foo.jpg', 90) assert mock_img.__enter__().rotate.call_args_list == [call(90)] assert mock_img.__enter__().save.call_args_list == [ call(filename='foo.jpg')]
def test_upload_o0(self): m_rfh = MagicMock() self.ftp._client.open.return_value = m_rfh fobj = Mock() fobj.read.side_effect = (b"bar", b"baz", b"") self.ftp._upload("foo", fobj) self.ftp._client.open.assert_called_once() m_rfh.__enter__().write.assert_any_call(b"bar") m_rfh.__enter__().write.assert_any_call(b"baz")
def test_process_inverse(self): test_files = [self.path / 'raw' / '000.jpg'] map(lambda x: x.touch(), test_files) mock_pool = Mock() autorotate.futures.ProcessPoolExecutor = Mock(return_value=mock_pool) self.config['autorotate']['rotate_odd'] = 90 self.config['autorotate']['rotate_even'] = -90 plug = autorotate.AutoRotatePlugin(self.config) with patch('spreadsplug.autorotate._get_exif_orientation') as geo: geo.return_value = 6 plug.process(self.path) mock_pool.__enter__().submit.assert_called_with( autorotate.rotate_image, test_files[0], rotation=-90 )
def setUp(self): self.mock_kv_store() Settings.GANESHA_CLUSTERS_RADOS_POOL_NAMESPACE = "ganesha/ns" self.temp_store = { 'export-1': GaneshaConfTest.RObject("export-1", self.export_1), 'conf-nodea': GaneshaConfTest.RObject("conf-nodea", self.conf_nodea), 'export-2': GaneshaConfTest.RObject("export-2", self.export_2), 'conf-nodeb': GaneshaConfTest.RObject("conf-nodeb", self.conf_nodeb) } self.io_mock = MagicMock() self.io_mock.list_objects.side_effect = self._ioctx_list_objects_mock self.io_mock.write_full.side_effect = self._ioctx_write_full_mock self.io_mock.remove_object.side_effect = self._ioctx_remove_mock ioctx_mock = MagicMock() ioctx_mock.__enter__ = Mock(return_value=(self.io_mock)) ioctx_mock.__exit__ = Mock(return_value=None) mgr.rados = MagicMock() mgr.rados.open_ioctx.return_value = ioctx_mock mgr.remote.return_value = False, None ganesha.CephX = MagicMock() ganesha.CephX.list_clients.return_value = ['ganesha'] ganesha.CephX.get_client_key.return_value = 'ganesha' ganesha.CephFS = MagicMock()
def test_load_template_source_second_source_path(self, open_mock): file_mock = MagicMock() file_mock.__enter__().read.return_value = "file_content" open_mock.side_effect = (IOError(errno.ENOENT, 'No such file or directory'), file_mock) loader = TemplateLoader(Mock()) self.assertEqual(loader.load_template_source("a.html"), ('file_content', '/fs/wirecloud/defaulttheme/templates/a.html'))
def run_test(self, mock_field_map, mock_build_sql_query, mock_ext_output, mock_projection): mock_field_map.return_value = [u'id_cfpb', u'name'] mock_build_sql_query.return_value = 'SELECT blah blah' mock_cursor_attrs = {'execute.return_value': True} mock_cursor = MagicMock(**mock_cursor_attrs) mock_cursor_enter_return = MagicMock( return_value=["row1", "row2", "row3"], **mock_cursor_attrs) mock_cursor_enter_return.__iter__.return_value = [ 'row1', 'row2', 'row3'] mock_cursor.__enter__ = Mock(return_value=mock_cursor_enter_return) mock_connect_attrs = {'cursor.return_value': mock_cursor} mock_connect = Mock(**mock_connect_attrs) mock_extractor_attrs = {'connect.return_value': mock_connect} mock_extractor = Mock(table="table", **mock_extractor_attrs) mock_ext_output.return_value = mock_extractor mock_projection.return_value = "1" format = Format("mapping_file", "docs_file", "table", sql_filter="WHERE id_cfpb is not NULL", marker_table=True) format.run() mock_field_map.assert_called_once() assert_equal(mock_projection.call_count, 3) mock_projection.assert_has_calls([ mock.call(mock_field_map.return_value, "row1"), mock.call(mock_field_map.return_value, "row2"), mock.call(mock_field_map.return_value, "row3") ])
def test_process(self): test_files = [self.path / 'raw' / x for x in ('000.jpg', '001.jpg', '002.jpg')] map(lambda x: x.touch(), test_files) mock_pool = Mock() autorotate.futures.ProcessPoolExecutor = Mock(return_value=mock_pool) with patch('spreadsplug.autorotate._get_exif_orientation') as geo: geo.side_effect = (6, 8, -1) plug = autorotate.AutoRotatePlugin(self.config) plug.process(self.path) assert geo.call_count == 3 mock_pool.__enter__().submit.assert_has_calls([ call(autorotate.rotate_image, test_files[0], rotation=90), call(autorotate.rotate_image, test_files[1], rotation=-90) ])
def setUp(self): account_mgr.get_cursor = MagicMock() cur = MagicMock() account_mgr.get_cursor.return_value = cur self.cur = cur.__enter__() account_mgr.get_api = MagicMock() self.api = MagicMock() account_mgr.get_api.return_value = self.api
def test_ls_o0(self): m_rfh = MagicMock() m_rfh.__enter__().readdir.return_value = [ ("whatever", b"bar"), ("again", b".baz"), ("toto", b".")] self.ftp._client.opendir = MagicMock(return_value=m_rfh) res = self.ftp._ls("foo") self.ftp._client.opendir.assert_called_once_with("foo") self.assertEqual(res, ["bar", ".baz"])
def _gracefulCreateTableMock(definition): """ Mock for DynamoDBService._gracefulCreateTable """ batchTableMock = MagicMock(spec_set=BatchTable, put_item=Mock(spec_set=BatchTable.put_item)) batchTableMock.__enter__ = Mock(return_value=batchTableMock) batchTableMock.__exit__ = Mock(return_value=False) return Mock( spec_set=DynamoTableTemplate, table_name=definition.tableName, batch_write=MagicMock(spec_set="boto.dynamodb2.table.batch_write", return_value=batchTableMock), )
def test_download_o0(self): m_rfh = MagicMock() m_rfh.__enter__().__iter__.return_value = iter( [(3, b"bar"), (3, b"baz"), (0, b"")]) self.ftp._client.open.return_value = m_rfh fobj = Mock() self.ftp._download("foo", fobj) self.ftp._client.open.assert_called_once_with("foo", 0, 0) fobj.write.assert_any_call(b"bar") fobj.write.assert_any_call(b"baz") fobj.write.assert_any_call(b"")
def setUp(self): account_mgr.get_cursor = MagicMock() cur = MagicMock() account_mgr.get_cursor.return_value = cur self.cur = cur.__enter__() account_mgr.get_api = MagicMock() self.api = MagicMock() account_mgr.get_api.return_value = self.api self.user = { 'avatar_id': sentinel.avatar_id, 'email': sentinel.email, } self.api.get_user.return_value = self.user self.time = datetime.now() + timedelta(hours=1)
def test_process_inverse(self, listdir): listdir.return_value = ['foo.jpg'] mock_exif = Mock() mock_exif.exif.primary.Orientation = [6] autorotate.os.listdir = listdir autorotate.JpegFile = Mock() autorotate.JpegFile.fromFile = Mock(return_value=mock_exif) mock_pool = Mock() autorotate.futures.ProcessPoolExecutor = Mock(return_value=mock_pool) spreads.config['rotate_inverse'] = False plug = autorotate.AutoRotatePlugin(spreads.config) plug.process('/tmp/foobar') assert mock_pool.__enter__().submit.call_args_list == [ call(autorotate.rotate_image, '/tmp/foobar/raw/foo.jpg', rotation=90) ]
def test_save_configuration(self): """ Does it have the configuration save a copy of itself? """ configadapter = MagicMock() rvrconfiguration = RVRConfiguration(configadapter) self.tester._configuration = rvrconfiguration open_mock = mock_open() opened_file = MagicMock() open_mock.return_value = opened_file print __name__ self.tester._result_location = 'apple_jack' with patch('__builtin__.open', open_mock, create=True): filename = 'outyor.ini' self.tester.save_configuration(filename=filename) open_mock.assert_called_with('apple_jack/outyor.ini', 'w') configadapter.write.assert_called_with(opened_file.__enter__()) return
def test_patch_https(self, getenv): # NB: HTTPSConnection is never mocked here; the monkey-patch applies to the actual httplib library. # If other tests in the future have any issues with httplib (they shouldn't, the patch is transparent, # and the original initializer is restored in the finally block), this may be why. orig_init = auth_requests._ORIG_HTTPSCONNECTION_INIT try: new_orig_init = MagicMock() auth_requests._ORIG_HTTPSCONNECTION_INIT = new_orig_init # Confirm that the patch is applied getenv.return_value = "key and cert contents" auth_requests.patch_https("test-provider-slug") self.assertNotEqual(auth_requests._ORIG_HTTPSCONNECTION_INIT, http.client.HTTPSConnection.__init__) self.assertEqual("_new_init", http.client.HTTPSConnection.__init__ .__closure__[1].cell_contents.__name__) # complicated because decorator named_tempfile = MagicMock() cert_tempfile = MagicMock() cert_tempfile.name = "temp filename" named_tempfile.__enter__ = MagicMock(return_value=cert_tempfile) cert_tempfile.write = MagicMock() cert_tempfile.flush = MagicMock() with patch('eventkit_cloud.utils.auth_requests.NamedTemporaryFile', return_value=named_tempfile, create=True): # Confirm that a base HTTPSConnection picks up key and cert files conn = http.client.HTTPSConnection() getenv.assert_called_with("test_provider_slug_CERT") new_orig_init.assert_called_with(ANY, key_file="temp filename", cert_file="temp filename") cert_tempfile.write.assert_called_once_with("key and cert contents".encode()) # Confirm that a MapProxy VerifiedHTTPSConnection picks up key and cert files cert_tempfile.write.reset_mock() conn = VerifiedHTTPSConnection() new_orig_init.assert_called_with(ANY, key_file="temp filename", cert_file="temp filename") cert_tempfile.write.assert_called_once_with("key and cert contents".encode()) # Test removing the patch auth_requests.unpatch_https() self.assertEqual(http.client.HTTPSConnection.__init__, new_orig_init) finally: auth_requests._ORIG_HTTPSCONNECTION_INIT = orig_init auth_requests.unpatch_https()
def test_process(self, listdir): listdir.return_value = ['left.jpg', 'right.jpg', 'invalid.jpg'] mock_exifs = [Mock(), Mock(), Mock()] for item, orient in zip(mock_exifs, (6, 8, -1)): item.exif.primary.Orientation = [orient] autorotate.os.listdir = listdir autorotate.JpegFile = Mock() autorotate.JpegFile.fromFile = Mock(side_effect=mock_exifs) mock_pool = Mock() autorotate.futures.ProcessPoolExecutor = Mock(return_value=mock_pool) plug = autorotate.AutoRotatePlugin(spreads.config) plug.process('/tmp/foobar') assert autorotate.JpegFile.fromFile.call_count == 3 assert mock_pool.__enter__().submit.call_args_list == [ call(autorotate.rotate_image, '/tmp/foobar/raw/left.jpg', rotation=90), call(autorotate.rotate_image, '/tmp/foobar/raw/right.jpg', rotation=-90) ]
def test(self, open_mock): context_manager_mock = MagicMock() open_mock.return_value = context_manager_mock context_manager_mock.__exit__ = Mock() context_manager_mock.__enter__ = Mock( side_effect=lambda *args, **kwargs: StringIO.StringIO( r""" MP_007 RushLarge0 2 MP_018 ConquestSmall0 2 # comment MP_Subway RushLarge0 4 MP_003 RushLarge0 4 """ ) ) maplist_block = self.p._read_maplist_file("f00") self.assertEqual( "MapListBlock[MP_007:RushLarge0:2, MP_018:ConquestSmall0:2, MP_Subway:RushLarge0:4, MP_003:RushLarge0:4]", str(maplist_block), )
def do_tests(self, req, req_patch, getenv): # Test: exception propagation getenv.return_value = None req_patch.side_effect = requests.exceptions.ConnectionError() with self.assertRaises(Exception): req(self.url) # Test: normal response without cert response = MagicMock() response.content = "test" req_patch.side_effect = None req_patch.return_value = response result = req(self.url, slug="test_slug", data=42) getenv.assert_any_call("TEST_SLUG_CERT") getenv.assert_any_call("TEST_SLUG_CRED") req_patch.assert_called_with(self.url, data=42) self.assertEqual("test", result.content) # Test: normal response with cert getenv.return_value = "test cert content" named_tempfile = MagicMock() cert_tempfile = MagicMock() cert_tempfile.name = "temp filename" named_tempfile.__enter__ = MagicMock(return_value=cert_tempfile) cert_tempfile.write = MagicMock() cert_tempfile.flush = MagicMock() with patch('eventkit_cloud.utils.auth_requests.NamedTemporaryFile', return_value=named_tempfile, create=True): result = req(self.url, slug="test_slug", data=42) getenv.assert_any_call("test_slug_CRED") getenv.assert_any_call("test_slug_CERT") cert_tempfile.write.assert_called_once_with("test cert content".encode()) cert_tempfile.flush.assert_called() req_patch.assert_called_with(self.url, data=42, cert="temp filename") self.assertEqual("test", result.content)
def test_download_plugin_from_nexus(self, tarfile_mock, re_mock, tempfile_mock, contextlib_mock, shutil_mock, urllib_mock, os_mock, open_mock, log_mock): single_tarfile_open_mock = MagicMock() tarfile_mock.open = MagicMock(return_value=single_tarfile_open_mock) single_tarfile_mock = MagicMock() single_tarfile_open_mock.__enter__ = MagicMock( return_value=single_tarfile_mock) os_mock.path.isdir = MagicMock(return_value=False) externalplugins._download_plugin_from_nexus(XMAKE_NEXUS, 'sampleplugin', nexusRepo='blabla', destDirectory='/my/folder') assert (urllib_mock.openurl.called_once_with( 'http://nexus.wdf.sap.corp:8081/nexus/service/local/artifact/maven/content?g=com.sap.prd.xmake.buildplugins&a=sampleplugin&v=LATEST&r=build.snapshots&e=tar.gz' )) assert (tarfile_mock.open.call_count == 1) assert (single_tarfile_mock.extractall.call_count == 1) assert (shutil_mock.rmtree.call_count == 0) assert (log_mock.error.call_count == 0)
def _create_hook_mock(sensor): mock = MagicMock() mock.__enter__ = lambda x: self.hook_mock return mock