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

Python minimock.mock函数代码示例

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

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



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

示例1: setUp

 def setUp(self):
     super(StartStateMachineTests, self).setUp()
     filename = 'test-TaskQueueFSMTests.yaml'
     setUpByFilename(self, filename)
     self.machineName = getMachineNameByFilename(filename)
     self.mockQueue = TaskQueueDouble()
     mock(name='Queue.add', returns_func=self.mockQueue.add, tracker=None)
开发者ID:iki,项目名称:fantasm,代码行数:7,代码来源:fsm_test.py


示例2: test_cb

    def test_cb(self):
        """Callback from proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one', returns=('token', 'frob'))

        def _bad_api(auth_response):
            raise FlickrError('Error: 108: Invalid frob')

        minimock.mock('flickrapi.FlickrAPI.get_token_part_two',
                      returns_func=_bad_api)

        self.hit_cb = False

        def _cb(proxy, perms, token, frob):
            assert perms == 'write'
            assert token == 'token'
            assert frob == 'frob'

            if self.hit_cb:
                return True
            else:
                self.hit_cb = True

        assert_raises(FlickrError, get_proxy, wait_callback=_cb)
        assert self.hit_cb
开发者ID:faulkner,项目名称:pif,代码行数:25,代码来源:flickr_tests.py


示例3: setUp

 def setUp(self):
     self.maxDiff = None
     run.Redis = fakeredis.FakeRedis
     self.r = fakeredis.FakeStrictRedis()
     self.tt = TraceTracker()
     self.return_value = ''
     mock('run.analyse', tracker=self.tt, returns_func=self.get_return_value)
开发者ID:BIMSBbioinfo,项目名称:webdorina,代码行数:7,代码来源:test_dorina.py


示例4: setUp

 def setUp(self):
     self.api = MediaMosaAPI('http://video.example.com')
     self.tt = TraceTracker()
     mock('self.api.session', tracker=self.tt)
     self.response = Mock('requests.Response')
     self.response.status_code = 200
     self.api.session.get.mock_returns = self.response
开发者ID:UGentPortaal,项目名称:python-mediamosa,代码行数:7,代码来源:test_assetlist_resource.py


示例5: mock_send_email

def mock_send_email(request):
    """Mock up smtplib.SMTP and keyring.get_password for send_email."""
    import smtplib
    import keyring

    # capture all calls into mock objects
    # (instead of letting output go to stdout)
    tracker = minimock.TraceTracker()

    # mock up smtplib
    minimock.mock('smtplib.SMTP',
                  returns=minimock.Mock('smtp_connection', tracker=tracker),
                  tracker=tracker)

    # mock up keyring.get_password
    minimock.mock('keyring.get_password',
                  returns='send_email_secret',
                  tracker=tracker)

    def finalizer():
        # restore all objects in global module state that minimock replaced
        minimock.restore()

    request.addfinalizer(finalizer)

    return tracker
开发者ID:brbsix,项目名称:updatewatch,代码行数:26,代码来源:test_mailer.py


示例6: setUp

    def setUp(self):
        self.api = MediaMosaAPI('http://video.example.com')
        self.tt = TraceTracker()
        mock('self.api.session', tracker=self.tt)
        self.response = Mock('requests.Response')
        self.response.status_code = 200
        self.api.session.get.mock_returns = self.response

        self.item_dict = {u'is_original_file': u'FALSE',
            u'is_streamable': u'FALSE', u'is_downloadable': u'FALSE',
            u'app_id': u'2', u'transcode_inherits_acl': u'TRUE',
            u'tag': '', u'response_metafile_available': u'TRUE',
            u'mediafile_id_source': u'u2ilZNiHdl7iNUdexL7BcFMY',
            u'asset_id': u'g1QkoSmSeHdWfGkMKlOlldLn',
            u'mediafile_id': u'Md2RgaUEVFhfJMeUIbwPOMei',
            u'transcode_profile_id': u'17',
            u'filename': u'Sintel_Trailer1.1080p.DivX_Plus_HD.mp4',
            u'is_protected': u'FALSE', u'ega_stream_url': '',
            u'file_extension': u'mp4', 'metadata': {
            u'is_inserted_md': u'FALSE', u'fps': u'24', u'bpp': u'0.31',
            u'file_duration': u'00:00:52.20', u'colorspace': u'yuv420p',
            u'container_type': u'mov;mp4;m4a;3gp;3g2;mj2', u'height': u'478',
            u'channels': u'stereo', u'width': u'852', u'sample_rate': u'44100',
            u'filesize': u'20543936', u'audio_codec': u'aac',
            u'video_codec': u'h264', u'is_hinted': u'TRUE',
            u'bitrate': u'3012', u'mime_type': u'video/mp4'},
            u'ega_download_url': '', u'ega_play_url': '', u'tool': u'ffmpeg',
            u'response_plain_available': u'TRUE', u'owner_id': u'krkeppen',
            u'response_object_available': u'TRUE',
            u'created': u'2012-07-05 11:38:14',
            u'changed': u'2012-07-05 11:38:14', u'uri': '',
            u'is_still': u'FALSE', u'command':
            u'audiocodec:libfaac;audiobitrate:128000;audiosamplingrate:44100;audiochannels:2;videocodec:libx264;videopreset_quality:slow;videopreset_profile:baseline;2_pass_h264_encoding:2;videobitrate:800000;qmax:17;size:852x480;maintain_aspect_ratio:yes',
            u'group_id': ''}
开发者ID:UGentPortaal,项目名称:python-mediamosa,代码行数:34,代码来源:test_mediafile_resource.py


示例7: mock_set_password

def mock_set_password(request):
    """Mock up getpass.getpass and keyring.set_password for set_password."""
    import getpass
    import keyring

    # capture all calls into mock objects
    # (instead of letting output go to stdout)
    tracker = minimock.TraceTracker()

    # mock up getpass.getpass
    minimock.mock('getpass.getpass',
                  returns='set_password_secret',
                  tracker=tracker)

    # mock up keyring.set_password
    minimock.mock('keyring.set_password',
                  tracker=tracker)

    def finalizer():
        # restore all objects in global module state that minimock replaced
        minimock.restore()

    request.addfinalizer(finalizer)

    return tracker
开发者ID:brbsix,项目名称:updatewatch,代码行数:25,代码来源:test_mailer.py


示例8: setUp

    def setUp(self):
        """
        Nadgers haystack SearchView so that:
        - we don't need a search backend
        - response is a TemplateResponse, not and HttpResponse (so
          that in tests we can check context contents)
        """
        import django.template.response
        import haystack.views
        
        # SearchView passes a RequestContext to render_to_response,
        # but we want to be able to get hold of the request itself
        # (to pass on to TemplateResponse).
        class RequestContext(django.template.response.RequestContext):
            def __init__(self, request):
                super(RequestContext, self).__init__(request)
                self.request = request

        def render_to_response(template, context, context_instance):
            return django.template.response.TemplateResponse(
                    request = context_instance.request,
                    template = template,
                    context = context)

        self.context_class = RequestContext
        minimock.mock("haystack.views.render_to_response", returns_func=render_to_response, tracker=None)
        minimock.mock("haystack.views.SearchView.get_results", returns_func=self.get_results, tracker=None)

        self.org = OrganizationFactory()
开发者ID:TristramNorman,项目名称:econsensus,代码行数:29,代码来源:search_view_test.py


示例9: test_ok

    def test_ok(self):
        """OK proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one')
        minimock.mock('flickrapi.FlickrAPI.get_token_part_two', returns=True)

        assert isinstance(get_proxy(), flickrapi.FlickrAPI)
开发者ID:faulkner,项目名称:pif,代码行数:7,代码来源:flickr_tests.py


示例10: test_offline

    def test_offline(self):
        """Proxy when offline"""

        import urllib
        minimock.mock('urllib.urlopen', raises=IOError)

        get_proxy()
开发者ID:faulkner,项目名称:pif,代码行数:7,代码来源:flickr_tests.py


示例11: test_multipleLevelMountPointExtraPathInfo

 def test_multipleLevelMountPointExtraPathInfo(self):
     url = '/other/mount/point/fsm/MyMachine/state1/to/state2'
     request = buildRequest(path=url)
     from fantasm import config
     mock('config.currentConfiguration', returns=MockConfigRootUrl('/other/mount/point/'), tracker=None)
     name = getMachineNameFromRequest(request)
     self.assertEquals(name, 'MyMachine')
开发者ID:pombredanne,项目名称:fantasm,代码行数:7,代码来源:handlers_test.py


示例12: test_users_from_url

    def test_users_from_url(self):
        mock('obswatch.http_GET', tracker=self.tt,
             returns=StringIO('''<?xml version="1.0" encoding="UTF-8"?>
           <project name="superkde" created="2005-01-01T00:00:02+01:00" updated="2007-01-19T10:44:45+01:00">
             <title>SuperKDE</title>
             <description>SuperKDE is a heavily tuned version of KDE.</description>
             <link project="openSUSE:11.2:Update" />
             <link project="openSUSE:11.2" />
             <person role="maintainer" userid="Geeko"/>
             <person role="maintainer" userid="BrownGeeko"/>
             <group  role="reviewer"  groupid="release_team"/>
             <build>
               <disable />
             </build>
             <repository name="kde4:factory" rebuild="transitive">
               <path project="kde4" repository="factory"/>
               <arch>i386</arch>

               <arch>x86_64</arch>
             </repository>
           </project>'''))
        mock('obswatch.get_user_email', returns='[email protected]')

        result = obswatch.get_users_from_url('%ssource/superkde/_meta' %
                                            obswatch.APIURL)
        assert_same_trace(self.tt, """Called obswatch.http_GET(
            '%ssource/superkde/_meta')""" % obswatch.APIURL)
        self.assertEqual(len(result), 2)
        self.assertEqual(result['Geeko'], '[email protected]')
        self.assertEqual(result['BrownGeeko'], '[email protected]')        
开发者ID:mapleoin,项目名称:obswatch,代码行数:30,代码来源:tests.py


示例13: setUp

 def setUp(self):
     super(FanInMergeJoinDispatchTest, self).setUp()
     setUpByString(self, FAN_IN_MACHINE, machineName='FanInMachine', instanceName='foo')
     mock('config.currentConfiguration', returns=self.currentConfig, tracker=None)
     for i in range(20):
         SimpleModel(key_name='%d' % i).put()
     memcache.set('calls', 0)
     memcache.set('raise', False)
     
     context = self.factory.createFSMInstance(self.machineConfig.name, instanceName='foo')
     context[constants.STEPS_PARAM] = 1
     obj = TemporaryStateObject()
     obj[constants.TASK_NAME_PARAM] = 'taskName'
     obj[constants.RETRY_COUNT_PARAM] = 0
     
     self.context = None
     self.obj = None
     
     random.seed(0)
     context.dispatch('pseudo-init', obj) # write down a work package
     self.index = context[constants.INDEX_PARAM]
     
     self.assertEqual(1, _FantasmFanIn.all().count())
     self.assertEqual('foo--InitialState--ok--FanInState--step-2-2957927341', 
                      _FantasmFanIn.all().get().workIndex)
开发者ID:iki,项目名称:fantasm,代码行数:25,代码来源:idempotency_test.py


示例14: testTripwireTripped

    def testTripwireTripped(self):
        '''Tripwire test, tripped'''
        tt = minimock.TraceTracker()
        minimock.mock('tripwire.sendEmail', tracker=tt)
        
        datevalue = datetime.date(2011, 8, 16)
        
        dtmock = minimock.Mock('datetime.date')
        minimock.mock('datetime.date', mock_obj=dtmock)
        dtmock.mock_returns = dtmock
        dtmock.today.mock_returns = datevalue
        dtmock.today.mock_tracker = tt
        #can't just do minimock.mock('datetime.date.today', returns=datevalue, tracker=tt)
        #because datetime.date is in an extension (ie, not native python)
        
        #Add another value to make the tripwire trip
        self.session.add(model.MeasuredValue(6))
        self.session.commit()
        
        tripwire.main()
        expected = r'''Called datetime.date.today()
Called tripwire.sendEmail(3.0, datetime.date(2011, 8, 16))'''
        self.assertTrue(tt.check(expected), tt.diff(expected))
        
        minimock.restore()
        
开发者ID:llnz,项目名称:kiwipycon2011testing,代码行数:25,代码来源:tripwiretest.py


示例15: setUp

    def setUp(self):
        from netprintbox.data import OAuthRequestToken

        super(DropboxServiceSetupTest, self).setUp()

        token = 'oauth_token=token&oauth_token_secret=secret'
        token = OAuthRequestToken(key=self.key, token=token)
        token.put()

        class client(object):
            @staticmethod
            def account_info():
                return {'uid': self.uid,
                        'email': 'email',
                        'display_name': 'display_name',
                        'country': 'JP',
                        }

        class session(object):
            @staticmethod
            def obtain_access_token(request_token):
                pass

            class token(object):
                key = 'access_key'
                secret = 'access_secret'

        import dropbox.client
        import dropbox.session
        mock('dropbox.client.DropboxClient', returns=client)
        mock('dropbox.session.DropboxSession', returns=session)
开发者ID:jbking,项目名称:netprintbox,代码行数:31,代码来源:test_service.py


示例16: test_parseUrl

    def test_parseUrl(self):
        "CSSParser.parseUrl()"
        if mock:
            # parseUrl(self, href, encoding=None, media=None, title=None):
            parser = cssutils.CSSParser()
            mock("cssutils.util._defaultFetcher", 
                 mock_obj=self._make_fetcher(None, u''))
            sheet = parser.parseUrl('http://example.com',
                                    media='tv,print', 
                                    title='test')
            restore()
            #self.assertEqual(sheet, 1)
            self.assertEqual(sheet.href, 'http://example.com')
            self.assertEqual(sheet.encoding, 'utf-8')
            self.assertEqual(sheet.media.mediaText, 'tv, print')
            self.assertEqual(sheet.title, 'test')
            
            # URL and content tests
            tests = {
                # (url, content): isSheet, encoding, cssText
                ('', None): (False, None, None), 
                ('1', None): (False, None, None), 
                ('mailto:[email protected]', None): (False, None, None), 
                ('http://example.com/x.css', None): (False, None, None), 
                ('http://example.com/x.css', ''): (True, u'utf-8', u''), 
               # ('http://example.com/x.css', 'a'): (True, u'utf-8', u''), 
#                ('http://example.com/x.css', 'a {color: red}'): (True, u'utf-8', 
#                                                                 u'a {\n    color: red\n    }'), 
#                ('http://example.com/x.css', 'a {color: red}'): (True, u'utf-8', 
#                                                                 u'a {\n    color: red\n    }'), 
#                ('http://example.com/x.css', '@charset "ascii";a {color: red}'): (True, u'ascii', 
#                                                                 u'@charset "ascii";\na {\n    color: red\n    }'), 
            }
            override = 'iso-8859-1'
            overrideprefix = u'@charset "iso-8859-1";'
            httpencoding = None
            
            for (url, content), (isSheet, expencoding, cssText) in tests.items():
                mock("cssutils.util._defaultFetcher", 
                     mock_obj=self._make_fetcher(httpencoding, content))
                #parser.setFetcher(self._make_fetcher(httpencoding, content))
                sheet1 = parser.parseUrl(url)
                sheet2 = parser.parseUrl(url, encoding=override)
                restore()
                if isSheet:
                    self.assertEqual(sheet1.encoding, expencoding)
                    self.assertEqual(sheet1.cssText, cssText)
                    self.assertEqual(sheet2.encoding, override)
                    if sheet1.cssText and sheet1.cssText.startswith('@charset'):
                        self.assertEqual(sheet2.cssText, cssText.replace('ascii', override))
                    elif sheet1.cssText:
                        self.assertEqual(sheet2.cssText, overrideprefix + '\n' + cssText)
                    else:
                        self.assertEqual(sheet2.cssText, overrideprefix + cssText)
                else:
                    self.assertEqual(sheet1, None)
                    self.assertEqual(sheet2, None)

            self.assertRaises(ValueError, parser.parseUrl, '../not-valid-in-urllib')
            self.assertRaises(urllib2.HTTPError, parser.parseUrl, 'http://example.com/not-present.css')
开发者ID:creativify,项目名称:information-overload,代码行数:60,代码来源:test_parse.py


示例17: test_bad_xml

    def test_bad_xml(self):
        """Bad XML from proxy"""

        minimock.mock('flickrapi.FlickrAPI.get_token_part_one',
                      raises=ExpatError)

        get_proxy()
开发者ID:faulkner,项目名称:pif,代码行数:7,代码来源:flickr_tests.py


示例18: test_get_fail_bad

    def test_get_fail_bad(self):
        """Failed shorthash retrieval passes fatal exceptions"""

        self.make_mock_photo('123')

        minimock.mock('urllib2.urlopen', raises=SystemError)

        self.index.refresh()
开发者ID:faulkner,项目名称:pif,代码行数:8,代码来源:tests.py


示例19: test_get_fail

    def test_get_fail(self):
        """Fail shorthash retrieval"""

        self.make_mock_photo('123')

        minimock.mock('urllib2.urlopen', raises=IOError)

        self.index.refresh()
开发者ID:faulkner,项目名称:pif,代码行数:8,代码来源:tests.py


示例20: test_maxDoublingsAddedToQueuedTask

 def test_maxDoublingsAddedToQueuedTask(self):
     def execute(context, obj):
         return 'ok5'            
     mock(name='CountExecuteCalls.execute', returns_func=execute, tracker=None)
     self.context.dispatch(self.initEvent, TemporaryStateObject())
     self.assertEquals(len(self.mockQueue.tasks), 1)
     task = self.mockQueue.tasks[0][0]
     self.assertEquals(task.retry_options.max_doublings, 5)
开发者ID:iki,项目名称:fantasm,代码行数:8,代码来源:fsm_test.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python minimock.restore函数代码示例发布时间:2022-05-27
下一篇:
Python minimock.assert_same_trace函数代码示例发布时间: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