Python unittest.mock.MagicMock() Examples

The following are 30 code examples of unittest.mock.MagicMock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module unittest.mock , or try the search function .
Example #1
Source File: conf.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def mock_pywin32():
    """Mock pywin32 module.

    Resulting in Linux hosts, including ReadTheDocs,
    and other environments that don't have pywin32 can generate the docs
    properly including the PDF version.
    See:
    http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
    """
    if try_import('win32api'):
        return

    from unittest import mock

    MOCK_MODULES = [
        'win32api', 'win32con', 'win32event', 'win32service',
        'win32serviceutil',
    ]
    for mod_name in MOCK_MODULES:
        sys.modules[mod_name] = mock.MagicMock() 
Example #2
Source File: testmagicmethods.py    From jawfish with MIT License 6 votes vote down vote up
def test_comparison(self):
        mock = Mock()
        def comp(s, o):
            return True
        mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp
        self. assertTrue(mock < 3)
        self. assertTrue(mock > 3)
        self. assertTrue(mock <= 3)
        self. assertTrue(mock >= 3)

        self.assertRaises(TypeError, lambda: MagicMock() < object())
        self.assertRaises(TypeError, lambda: object() < MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() < MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() > object())
        self.assertRaises(TypeError, lambda: object() > MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() > MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() <= object())
        self.assertRaises(TypeError, lambda: object() <= MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() <= MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() >= object())
        self.assertRaises(TypeError, lambda: object() >= MagicMock())
        self.assertRaises(TypeError, lambda: MagicMock() >= MagicMock()) 
Example #3
Source File: test_content_types.py    From waspy with Apache License 2.0 6 votes vote down vote up
def test_body_raw_body(monkeypatch):
    app = MagicMock()
    app.default_content_type = 'application/json'
    p = {'application/json': JSONParser()}
    monkeypatch.setattr('waspy.webtypes.parsers', p)

    # Test happy path
    original_body = {'test': 'original'}
    r = Response(body=original_body)
    r.app = app
    assert r.body == original_body
    assert r.raw_body == json.dumps(original_body).encode()

    # Test changing the body later
    new_body = {'test': 'new body'}
    r.body = new_body
    assert r.body == new_body
    assert r.raw_body == json.dumps(new_body).encode() 
Example #4
Source File: testmagicmethods.py    From jawfish with MIT License 6 votes vote down vote up
def test_magic_methods_and_spec_set(self):
        class Iterable(object):
            def __iter__(self):
                pass

        mock = Mock(spec_set=Iterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        mock.__iter__ = Mock(return_value=iter([]))
        self.assertEqual(list(mock), [])

        class NonIterable(object):
            pass
        mock = Mock(spec_set=NonIterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        def set_int():
            mock.__int__ = Mock(return_value=iter([]))
        self.assertRaises(AttributeError, set_int)

        mock = MagicMock(spec_set=Iterable)
        self.assertEqual(list(mock), [])
        self.assertRaises(AttributeError, set_int) 
Example #5
Source File: test_html.py    From ciftify with MIT License 6 votes vote down vote up
def test_image_and_subject_page_linked_for_each_subject(self, mock_open,
            mock_link):
        # Set up
        html_page = MagicMock()
        mock_open.return_value.__enter__.return_value = html_page
        class MockQCConfig(object):
            def __init__(self):
                pass
            def get_navigation_list(self, path):
                return []

        # Call
        html.write_image_index(self.qc_dir, self.subjects, MockQCConfig(),
                self.page_subject, self.image_name)

        # Assert
        assert mock_link.call_count == len(self.subjects) 
Example #6
Source File: test_compute_manager.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_container_commit(
            self, mock_save, mock_unpause, mock_pause, mock_commit,
            mock_get_image, mock_upload_image_data, mock_action_finish,
            mock_event_finish, mock_event_start):
        container = Container(self.context, **utils.get_test_container(
            status=consts.PAUSED))
        mock_get_image_response = mock.MagicMock()
        mock_get_image_response.data = StringIO().read()
        mock_get_image.return_value = mock_get_image_response
        mock_upload_image_data.return_value = mock.MagicMock()

        self.compute_manager._do_container_commit(self.context,
                                                  mock_get_image_response,
                                                  container, 'repo', 'tag')
        mock_commit.assert_called_once_with(
            self.context, container, 'repo', 'tag')
        mock_pause.assert_not_called()
        mock_unpause.assert_not_called()
        self.assertEqual(
            (self.context, container.uuid, 'compute__do_container_commit'),
            mock_event_finish.call_args[0])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_val'])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_tb']) 
Example #7
Source File: test_compute_manager.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_container_commit_with_pause(
            self, mock_save, mock_unpause, mock_pause, mock_commit,
            mock_get_image, mock_upload_image_data, mock_action_finish,
            mock_event_finish, mock_event_start):
        container = Container(self.context, **utils.get_test_container())
        mock_get_image_response = mock.MagicMock()
        mock_get_image_response.data = StringIO().read()
        mock_get_image.return_value = mock_get_image_response
        mock_upload_image_data.return_value = mock.MagicMock()
        mock_unpause.return_value = container
        mock_pause.return_value = container

        self.compute_manager._do_container_commit(self.context,
                                                  mock_get_image_response,
                                                  container, 'repo', 'tag')
        mock_commit.assert_called_once_with(
            self.context, container, 'repo', 'tag')
        mock_pause.assert_called_once_with(self.context, container)
        mock_unpause.assert_called_once_with(self.context, container)
        self.assertEqual(
            (self.context, container.uuid, 'compute__do_container_commit'),
            mock_event_finish.call_args[0])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_val'])
        self.assertIsNone(mock_event_finish.call_args[1]['exc_tb']) 
Example #8
Source File: test_html.py    From ciftify with MIT License 6 votes vote down vote up
def test_title_not_added_when_not_given(self, mock_open, mock_header):
        # Set up
        # fake page to 'open' and write to
        html_page = MagicMock()
        mock_open.return_value.__enter__.return_value = html_page
        # qc_config.Config stub
        class MockQCConfig(object):
            def __init__(self):
                pass

        # Call
        html.write_image_index(self.qc_dir, self.subjects, MockQCConfig(),
                self.page_subject, self.image_name)

        # Assert
        for call in html_page.write.call_args_list:
            assert '<h1>' not in call[0]
        assert mock_header.call_count == 1
        header_kword_args = mock_header.call_args_list[0][1]
        assert 'title' in header_kword_args.keys()
        assert header_kword_args['title'] == None 
Example #9
Source File: test_compute_api.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_container_create(self, mock_schedule_container,
                              mock_image_search,
                              mock_container_create,
                              mock_record_action_start):
        CONF.set_override('enable_image_validation', True, group="api")
        container = self.container
        container.status = consts.CREATING
        image_meta = mock.MagicMock()
        image_meta.id = '1234'
        mock_schedule_container.return_value = {'host': u'Centos',
                                                'nodename': None,
                                                'limits': {}}
        mock_image_search.return_value = [image_meta]
        self.compute_api.container_create(self.context, container,
                                          {}, None, None, False)
        self.assertTrue(mock_schedule_container.called)
        self.assertTrue(mock_image_search.called)
        self.assertTrue(mock_container_create.called) 
Example #10
Source File: test_kuryr_network.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_connect_container_to_network_failed(self, mock_neutron_api_cls):
        container = Container(self.context, **utils.get_test_container())
        network_name = 'c02afe4e-8350-4263-8078'
        requested_net = {'ipv4_address': '10.5.0.22',
                         'port': 'fake-port-id',
                         'preserve_on_delete': True}
        mock_neutron_api_cls.return_value = self.network_api.neutron_api
        old_port = self.network_api.neutron_api.list_ports(
            id='fake-port-id')['ports'][0]
        self.assertEqual('', old_port['device_id'])
        self.network_api.docker = mock.MagicMock()
        self.network_api.docker.connect_container_to_network = \
            mock.Mock(side_effect=exception.DockerError)
        self.assertRaises(exception.DockerError,
                          self.network_api.connect_container_to_network,
                          container, network_name, requested_net)
        new_port = self.network_api.neutron_api.list_ports(
            id='fake-port-id')['ports'][0]
        self.assertEqual('', new_port['device_id']) 
Example #11
Source File: testmagicmethods.py    From jawfish with MIT License 6 votes vote down vote up
def test_magic_methods_and_spec(self):
        class Iterable(object):
            def __iter__(self):
                pass

        mock = Mock(spec=Iterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        mock.__iter__ = Mock(return_value=iter([]))
        self.assertEqual(list(mock), [])

        class NonIterable(object):
            pass
        mock = Mock(spec=NonIterable)
        self.assertRaises(AttributeError, lambda: mock.__iter__)

        def set_int():
            mock.__int__ = Mock(return_value=iter([]))
        self.assertRaises(AttributeError, set_int)

        mock = MagicMock(spec=Iterable)
        self.assertEqual(list(mock), [])
        self.assertRaises(AttributeError, set_int) 
Example #12
Source File: test_components_plugin.py    From skelebot with MIT License 6 votes vote down vote up
def test_execute(self, mock_zipfile, mock_makedirs, mock_exists, mock_expanduser):
        mock_expanduser.return_value = "test/dummy"
        mock_exists.return_value = False

        mock_zip = mock.MagicMock()
        mock_zipfile.ZipFile.return_value = mock_zip
        config = sb.objects.config.Config()
        args = argparse.Namespace(plugin="test.zip")

        plugin = sb.components.plugin.Plugin()
        plugin.execute(config, args)

        mock_zipfile.ZipFile.assert_called_with("test.zip", "r")
        mock_zip.extractall.assert_called()
        mock_zip.close.assert_called()

        mock_makedirs.assert_any_call("test/dummy", exist_ok=True) 
Example #13
Source File: test_docker_cache.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        logging.getLogger().setLevel(logging.DEBUG)

        # We need to be in the same directory than the script so the commands in the dockerfiles work as
        # expected. But the script can be invoked from a different path
        base = os.path.split(os.path.realpath(__file__))[0]
        os.chdir(base)

        docker_cache._login_dockerhub = MagicMock()  # Override login

        # Stop in case previous execution was dirty
        try:
            self._stop_local_docker_registry()
        except Exception:
            pass

        # Start up docker registry
        self._start_local_docker_registry() 
Example #14
Source File: test-distro.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def test_distro_detection(self):
        def os_path_exists(f):
            if f.endswith('multibootusb.log'):
                return False
            return True
        os_path_exists_mock = MM()
        log_mock = MM()
        @patch('os.path.exists', os_path_exists)
        @patch('scripts.distro.log', log_mock)
        def _():
            fn = distro.detect_iso_from_file_list
            assert fn(['BOOT.wim', 'Sources']) == 'Windows'
            assert fn(['BOOT.wim', 'Sause']) is None
            assert fn(['config.isoclient', 'foo']) == 'opensuse'
            assert fn(['bar', 'dban', 'foo']) == 'slitaz'
            assert fn(['memtest.img']) == 'memtest'
            assert fn(['mt86.png','isolinux']) == 'raw_iso'
            assert fn(['menu.lst']) == 'grub4dos'
            assert fn(['bootwiz.cfg', 'bootmenu_logo.png']) == \
                'grub4dos_iso'
        _() 
Example #15
Source File: test_html.py    From ciftify with MIT License 6 votes vote down vote up
def test_title_changed_to_include_image_name_when_title_given(self,
            mock_open, mock_add_header, mock_add_img_subj, mock_index,
            mock_exists, mock_writable):
        mock_file = MagicMock(spec=io.IOBase)
        mock_open.return_value.__enter__.return_value = mock_file
        mock_exists.return_value = False
        mock_writable.return_value = True
        qc_config = self.get_config_stub()

        html.write_index_pages(self.qc_dir, qc_config, self.subject,
                title='QC mode for image {}')

        for image in qc_config.images:
            name = image.name
            found = False
            for call in mock_index.call_args_list:
                if name in call[1]['title']:
                    found = True
            assert found 
Example #16
Source File: test_driver.py    From zun with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(CinderVolumeDriverTestCase, self).setUp()
        self.fake_uuid = uuidutils.generate_uuid()
        self.fake_volume_id = 'fake-volume-id'
        self.fake_devpath = '/fake-path'
        self.fake_mountpoint = '/fake-mountpoint'
        self.fake_container_path = '/fake-container-path'
        self.fake_conn_info = {
            'data': {'device_path': self.fake_devpath},
        }
        self.volmap = mock.MagicMock()
        self.volmap.volume.uuid = self.fake_uuid
        self.volmap.volume_provider = 'cinder'
        self.volmap.volume_id = self.fake_volume_id
        self.volmap.container_path = self.fake_container_path
        self.volmap.connection_info = jsonutils.dumps(self.fake_conn_info) 
Example #17
Source File: test_driver.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_attach_fail_attach(self, mock_cinder_workflow_cls,
                                mock_get_mountpoint, mock_ensure_tree,
                                mock_do_mount):
        mock_cinder_workflow = mock.MagicMock()
        mock_cinder_workflow_cls.return_value = mock_cinder_workflow
        mock_cinder_workflow.attach_volume.side_effect = \
            exception.ZunException()
        mock_get_mountpoint.return_value = self.fake_mountpoint

        volume_driver = driver.Cinder()
        self.volmap.connection_info = None
        self.assertRaises(exception.ZunException,
                          volume_driver.attach, self.context, self.volmap)

        mock_cinder_workflow.attach_volume.assert_called_once_with(self.volmap)
        mock_get_mountpoint.assert_not_called()
        mock_do_mount.assert_not_called()
        mock_cinder_workflow.detach_volume.assert_not_called() 
Example #18
Source File: test_driver.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_attach_fail_mount(self, mock_cinder_workflow_cls,
                               mock_get_mountpoint, mock_ensure_tree,
                               mock_do_mount):
        mock_cinder_workflow = mock.MagicMock()
        mock_cinder_workflow_cls.return_value = mock_cinder_workflow
        mock_cinder_workflow.attach_volume.return_value = self.fake_devpath
        mock_get_mountpoint.return_value = self.fake_mountpoint
        mock_do_mount.side_effect = exception.ZunException()

        volume_driver = driver.Cinder()
        self.volmap.connection_info = None
        self.assertRaises(exception.ZunException,
                          volume_driver.attach, self.context, self.volmap)

        mock_cinder_workflow.attach_volume.assert_called_once_with(self.volmap)
        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)
        mock_do_mount.assert_called_once_with(
            self.fake_devpath, self.fake_mountpoint, CONF.volume.fstype)
        mock_cinder_workflow.detach_volume.assert_called_once_with(
            self.context, self.volmap) 
Example #19
Source File: test_pci_passthrough_filters.py    From zun with Apache License 2.0 5 votes vote down vote up
def test_pci_passthrough_pass(self):
        pci_stats_mock = mock.MagicMock()
        pci_stats_mock.support_requests.return_value = True
        request = objects.ContainerPCIRequest(
            count=1, spec=[{'vendor_id': '8086'}])
        requests = objects.ContainerPCIRequests(requests=[request])
        container = objects.Container(self.context)
        host = HostState('testhost')
        host.pci_stats = pci_stats_mock
        extra_spec = {'pci_requests': requests}
        self.assertTrue(self.filt_cls.host_passes(host, container, extra_spec))
        pci_stats_mock.support_requests.assert_called_once_with(
            requests.requests) 
Example #20
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_title_used_when_given(self):
        html_page = MagicMock()
        qc_config = self.get_config_stub()
        title = 'THIS IS MY TITLE'

        html.add_page_header(html_page, qc_config, self.page_subject,
                title=title)

        for call in html_page.write.call_args_list:
            if '<TITLE>' in call[0]:
                assert title in call[0]
                assert self.page_subject not in call[0] 
Example #21
Source File: test_report.py    From zun with Apache License 2.0 5 votes vote down vote up
def test_put_allocations_retries_conflict(self, mock_put):
        failed = fake_requests.FakeResponse(
            status_code=409,
            content=jsonutils.dumps(
                {'errors': [{'code': 'placement.concurrent_update',
                             'detail': ''}]}))

        succeeded = mock.MagicMock()
        succeeded.status_code = 204

        mock_put.side_effect = (failed, succeeded)

        rp_uuid = mock.sentinel.rp
        consumer_uuid = mock.sentinel.consumer
        data = {"MEMORY_MB": 1024}
        expected_url = "/allocations/%s" % consumer_uuid
        payload = {
            "allocations": {
                rp_uuid: {"resources": data}
            },
            "project_id": mock.sentinel.project_id,
            "user_id": mock.sentinel.user_id,
            "consumer_generation": mock.sentinel.consumer_generation
        }
        resp = self.client.put_allocations(
            self.context, consumer_uuid, payload)
        self.assertTrue(resp)
        mock_put.assert_has_calls([
            mock.call(expected_url, payload, version='1.28',
                      global_request_id=self.context.global_id)] * 2) 
Example #22
Source File: test_migrations.py    From zun with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestWalkVersions, self).setUp()
        self.migration_api = mock.MagicMock()
        self.engine = mock.MagicMock()
        self.config = mock.MagicMock()
        self.versions = [mock.Mock(revision='2b2'), mock.Mock(revision='1a1')] 
Example #23
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_adds_qc_page_for_all_subjects_in_list(self):
        html_page = MagicMock()
        subjects = ['subject1', 'subject2', 'subject3']
        html_string = '<a href="{}/qc.html">'

        html.add_image_and_subject_index(html_page, [], subjects, 'test', 'testsubtitle')

        args_list = html_page.write.call_args_list

        for subject in subjects:
            assert self.call_found(html_page.write.call_args_list,
                    html_string.format(subject)) 
Example #24
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_image_not_added_to_index_if_image_settings_exclude_it(self):
        html_page = MagicMock()
        image1 = self.__make_image_stub('temporal')
        image2 = self.__make_image_stub('medial', make=False)
        image3 = self.__make_image_stub('mpfc')
        images = [image1, image2, image3]

        html.add_image_and_subject_index(html_page, images, [], 'test', 'testsubtitle')

        image_link = '<a href="{}.html">'.format(image2.name)
        assert html_page.write.call_count > 1
        for call in html_page.write.call_args_list:
            assert image_link not in call[0] 
Example #25
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_adds_all_expected_images_to_page(self):
        html_page = MagicMock()
        image1 = self.__make_image_stub('temporal')
        image2 = self.__make_image_stub('medial')
        images = [image1, image2]

        html.add_image_and_subject_index(html_page, images, [], 'test', 'testsubtitle')

        image_link = '<a href="{}.html">'
        for image in images:
            assert self.call_found(html_page.write.call_args_list,
                    image_link.format(image.name)) 
Example #26
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_items_marked_active_if_activelink_set(self):
        html_page = MagicMock()
        active_item = self.nav_list[1]['href']

        html.write_navbar(html_page, self.brand_name, self.nav_list,
                activelink=active_item)

        for call in html_page.call_args_list:
            html_string = call[0]
            if active_item in html_string:
                assert 'class="active"' in html_string 
Example #27
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_no_items_marked_active_if_activelink_not_set(self):
        html_page = MagicMock()

        html.write_navbar(html_page, self.brand_name, self.nav_list)
        for call in html_page.write.call_args_list:
            assert 'class="active"' not in call[0] 
Example #28
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_doesnt_write_images_if_make_index_is_false(self, mock_open,
            mock_add_header, mock_add_img_subj, mock_index, mock_exists,
            mock_writable):
        mock_file = MagicMock(spec=io.IOBase)
        mock_open.return_value.__enter__.return_value = mock_file
        qc_config = self.get_config_stub(make_all=False)
        mock_exists.return_value = False
        mock_writable.return_value = True

        html.write_index_pages(self.qc_dir, qc_config, self.subject)

        # One image in the list should have 'make_index' = False
        expected_writes = len(qc_config.images) - 1
        assert mock_index.call_count == expected_writes 
Example #29
Source File: test_html.py    From ciftify with MIT License 5 votes vote down vote up
def test_writes_images_to_index(self, mock_open, mock_add_header,
            mock_add_img_subj, mock_index, mock_exists, mock_writable):
        mock_file = MagicMock(spec=io.IOBase)
        mock_open.return_value.__enter__.return_value = mock_file
        mock_exists.return_value = False
        mock_writable.return_value = True

        qc_config = self.get_config_stub()

        html.write_index_pages(self.qc_dir, qc_config, self.subject)

        expected_writes = len(qc_config.images)
        assert mock_index.call_count == expected_writes 
Example #30
Source File: conftest.py    From selfmailbot with MIT License 5 votes vote down vote up
def tg_photo_size(tg_photo_file):
    """telegram.PhotoSize"""
    return lambda **kwargs: factory(
        'PhotoSize',
        file_id='__randint',
        width=1,
        height=1,
        download=MagicMock(return_value=tg_photo_file()),
        get_file=MagicMock(return_value=tg_photo_file()),
        **kwargs,
    )()