• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mock.NonCallableMock类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mock.NonCallableMock的典型用法代码示例。如果您正苦于以下问题:Python NonCallableMock类的具体用法?Python NonCallableMock怎么用?Python NonCallableMock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了NonCallableMock类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get

    def get(self, **params):
        request = NonCallableMock(spec_set=[
            "write", "finish", "setResponseCode", "setHeader", "args",
            "method", "processing"
        ])

        request.method = "GET"
        request.args = {k: [v] for k, v in params.items()}

        @contextlib.contextmanager
        def processing():
            yield
        request.processing = processing

        yield self.resource._async_render_GET(request)
        self.assertTrue(request.finish.called)

        if request.setResponseCode.called:
            response_code = request.setResponseCode.call_args[0][0]
        else:
            response_code = 200

        response_json = "".join(
            call[0][0] for call in request.write.call_args_list
        )
        response_body = json.loads(response_json)

        if response_code == 200:
            self.check_response(response_body)

        defer.returnValue((response_code, response_body))
开发者ID:pombredanne,项目名称:synapse-2,代码行数:31,代码来源:test_resource.py


示例2: test_volume_export

    def test_volume_export(self, mockrepo):
        mockobj = NonCallableMock()
        mockobj.pid = 'vol:1'
        mockobj.title = 'Lecoq, the detective'
        mockobj.volume = 'V.1'
        mockobj.date = ['1801']
        mockrepo.return_value.get_object.return_value = mockobj
        # to support for last modified conditional
        mockobj.ocr.created = datetime.now()

        # anonymous
        export_url = reverse('books:webexport', kwargs={'pid': mockobj.pid})
        response = self.client.get(export_url)
        self.assertContains(response,
            '''<div class="alert alert-warning">Export functionality is only available
      to logged in users.</div>''',
            msg_prefix='Anonymous user should see warning when viewing export page',
            html=True)

        # log in as a regular user
        self.client.login(**self.user_credentials['user'])
        response = self.client.get(export_url)
        self.assert_('export_form' in response.context,
            'export form should be set in response context for logged in user')
        self.assertContains(response, 'Export to GitHub requires a GitHub account.',
            msg_prefix='user should see a warning about github account')
开发者ID:emory-libraries,项目名称:readux,代码行数:26,代码来源:views.py


示例3: STALE_test_invite_join_public

    def STALE_test_invite_join_public(self):
        room_id = "#foo:blue"
        user_id = "@bob:red"
        target_user_id = "@bob:red"
        content = {"membership": Membership.JOIN}

        event = self.hs.get_event_factory().create_event(
            etype=RoomMemberEvent.TYPE,
            user_id=user_id,
            target_user_id=target_user_id,
            room_id=room_id,
            membership=Membership.JOIN,
            content=content,
        )

        joined = ["red", "blue", "green"]

        self.state_handler.handle_new_event.return_value = defer.succeed(True)
        self.datastore.get_joined_hosts_for_room.return_value = (
            defer.succeed(joined)
        )

        store_id = "store_id_fooo"
        self.datastore.store_room_member.return_value = defer.succeed(store_id)
        self.datastore.get_room.return_value = defer.succeed(None)

        prev_state = NonCallableMock(name="prev_state")
        prev_state.membership = Membership.INVITE
        prev_state.sender = "@foo:blue"
        self.datastore.get_room_member.return_value = defer.succeed(prev_state)

        # Actual invocation
        yield self.room_member_handler.change_membership(event)

        self.assertTrue(self.federation.handle_new_event.called)
        args = self.federation.handle_new_event.call_args[0]
        invite_join_event = args[0]

        self.assertTrue(InviteJoinEvent.TYPE, invite_join_event.TYPE)
        self.assertTrue("blue", invite_join_event.target_host)
        self.assertTrue("foo", invite_join_event.room_id)
        self.assertTrue(user_id, invite_join_event.user_id)
        self.assertFalse(hasattr(invite_join_event, "state_key"))

        self.assertEquals(
            set(["blue"]),
            set(invite_join_event.destinations)
        )

        self.federation.get_state_for_room.assert_called_once_with(
            "blue", "foo"
        )

        self.assertFalse(self.datastore.store_room_member.called)

        self.assertFalse(self.notifier.on_new_room_event.called)
        self.assertFalse(self.state_handler.handle_new_event.called)
开发者ID:gitter-badger,项目名称:synapse,代码行数:57,代码来源:test_room.py


示例4: _inject_mock_invalid_consumer

    def _inject_mock_invalid_consumer(self, uuid=None):
        """For chaning injected consumer identity to one that fails is_valid()

        Returns the injected identity if it need to be examined.
        """
        invalid_identity = NonCallableMock(name='InvalidIdentityMock')
        invalid_identity.is_valid = Mock(return_value=False)
        invalid_identity.uuid = uuid or "INVALIDCONSUMERUUID"
        inj.provide(inj.IDENTITY, invalid_identity)
        return invalid_identity
开发者ID:MichaelMraka,项目名称:subscription-manager,代码行数:10,代码来源:fixture.py


示例5: test_clean_up_remove_68_pem

 def test_clean_up_remove_68_pem(self, mock_remove, mock_isfile):
     mock_product_directory = NonCallableMock(spec=ProductDirectory)
     mock_product_directory.path = "/some/path"
     inj.provide(inj.PROD_DIR, mock_product_directory)
     self.engine.db = MagicMock()
     mock_isfile.side_effect = iter([True, True])
     self.engine.clean_up([])
     mock_remove.assert_called_with("/some/path/68.pem")
     self.engine.db.delete.assert_called_with("68")
     self.engine.db.write.assert_called_with()
开发者ID:belonesox,项目名称:subscription-manager,代码行数:10,代码来源:test_migration.py


示例6: _inject_mock_valid_consumer

    def _inject_mock_valid_consumer(self, uuid=None):
        """For changing injected consumer identity to one that passes is_valid()

        Returns the injected identity if it need to be examined.
        """
        identity = NonCallableMock(name='ValidIdentityMock')
        identity.uuid = uuid or "VALIDCONSUMERUUID"
        identity.is_valid = Mock(return_value=True)
        identity.cert_dir_path = "/not/a/real/path/to/pki/consumer/"
        inj.provide(inj.IDENTITY, identity)
        return identity
开发者ID:darinlively,项目名称:subscription-manager,代码行数:11,代码来源:fixture.py


示例7: setUp

    def setUp(self):
        # By default mock that we are registered. Individual test cases
        # can override if they are testing disconnected scenario.
        id_mock = NonCallableMock(name='FixtureIdentityMock')
        id_mock.exists_and_valid = Mock(return_value=True)
        id_mock.uuid = 'fixture_identity_mock_uuid'
        id_mock.name = 'fixture_identity_mock_name'

        # Don't really care about date ranges here:
        self.mock_calc = NonCallableMock()
        self.mock_calc.calculate.return_value = None

        inj.provide(inj.IDENTITY, id_mock)
        inj.provide(inj.PRODUCT_DATE_RANGE_CALCULATOR, self.mock_calc)

        inj.provide(inj.ENTITLEMENT_STATUS_CACHE, stubs.StubEntitlementStatusCache())
        inj.provide(inj.PROD_STATUS_CACHE, stubs.StubProductStatusCache())
        inj.provide(inj.OVERRIDE_STATUS_CACHE, stubs.StubOverrideStatusCache())
        inj.provide(inj.PROFILE_MANAGER, stubs.StubProfileManager())
        # By default set up an empty stub entitlement and product dir.
        # Tests need to modify or create their own but nothing should hit
        # the system.
        self.ent_dir = stubs.StubEntitlementDirectory()
        inj.provide(inj.ENT_DIR, self.ent_dir)
        self.prod_dir = stubs.StubProductDirectory()
        inj.provide(inj.PROD_DIR, self.prod_dir)

        # Installed products manager needs PROD_DIR injected first
        inj.provide(inj.INSTALLED_PRODUCTS_MANAGER, stubs.StubInstalledProductsManager())

        self.stub_cp_provider = stubs.StubCPProvider()
        self._release_versions = []
        self.stub_cp_provider.content_connection.get_versions = self._get_release_versions

        inj.provide(inj.CP_PROVIDER, self.stub_cp_provider)
        inj.provide(inj.CERT_SORTER, stubs.StubCertSorter())

        # setup and mock the plugin_manager
        plugin_manager_mock = Mock(name='FixturePluginManagerMock')
        inj.provide(inj.PLUGIN_MANAGER, plugin_manager_mock)
        inj.provide(inj.DBUS_IFACE, Mock(name='FixtureDbusIfaceMock'))

        pooltype_cache = Mock()
        inj.provide(inj.POOLTYPE_CACHE, pooltype_cache)
        # don't use file based locks for tests
        inj.provide(inj.ACTION_LOCK, RLock)

        self.stub_facts = stubs.StubFacts()
        inj.provide(inj.FACTS, self.stub_facts)

        self.dbus_patcher = patch('subscription_manager.managercli.CliCommand._request_validity_check')
        self.dbus_patcher.start()
开发者ID:aweiteka,项目名称:subscription-manager,代码行数:52,代码来源:fixture.py


示例8: test_clean_up_remove_180_pem

    def test_clean_up_remove_180_pem(self, mock_remove, mock_isfile):
        mock_product_directory = NonCallableMock(spec=ProductDirectory)
        mock_product_directory.path = "/some/path"
        inj.provide(inj.PROD_DIR, mock_product_directory)

        self.engine.db = MagicMock()
        mock_isfile.side_effect = iter([False, False])
        self.engine.clean_up([
            "rhel-i386-client-dts-5-beta",
            "rhel-i386-client-dts-5",
            ])
        mock_remove.assert_called_with("/some/path/180.pem")
        self.engine.db.delete.assert_called_with("180")
        self.engine.db.write.assert_called_with()
开发者ID:belonesox,项目名称:subscription-manager,代码行数:14,代码来源:test_migration.py


示例9: test_update_button_disabled

    def test_update_button_disabled(self):
        # Need an unregistered consumer object:
        id_mock = NonCallableMock()
        id_mock.name = None
        id_mock.uuid = None

        def new_identity():
            return id_mock
        provide(IDENTITY, new_identity)

        dialog = factsgui.SystemFactsDialog()
        dialog.show()

        enabled = dialog.update_button.get_property('sensitive')

        self.assertFalse(enabled)
开发者ID:Januson,项目名称:subscription-manager,代码行数:16,代码来源:test_facts_gui.py


示例10: setUp

 def setUp(self):
     self.mock_notifier = NonCallableMock(MeetmeServiceNotifier)
     self.ami_class = Mock(xivo_ami.AMIClass)
     self.manager = service_manager.MeetmeServiceManager(
         self.mock_notifier,
         self.ami_class,
     )
     self.mock_manager = NonCallableMock(MeetmeServiceManager)
     context.register('meetme_service_notifier', self.mock_notifier)
     context.register('meetme_service_manager', self.mock_manager)
开发者ID:gorocacher,项目名称:xivo-ctid,代码行数:10,代码来源:test_meetme_service_manager.py


示例11: _mock_response

 def _mock_response(self):
     response = NonCallableMock()
     response._headers = {}
     response.status_code = 200
     response.queries = []
     response.get = response._headers.get
     response.content = ""
     return response
开发者ID:auvipy,项目名称:silk,代码行数:8,代码来源:test_config_meta.py


示例12: test_pushapps_noatomic

def test_pushapps_noatomic(discover_apps_, hook, document_):
    '''
    Test case for pushapps with ``--no-atomic``

    Algo:
    1. discover apps

    #. for each app
        1. pre-push
        2. push
        3. post-push
    '''
    conf = NonCallableMock(name='conf')
    dest = 'http://localhost:5984'
    doc = document_()
    dbs = conf.get_dbs()

    ret_code = commands.pushapps(conf, '/mock_dir', dest, no_atomic=True)
    assert ret_code == 0
    conf.get_dbs.assert_called_with(dest)
    hook.assert_any_call(conf, 'foo', 'pre-push', dbs=dbs, pushapps=True)
    hook.assert_any_call(conf, 'foo', 'post-push', dbs=dbs, pushapps=True)
    doc.push.assert_called_with(dbs, True, False)
开发者ID:couchapp,项目名称:couchapp,代码行数:23,代码来源:test_commands.py


示例13: test_pushapps_export

def test_pushapps_export(discover_apps_, hook, document_, dumps):
    '''
    Test case for pushapps with ``--export``,

    Algo:
    1. discover apps
    #. pre-push
    #. add app to a list ``apps``
    #. post-push
    #. json.dumps from apps
    '''
    conf = NonCallableMock(name='conf')
    dest = None

    ret_code = commands.pushapps(conf, '/mock_dir', dest, export=True)

    assert ret_code == 0
    discover_apps_.assert_called_with('/mock_dir')
    hook.assert_any_call(conf, 'foo', 'pre-push',
                         dbs=conf.get_dbs(), pushapps=True)
    hook.assert_any_call(conf, 'foo', 'post-push',
                         dbs=conf.get_dbs(), pushapps=True)
    assert dumps.called
开发者ID:gbn972,项目名称:couchapp,代码行数:23,代码来源:test_commands.py


示例14: test_pushapps_output

def test_pushapps_output(discover_apps_, hook, document_, write_json):
    '''
    Test case for pushapps with ``--export --output file``

    Algo:
    1. discover apps
    #. pre-push
    #. add app to a list ``apps``
    #. post-push
    #. write_json(apps)
    '''
    conf = NonCallableMock(name='conf')
    dest = None

    ret_code = commands.pushapps(conf, '/mock_dir', dest, export=True, output='file')

    assert ret_code == 0
    discover_apps_.assert_called_with('/mock_dir')
    hook.assert_any_call(conf, 'foo', 'pre-push',
                         dbs=conf.get_dbs(), pushapps=True)
    hook.assert_any_call(conf, 'foo', 'post-push',
                         dbs=conf.get_dbs(), pushapps=True)
    'file' in write_json.call_args[0]
开发者ID:gbn972,项目名称:couchapp,代码行数:23,代码来源:test_commands.py


示例15: test_volume_pages

    def test_volume_pages(self, mockpaginator, mockrepo):
        mockvol = NonCallableMock(spec=Volume)
        mockvol.pid = 'vol:1'
        mockvol.title = 'Lecoq, the detective'
        mockvol.date = ['1801']
        # second object retrieved from fedora is page, for layout
        mockvol.width = 150
        mockvol.height = 200
        # volume url needed to identify annotations for pages in this volume
        mockvol.get_absolute_url.return_value = reverse('books:volume',
            kwargs={'pid': mockvol.pid})
        mockrepo.return_value.get_object.return_value = mockvol
        mockvol.find_solr_pages = MagicMock()
        mockvol.find_solr_pages.return_value.count = 3
        mockvol.find_solr_pages.__len__.return_value = 3
        mockpage = Mock(width=640, height=400)
        mockvol.pages = [mockpage]

        vol_page_url = reverse('books:pages', kwargs={'pid': mockvol.pid})
        response = self.client.get(vol_page_url)
        # volume method should be used to find pages
        self.assert_(call() in mockvol.find_solr_pages.call_args_list)
        # volume should be set in context
        self.assert_(mockvol, response.context['vol'])
        # annotated pages should be empty for anonymous user
        self.assertEqual({}, response.context['annotated_pages'])

        # log in as a regular user
        self.client.login(**self.user_credentials['user'])
        testuser = get_user_model().objects.get(username=self.user_credentials['user']['username'])

        page1_url = reverse('books:page', kwargs={'vol_pid': mockvol.pid, 'pid': 'page:1'})
        page2_url = reverse('books:page', kwargs={'vol_pid': mockvol.pid, 'pid': 'page:2'})
        page3_url = reverse('books:page', kwargs={'vol_pid': mockvol.pid, 'pid': 'page:3'})
        mockvol.page_annotation_count.return_value = {
          absolutize_url(page1_url): 5,
          absolutize_url(page2_url): 2,
          page3_url: 13
        }
        response = self.client.get(vol_page_url)
        mockvol.page_annotation_count.assert_called_with(testuser)
        annotated_pages = response.context['annotated_pages']
        # counts should be preserved; urls should be non-absolute
        # whether they started that way or not
        self.assertEqual(5, annotated_pages[absolutize_url(page1_url)])
        self.assertEqual(2, annotated_pages[absolutize_url(page2_url)])
        self.assertEqual(13, annotated_pages[page3_url])
开发者ID:emory-libraries,项目名称:readux,代码行数:47,代码来源:views.py


示例16: MockEvent

def MockEvent(**kwargs):
    ev = NonCallableMock(spec_set=kwargs.keys())
    ev.configure_mock(**kwargs)
    return ev
开发者ID:roblabla,项目名称:synapse,代码行数:4,代码来源:test_filtering.py


示例17: mock_auctions_server

def mock_auctions_server(request, mocker):
    params = getattr(request, 'param', {})

    server_config_redis = params.get('server_config_redis', DEFAULT)
    connection_limit = params.get('connection_limit', DEFAULT)
    get_mapping = params.get('get_mapping', DEFAULT)
    proxy_path = params.get('proxy_path', DEFAULT)
    event_sources_pool = params.get('event_sources_pool', DEFAULT)
    proxy_connection_pool = params.get('proxy_connection_pool', DEFAULT)
    stream_proxy = params.get('stream_proxy', DEFAULT)
    db = params.get('db', DEFAULT)
    request_headers = params.get('request_headers', [])
    request_url = params.get('request_url', DEFAULT)
    redirect_url = params.get('redirect_url', DEFAULT)
    abort = params.get('abort', DEFAULT)

    class AuctionsServerAttributesContainer(object):
        logger = NotImplemented
        proxy_mappings = NotImplemented
        config = NotImplemented
        event_sources_pool = NotImplemented
        proxy_connection_pool = NotImplemented
        get_mapping = NotImplemented
        db = NotImplemented
        request_headers = NotImplemented

    class Request(object):
        headers = NotImplemented
        environ = NotImplemented
        url = NotImplemented

    class Config(object):
        __getitem__ = NotImplemented

    def config_getitem(item):
        if item == 'REDIS':
            return server_config_redis
        elif item == 'event_source_connection_limit':
            return connection_limit
        else:
            raise KeyError

    mock_path_info = MagicMock()

    def environ_setitem(item, value):
        if item == 'PATH_INFO':
            mock_path_info(value)
            return value
        else:
            raise KeyError

    mocker.patch.object(auctions_server_module, 'get_mapping', get_mapping)
    patch_pysse = mocker.patch.object(auctions_server_module, 'PySse',
                                      spec_set=PySse)
    patch_add_message = patch_pysse.return_value.add_message

    patch_request = mocker.patch.object(auctions_server_module, 'request',
                                        spec_set=Request)
    patch_request.environ.__setitem__.side_effect = environ_setitem
    patch_request.headers = request_headers
    patch_request.url = request_url

    patch_redirect = mocker.patch.object(auctions_server_module, 'redirect',
                                         return_value=redirect_url)
    patch_abort = mocker.patch.object(auctions_server_module, 'abort',
                                      return_value=abort)

    patch_StreamProxy = \
        mocker.patch.object(auctions_server_module, 'StreamProxy',
                            return_value=stream_proxy)

    auctions_server = NonCallableMock(spec_set=
                                      AuctionsServerAttributesContainer)

    logger = MagicMock(spec_set=frontend.logger)
    proxy_mappings = MagicMock(spec_set=Memoizer({}))
    proxy_mappings.get.return_value = proxy_path
    config = MagicMock(spec_set=Config)
    config.__getitem__.side_effect = config_getitem

    auctions_server.logger = logger
    auctions_server.proxy_mappings = proxy_mappings
    auctions_server.config = config
    auctions_server.event_sources_pool = event_sources_pool
    auctions_server.proxy_connection_pool = proxy_connection_pool
    auctions_server.db = db

    mocker.patch.object(auctions_server_module, 'auctions_server',
                        auctions_server)

    return {'server': auctions_server,
            'proxy_mappings': proxy_mappings,
            'mock_path_info': mock_path_info,
            'patch_StreamProxy': patch_StreamProxy,
            'patch_redirect': patch_redirect,
            'patch_abort': patch_abort,
            'patch_PySse': patch_pysse,
            'patch_add_message': patch_add_message}
开发者ID:openprocurement,项目名称:openprocurement.auction,代码行数:98,代码来源:conftest.py


示例18: setUp

    def setUp(self):
        # By default mock that we are registered. Individual test cases
        # can override if they are testing disconnected scenario.
        id_mock = NonCallableMock(name='FixtureIdentityMock')
        id_mock.exists_and_valid = Mock(return_value=True)
        id_mock.uuid = 'fixture_identity_mock_uuid'
        id_mock.name = 'fixture_identity_mock_name'
        id_mock.cert_dir_path = "/not/a/real/path/to/pki/consumer/"

        # Don't really care about date ranges here:
        self.mock_calc = NonCallableMock()
        self.mock_calc.calculate.return_value = None

        # Avoid trying to read real /etc/yum.repos.d/redhat.repo
        self.mock_repofile_path_exists_patcher = patch('subscription_manager.repolib.RepoFile.path_exists')
        mock_repofile_path_exists = self.mock_repofile_path_exists_patcher.start()
        mock_repofile_path_exists.return_value = True

        inj.provide(inj.IDENTITY, id_mock)
        inj.provide(inj.PRODUCT_DATE_RANGE_CALCULATOR, self.mock_calc)

        inj.provide(inj.ENTITLEMENT_STATUS_CACHE, stubs.StubEntitlementStatusCache())
        inj.provide(inj.PROD_STATUS_CACHE, stubs.StubProductStatusCache())
        inj.provide(inj.OVERRIDE_STATUS_CACHE, stubs.StubOverrideStatusCache())
        inj.provide(inj.RELEASE_STATUS_CACHE, stubs.StubReleaseStatusCache())
        inj.provide(inj.PROFILE_MANAGER, stubs.StubProfileManager())
        # By default set up an empty stub entitlement and product dir.
        # Tests need to modify or create their own but nothing should hit
        # the system.
        self.ent_dir = stubs.StubEntitlementDirectory()
        inj.provide(inj.ENT_DIR, self.ent_dir)
        self.prod_dir = stubs.StubProductDirectory()
        inj.provide(inj.PROD_DIR, self.prod_dir)

        # Installed products manager needs PROD_DIR injected first
        inj.provide(inj.INSTALLED_PRODUCTS_MANAGER, stubs.StubInstalledProductsManager())

        self.stub_cp_provider = stubs.StubCPProvider()
        self._release_versions = []
        self.stub_cp_provider.content_connection.get_versions = self._get_release_versions

        inj.provide(inj.CP_PROVIDER, self.stub_cp_provider)
        inj.provide(inj.CERT_SORTER, stubs.StubCertSorter())

        # setup and mock the plugin_manager
        plugin_manager_mock = MagicMock(name='FixturePluginManagerMock')
        plugin_manager_mock.runiter.return_value = iter([])
        inj.provide(inj.PLUGIN_MANAGER, plugin_manager_mock)
        inj.provide(inj.DBUS_IFACE, Mock(name='FixtureDbusIfaceMock'))

        pooltype_cache = Mock()
        inj.provide(inj.POOLTYPE_CACHE, pooltype_cache)
        # don't use file based locks for tests
        inj.provide(inj.ACTION_LOCK, RLock)

        self.stub_facts = stubs.StubFacts()
        inj.provide(inj.FACTS, self.stub_facts)

        self.dbus_patcher = patch('subscription_manager.managercli.CliCommand._request_validity_check')
        self.dbus_patcher.start()
        # No tests should be trying to connect to any configure or test server
        # so really, everything needs this mock. May need to be in __init__, or
        # better, all test classes need to use SubManFixture
        self.is_valid_server_patcher = patch("subscription_manager.managercli.is_valid_server_info")
        is_valid_server_mock = self.is_valid_server_patcher.start()
        is_valid_server_mock.return_value = True
        # No tests should be trying to test the proxy connection
        # so really, everything needs this mock. May need to be in __init__, or
        # better, all test classes need to use SubManFixture
        self.test_proxy_connection_patcher = patch("subscription_manager.managercli.CliCommand.test_proxy_connection")
        test_proxy_connection_mock = self.test_proxy_connection_patcher.start()
        test_proxy_connection_mock.return_value = True

        self.files_to_cleanup = []
开发者ID:darinlively,项目名称:subscription-manager,代码行数:74,代码来源:fixture.py


示例19: test_search

    def test_search(self, mockqs_paginate, mocksolr_interface, mockpaginator):
        mockpage = NonCallableMock()
        search_url = reverse('books:search')

        # NOTE: pagination now happens in django's class-based view,
        # so must be mocked there
        mockqs_paginate.return_value = (mockpaginator.return_value,
            mockpage, [], False)

        # no search terms - invalid form
        response = self.client.get(search_url)
        self.assertContains(response, 'Please enter one or more search terms')

        mocksolr = mocksolr_interface.return_value
        # simulate sunburnt's fluid interface
        mocksolr.query.return_value = mocksolr.query
        for method in ['query', 'facet_by', 'sort_by', 'field_limit',
                       'exclude', 'filter', 'join', 'paginate', 'results_as',
                       'facet_query']:
            getattr(mocksolr.query, method).return_value = mocksolr.query

        # set up mock results for collection query and facet counts
        solr_result = NonCallableMagicMock(spec_set=['__iter__', 'facet_counts'])
        # *only* mock iter, to avoid weirdness with django templates & callables
        solr_result.__iter__.return_value = [
            SolrVolume(**{'pid': 'vol:1', 'title': 'Lecoq, the detective', 'pdf_size': 1024}),
            SolrVolume(**{'pid': 'vol:2', 'title': 'Mabel Meredith', 'pdf_size': 34665}),
        ]
        mocksolr.query.__iter__.return_value = iter(solr_result)
        mocksolr.count.return_value = 2
        # mock facets
        # solr_result.facet_counts.facet_fields = {
        #     'collection_label_facet': [('Civil War Literature', 2), ('Yellowbacks', 4)]
        # }

        # use a noncallable for the pagination result that is used in the template
        # because passing callables into django templates does weird things

        mockpaginator.return_value.page.return_value = mockpage
        results = NonCallableMagicMock(spec=['__iter__', 'facet_counts', '__len__'])

        results.__iter__.return_value = iter(solr_result)
        results.facet_counts.facet_fields = {
            'collection_label_facet': [('Emory Yearbooks', 1), ('Yellowbacks', 4)]
        }
        results.__len__.return_value = 2

        mockpage.object_list = results
        mockpage.has_other_pages = False
        mockpage.paginator.count = 2
        mockpage.paginator.page_range = [1]
        mockpaginator.return_value.count = 2
        mockpaginator.return_value.page_range = [1]
        mockqs_paginate.return_value = (mockpaginator.return_value, mockpage, results, True)

        # query with search terms
        response = self.client.get(search_url, {'keyword': 'yellowbacks'})

        mocksolr.query.filter.assert_called_with(content_model=Volume.VOLUME_CMODEL_PATTERN)
        # because of creator/title search boosting, actual query is a little difficult to test
        mocksolr.Q.assert_any_call('yellowbacks')
        mocksolr.Q.assert_any_call(creator='yellowbacks')
        mocksolr.Q.assert_any_call(title='yellowbacks')
        # not sure how to test query on Q|Q**3|Q**3
        mocksolr.query.field_limit.assert_called_with(SolrVolume.necessary_fields,
            score=True)

        # check that unapi / zotero harvest is enabled
        self.assertContains(response,
            '<link rel="unapi-server" type="application/xml" title="unAPI" href="%s" />' % \
            reverse('books:unapi'),
            html=True,
            msg_prefix='link to unAPI server URL should be specified in header')

        # check that items are displayed
        for item in solr_result:
            self.assertContains(response, item['title'],
                msg_prefix='title should be displayed')
            self.assertContains(response, unquote(reverse('books:pdf', kwargs={'pid': item['pid']})),
                    msg_prefix='link to pdf should be included in response')
            self.assertContains(response,
                '<abbr class="unapi-id" title="%s"></abbr>' % item['pid'],
                msg_prefix='unapi item id for %s should be included to allow zotero harvest' \
                           % item['pid'])
            # pdf size
            self.assertContains(response, filesizeformat(item['pdf_size']),
                msg_prefix='PDF size should be displayed in human-readable format')

        # check that collection facets are displayed / linked
        for coll, count in results.facet_counts.facet_fields['collection_label_facet']:
            self.assertContains(response, coll,
                msg_prefix='collection facet label should be displayed on search results page')
            # not a very definitive test, but at least check the number is displayed
            self.assertContains(response, count,
                msg_prefix='collection facet count should be displayed on search results page')
            self.assertContains(response,
                '?keyword=yellowbacks&amp;collection=%s' % coll.replace(' ', '%20'),
                msg_prefix='response should include link to search filtered by collection facet')

        # multiple terms and phrase
#.........这里部分代码省略.........
开发者ID:emory-libraries,项目名称:readux,代码行数:101,代码来源:views.py


示例20: test_volume

    def test_volume(self, mockrepo):
        mockobj = NonCallableMock()
        mockobj.pid = 'vol:1'
        mockobj.title = 'Lecoq, the detective'
        mockobj.volume = 'V.1'
        mockobj.date = ['1801']
        mockobj.creator = ['Gaboriau, Emile']
        mockobj.book.dc.content.description_list = [
           'Translation of: Monsieur Lecoq.',
           'Victorian yellowbacks + paperbacks, 1849-1905'
        ]
        mockobj.book.dc.content.publisher = 'London : Vizetelly'
        mockobj.book.volume_set = [mockobj, NonCallableMock(pid='vol:2')]
        mockobj.pdf_size = 1024
        mockobj.has_pages = False
        mockobj.is_a_volume = True
        mockrepo.return_value.get_object.return_value = mockobj
        # to support for last modified conditional
        mockobj.ocr.created = datetime.now()

        vol_url = reverse('books:volume', kwargs={'pid': mockobj.pid})
        response = self.client.get(vol_url)
        self.assertContains(response, mockobj.title,
            msg_prefix='response should include title')
        self.assertContains(response, mockobj.volume,
            msg_prefix='response should include volume label')
        self.assertContains(response, mockobj.date[0],
            msg_prefix='response should include date')
        self.assertContains(response, mockobj.creator[0],
            msg_prefix='response should include creator')
        for desc in mockobj.book.dc.content.description_list:
            self.assertContains(response, desc,
                msg_prefix='response should include dc:description')
        self.assertContains(response, mockobj.book.dc.content.publisher,
            msg_prefix='response should include publisher')
        self.assertContains(response, reverse('books:pdf', kwargs={'pid': mockobj.pid}),
            msg_prefix='response should include link to pdf')
        # related volumes
        self.assertContains(response, 'Related volumes',
            msg_prefix='response should include related volumes when present')
        self.assertContains(response,
            reverse('books:volume', kwargs={'pid': mockobj.book.volume_set[0].pid}),
            msg_prefix='response should link to related volumes')
        # pdf size
        self.assertContains(response, filesizeformat(mockobj.pdf_size),
            msg_prefix='PDF size should be displayed in human-readable format')
        # no pages loaded, should not include volume search or read online
        self.assertNotContains(response, 'Read online',
            msg_prefix='volume without pages loaded should not display read online option')
        # NOTE: href needed to differentiate from cover url, which starts the same
        self.assertNotContains(response, 'href="%s"' % reverse('books:pages', kwargs={'pid': mockobj.pid}),
            msg_prefix='volume without pages loaded should not have link to read online')
        self.assertNotContains(response, '<form id="volume-search" ',
            msg_prefix='volume without pages loaded should not have volume search')

        # annotation total passed to context
        self.assert_('annotated_volumes' not in response.context,
            'annotation count should not be set for volumes without pages')

        # simulate volume with pages loaded
        mockobj.has_pages = True
        # to test annotation count
        mockobj.get_absolute_url.return_value = '/books/vol:1/'
        mockobj.annotation_count.return_value = 5

        response = self.client.get(vol_url)
        # *should* include volume search and read online
        self.assertContains(response, 'Read online',
            msg_prefix='volume with pages loaded should display read online option')
        self.assertContains(response, reverse('books:pages', kwargs={'pid': mockobj.pid}),
            msg_prefix='volume with pages loaded should have link to read online')
        self.assertContains(response, '<form id="volume-search" ',
            msg_prefix='volume without pages loaded should have volume search')
        # annotation total passed to context
        self.assertEqual({mockobj.get_absolute_url(): 5},
            response.context['annotated_volumes'],
            'annotation count should be set for volumes with pages')

        mockobj.annotation_count.return_value = 0
        response = self.client.get(vol_url)
        self.assert_('annotated_volumes' not in response.context,
            'annotation count should not be set in context when it is zero')

        # non-existent should 404
        mockobj.exists = False
        response = self.client.get(vol_url)
        expected, got = 404, response.status_code
        self.assertEqual(expected, got,
            'expected %s for %s when object does not exist, got %s' % \
            (expected, vol_url, got))
        # exists but isn't a volume - should also 404
        mockobj.exists = True
        mockobj.is_a_volume = False
        response = self.client.get(vol_url)
        expected, got = 404, response.status_code
        self.assertEqual(expected, got,
            'expected %s for %s when object is not a volume, got %s' % \
            (expected, vol_url, got))
开发者ID:emory-libraries,项目名称:readux,代码行数:98,代码来源:views.py



注:本文中的mock.NonCallableMock类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mock.PropertyMock类代码示例发布时间:2022-05-27
下一篇:
Python mock.NonCallableMagicMock类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap