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

Python mocker.expect函数代码示例

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

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



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

示例1: test_deserialize_failure_leaves_trace

 def test_deserialize_failure_leaves_trace(self):
     mock = self.mocker.patch(self.bundle)
     expect(mock._do_deserialize(False)).throw(Exception("boom"))
     self.mocker.replay()
     self.bundle.deserialize(False)
     self.assertFalse(self.bundle.is_deserialized)
     self.assertEqual(self.bundle.deserialization_error.error_message, "boom")
开发者ID:OSSystems,项目名称:lava-server,代码行数:7,代码来源:bundle.py


示例2: test_add_part_to_uploadjob

    def test_add_part_to_uploadjob(self):
        """Delete an uploadjob."""
        mocker = Mocker()

        # upload job
        uj = mocker.mock()
        expect(
            uj.add_part(
                "chunk_size", "inflated_size", "crc32", "hash_context", "magic_hash_context", "decompress_context"
            )
        )

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.get_uploadjob("uploadjob_id")).result(uj)

        with mocker:
            d = dict(
                user_id="user_id",
                uploadjob_id="uploadjob_id",
                chunk_size="chunk_size",
                inflated_size="inflated_size",
                crc32="crc32",
                hash_context="hash_context",
                magic_hash_context="magic_hash_context",
                decompress_context="decompress_context",
            )
            result = self.dal.add_part_to_uploadjob(**d)

        self.assertEqual(result, {})
开发者ID:cloudfleet,项目名称:filesync-server,代码行数:31,代码来源:test_dal_backend.py


示例3: test_informed_metrics

    def test_informed_metrics(self):
        """Check how stats are reported."""
        # prepare a lot of fake info that will be "collected"
        machine_info = dict(foo=3, bar=5)
        process_info = {
            1: dict(some=1234, other=4567),
            2: dict(some=9876, other=6543),
        }
        self.worker._collect_process = lambda pid, name: process_info[pid]
        self.worker._collect_machine = lambda: machine_info
        processes = [
            dict(name="proc1", group="", pid="1", state=RUNNING),
            dict(name="proc2", group="", pid="2", state=RUNNING),
        ]
        expect(self.rpc.supervisor.getAllProcessInfo()).result(processes)

        # patch the metric reporter to see what is sent
        reported = set()
        self.worker.metrics.gauge = lambda *a: reported.add(a)

        # what we should get is...
        should = set([
            ('foo', 3),
            ('bar', 5),
            ('some', 1234),
            ('other', 4567),
            ('some', 9876),
            ('other', 6543),
        ])
        with self.mocker:
            self.worker.collect_stats()
        self.assertEqual(reported, should)
开发者ID:CSRedRat,项目名称:magicicada-server,代码行数:32,代码来源:test_stats_worker.py


示例4: test

 def test(c):
     opts = TestConfig(
         sort_selection=c.opts._get("sel", False),
         reverse_sort=c.opts._get("rev", False),
         ignore_leading_ws=c.opts._get("ign", False),
         numeric_match=c.opts._get("num", False),
         regex_sort=c.opts._get("reg", False),
         search_pattern=c.opts._get("sch", ""),
         match_pattern=c.opts._get("mch", ""),
     )
     m = Mocker()
     tv = m.mock(TextView)
     ts = tv.textStorage() >> m.mock(NSTextStorage)
     text = tv.string() >> NSString.stringWithString_(c.text)
     if opts.sort_selection:
         sel = tv.selectedRange() >> c.sel
         sel = text.lineRangeForRange_(sel)
     else:
         sel = c.sel
     tv.shouldChangeTextInRange_replacementString_(sel, ANY) >> True
     output = []
     def callback(range, text):
         output.append(text)
     expect(ts.replaceCharactersInRange_withString_(sel, ANY)).call(callback)
     tv.didChangeText()
     if opts.sort_selection:
         tv.setSelectedRange_(sel)
     with m:
         sortlines(tv, opts)
         def ch(line):
             value = line.lstrip(" ")
             return value[0] if value else "|%i" % len(line)
         eq_(c.result, "".join(ch(line) for line in output[0].split("\n")), output[0])
开发者ID:youngrok,项目名称:editxt,代码行数:33,代码来源:test_sortlines.py


示例5: test_closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_

def test_closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_():
    context = 42
    dc = NSDocumentController.sharedDocumentController()
    m = Mocker()
    app = m.replace("editxt.app", type=Application)
    perf_sel = m.replace("editxt.util.perform_selector", passthrough=False)
    dsd_class = m.replace("editxt.application.DocumentSavingDelegate",
        spec=False, passthrough=False)
    docs = m.mock()
    app.iter_dirty_documents() >> docs
    selector = "_docController:shouldTerminate:context:"
    delegate = m.mock()
    def test_callback(callback):
        callback("<result>")
        return True
    should_term = delegate._docController_shouldTerminate_context_
    expect(perf_sel(delegate, selector, dc, "<result>", context)).call(
        lambda *a:should_term(dc, "<result>", context))
    should_term(dc, "<result>", context)
    saver = m.mock(DocumentSavingDelegate)
    dsd_class.alloc() >> saver
    saver.init_callback_(docs, MATCH(test_callback)) >> saver
    saver.save_next_document()
    with m:
        dc.closeAllDocumentsWithDelegate_didCloseAllSelector_contextInfo_(
            delegate, selector, context)
开发者ID:youngrok,项目名称:editxt,代码行数:26,代码来源:test_application.py


示例6: test_user_registration_executes_query_on_db

    def test_user_registration_executes_query_on_db(self):
        conn = db.Connection()
        mock_connection = self.mocker.patch(conn)
        expect(mock_connection.execute(mocker.ARGS)).count(1, None)
        self.mocker.replay()

        register_user('[email protected]', 'password', mock_connection)
开发者ID:rbp,项目名称:auth,代码行数:7,代码来源:unit_tests.py


示例7: test_authenticate_non_existent_email_raises

    def test_authenticate_non_existent_email_raises(self):
        mock_conn = self.mocker.mock()
        expect(mock_conn.get_user('[email protected]')).result(None)
        self.mocker.replay()

        self.assertRaises(AuthenticationError, authenticate,
                          '[email protected]', 'password', mock_conn)
开发者ID:rbp,项目名称:auth,代码行数:7,代码来源:unit_tests.py


示例8: test

 def test(c):
     proj = Project.create()
     m = Mocker()
     dsd_class = m.replace("editxt.application.DocumentSavingDelegate")
     app = m.replace("editxt.app", type=Application)
     ed = m.mock(Editor)
     app.find_editors_with_project(proj) >> [ed for x in xrange(c.num_eds)]
     if c.num_eds == 1:
         docs = [m.mock(TextDocumentView)]
         doc = docs[0].document >> m.mock(TextDocument)
         app.iter_editors_with_view_of_document(doc) >> \
             (ed for x in xrange(c.num_doc_views))
         dirty_documents = m.method(proj.dirty_documents)
         dirty_documents() >> docs
         def check_docs(_docs):
             d = docs if c.num_doc_views == 1 else []
             eq_(list(_docs), d + [proj])
             return True
         callback = []
         def get_callback(func):
             callback.append(func)
             return True
         def do_callback():
             callback[0](c.should_close)
         saver = m.mock(DocumentSavingDelegate)
         dsd_class.alloc() >> saver
         saver.init_callback_(MATCH(check_docs), MATCH(get_callback)) >> saver
         expect(saver.save_next_document()).call(do_callback)
         if c.should_close:
             ed.discard_and_focus_recent(proj)
     else:
         ed.discard_and_focus_recent(proj)
     with m:
         proj.perform_close(ed)
开发者ID:youngrok,项目名称:editxt,代码行数:34,代码来源:test_project.py


示例9: do

 def do(m, c, fc, sender):
     beep = m.replace(ak, 'NSBeep')
     dobeep = True
     tv = m.replace(fc.finder, 'find_target')() >> (m.mock(TextView) if c.has_tv else None)
     if c.has_tv:
         options = m.replace(fc.finder, "options")
         rtext = options.replace_text >> "abc"
         options.regular_expression >> c.regex
         FoundRange = make_found_range_factory(FindOptions(regular_expression=False))
         if c.regex:
             if c.rfr:
                 tv._Finder__recently_found_range >> FoundRange(None)
             elif c.rfr is None:
                 expect(tv._Finder__recently_found_range).throw(AttributeError)
             else:
                 tv._Finder__recently_found_range >> None
         range = tv.selectedRange() >> m.mock()
         tv.shouldChangeTextInRange_replacementString_(range, rtext) >> c.act
         if c.act:
             tv.textStorage().replaceCharactersInRange_withString_(range, rtext)
             tv.didChangeText()
             tv.setNeedsDisplay_(True)
             dobeep = False
     if dobeep:
         beep()
开发者ID:khairy,项目名称:editxt,代码行数:25,代码来源:test_find.py


示例10: test_result_is_cached

    def test_result_is_cached(self):
        viewlet = self.get_viewlet()
        viewlet.update()
        self.assertNotIn('purple', viewlet.generate_css(),
                         'Unexpectedly found "purple" in the CSS')

        # Setting a custom style automatically invalidates the cache.
        # For testing that things are cached, we stub the cache invalidation,
        # so that the cache persists.
        mocker = Mocker()
        invalidate_cache_mock = mocker.replace(invalidate_cache)
        expect(invalidate_cache_mock()).count(1, None)
        mocker.replay()

        ICustomStyles(self.layer['portal']).set('css.body-background', 'purple')
        self.assertNotIn('purple', viewlet.generate_css(),
                         'The result was not cached.')

        # Removing the stub and invalidating the cache should update the result.
        mocker.restore()
        mocker.verify()
        invalidate_cache()
        self.assertIn('purple', viewlet.generate_css(),
                      'Expected "purple" in CSS - does the style'
                      ' css.body-background no longer work?')
开发者ID:datakurre,项目名称:plonetheme.onegov,代码行数:25,代码来源:test_viewlets_customstyles.py


示例11: __rshift__

    def __rshift__(self, value, act=False):
        """syntax sugar for more concise expect/result expression syntax

        old:  expect(mock.func(arg)).result(value)
        new: mock.func(arg) >> value

        This variation has a subtle difference from the 'sour' code above as
        well as the << operator. It returns 'value' rather than the expect
        object, which allows us to construct expressions while "injecing"
        return values into sub-expressions. For example:

            (mock.func(arg) >> value).value_func()

            Equivalent to:

            expect(mock.func(arg)).result(value)
            value.value_func()

        Note: to mock a real right-shift operation use the following code in
        your test case:

            mock.func(arg).__rshift__(value, act=True)
        """
        if self.__mocker__.is_recording() and not act:
            mocker.expect(self).result(value)
            return value
        return self.__mocker_act__("__rshift__", (value,))
开发者ID:youngrok,项目名称:editxt,代码行数:27,代码来源:mockerext.py


示例12: set_parent

 def set_parent(self, context, parent_context):
     """Set the acquisition parent of `context` to `parent_context`.
     """
     self._check_super_setup()
     expect(aq_parent(aq_inner(context))).result(
         parent_context).count(0, None)
     return context
开发者ID:4teamwork,项目名称:ftw.testing,代码行数:7,代码来源:testcase.py


示例13: test

 def test(c):
     with test_app() as app:
         m = Mocker()
         fc = FindController(app)
         flog = m.replace("editxt.command.find.log")
         beep = m.replace(mod, "beep")
         get_editor = m.method(fc.get_editor)
         sender = m.mock()
         (sender.tag() << c.tag).count(1, 2)
         func = None
         for tag, meth in list(fc.action_registry.items()):
             fc.action_registry[tag] = temp = m.mock(meth)
             if tag == c.tag:
                 func = temp
         if c.fail:
             flog.info(ANY, c.tag)
         else:
             if c.error:
                 err = mod.CommandError("error!")
                 expect(func(sender)).throw(err)
                 beep()
                 editor = get_editor() >> (m.mock() if c.target else None)
                 if c.target:
                     editor.message("error!", msg_type=const.ERROR)
                 else:
                     flog.warn(err)
             else:
                 func(sender)
         with m:
             fc.perform_action(sender)
开发者ID:editxt,项目名称:editxt,代码行数:30,代码来源:test_find.py


示例14: test_fetching_data_retry_on_ConnectionError

    def test_fetching_data_retry_on_ConnectionError(self):
        from scieloapi.exceptions import ConnectionError
        mock_httpbroker = self.mocker.proxy(httpbroker)
        mocker.expect(mock_httpbroker.post).passthrough()

        mock_httpbroker.get('http://manager.scielo.org/api/v1/',
                            endpoint='journals',
                            params={},
                            resource_id=1,
                            check_ca=mocker.ANY,
                            auth=('any.username', 'any.apikey'))
        self.mocker.throw(ConnectionError)

        mock_httpbroker.get('http://manager.scielo.org/api/v1/',
                            endpoint='journals',
                            params={},
                            resource_id=1,
                            check_ca=mocker.ANY,
                            auth=('any.username', 'any.apikey'))
        self.mocker.result(self.valid_microset)

        self.mocker.replay()

        conn = self._makeOne('any.username', 'any.apikey', http_broker=mock_httpbroker)

        res = conn.fetch_data('journals', resource_id=1)
        self.assertIn('title', res)
开发者ID:gustavofonseca,项目名称:scieloapi.py,代码行数:27,代码来源:test_core.py


示例15: test_valid_login

 def test_valid_login(self):
     authenticator = self.mocker.mock()
     request = self.mocker.mock()
     expect(authenticator.authenticate(request)).result(True)
     with self.mocker:
         self.assertEqual(
             None, HttpDigestMiddleware(authenticator=authenticator).process_request(request))
开发者ID:GGSN,项目名称:geocamAppEngineLibs,代码行数:7,代码来源:tests.py


示例16: test_activate_with_non_existent_key_raises

    def test_activate_with_non_existent_key_raises(self):
        mock_conn = self.mocker.mock()
        expect(mock_conn.get_pending_user_by_key(mocker.ANY)).result([])
        self.mocker.replay()

        self.assertRaises(InvalidRegistrationKeyError,
                          activate, 'some key', mock_conn)
开发者ID:rbp,项目名称:auth,代码行数:7,代码来源:unit_tests.py


示例17: test_add_part_to_uploadjob

    def test_add_part_to_uploadjob(self):
        """Delete an uploadjob."""
        mocker = Mocker()

        # upload job
        uj = mocker.mock()
        expect(uj.add_part('chunk_size', 'inflated_size', 'crc32',
                           'hash_context', 'magic_hash_context',
                           'decompress_context'))

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.volume('volume_id')
               .get_uploadjob('uploadjob_id')).result(uj)

        with mocker:
            d = dict(user_id='user_id', uploadjob_id='uploadjob_id',
                     chunk_size='chunk_size', inflated_size='inflated_size',
                     crc32='crc32', hash_context='hash_context',
                     magic_hash_context='magic_hash_context',
                     decompress_context='decompress_context',
                     volume_id='volume_id')
            result = self.dal.add_part_to_uploadjob(**d)

        self.assertEqual(result, {})
开发者ID:CSRedRat,项目名称:magicicada-server,代码行数:26,代码来源:test_dal_backend.py


示例18: test_connecting_gets_new_cursor

    def test_connecting_gets_new_cursor(self):
        expect(self.mock_driver.connect()).result(self.mock_conn)
        self.mock_conn.cursor()
        self.mocker.replay()

        conn = db.Connection(driver=self.mock_driver)
        conn.connect()
开发者ID:rbp,项目名称:auth,代码行数:7,代码来源:unit_tests.py


示例19: should_build_objects_with_dependencies_from_factories

 def should_build_objects_with_dependencies_from_factories(self):
     factory = self.mockery.mock()
     expect(factory(arg_of_type(no_deps))).result(12345)
     with self.mockery:
         self.assembler.register(int, requires=[no_deps], factory=factory)
         instance = self.assembler.provide(int)
     assert instance == 12345
开发者ID:pmatiello,项目名称:assemblage,代码行数:7,代码来源:assemblage_spec.py


示例20: test

 def test(c):
     m = Mocker()
     options = make_options(c)
     tv = m.mock(TextView)
     tv.selectedRange() >> fn.NSMakeRange(0, 16)
     tv.string() >> fn.NSString.alloc().initWithString_(c.text)
     if not isinstance(c.expect, Exception):
         result = [c.text]
         def replace(range, value):
             start, end = range
             text = result[0]
             result[0] = text[:start] + value + text[start + end:]
         tv.shouldChangeTextInRange_replacementString_(ANY, ANY) >> True
         expect(tv.textStorage().replaceCharactersInRange_withString_(
             ANY, ANY)).call(replace)
         tv.didChangeText()
         tv.setNeedsDisplay_(True)
     finder = Finder((lambda: tv), options)
     with m:
         if isinstance(c.expect, Exception):
             def check(err):
                 print(err)
                 eq_(str(err), str(c.expect))
             with assert_raises(type(c.expect), msg=check):
                 getattr(finder, c.action)(None)
         else:
             getattr(finder, c.action)(None)
             eq_(result[0], c.expect)
开发者ID:khairy,项目名称:editxt,代码行数:28,代码来源:test_find.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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