本文整理汇总了Python中mocker.expect函数的典型用法代码示例。如果您正苦于以下问题:Python expect函数的具体用法?Python expect怎么用?Python expect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了expect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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")
示例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, {})
示例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)
示例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])
示例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)
示例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)
示例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)
示例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)
示例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()
示例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?')
示例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,))
示例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
示例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)
示例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)
示例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))