本文整理汇总了Python中mockito.when函数的典型用法代码示例。如果您正苦于以下问题:Python when函数的具体用法?Python when怎么用?Python when使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了when函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_getPlayerList
def test_getPlayerList(self):
"""
Query the game server for connected players.
return a dict having players' id for keys and players' data as another dict for values
"""
when(self.output_mock).write('status', maxRetries=anything()).thenReturn("""
map: ut4_casa
num score ping name lastmsg address qport rate
--- ----- ---- --------------- ------- --------------------- ----- -----
10 0 13 snowwhite 0 192.168.1.11:51034 9992 15000
12 0 10 superman 0 192.168.1.12:53039 9993 15000
""")
result = self.console.getPlayerList()
verify(self.output_mock).write('status', maxRetries=anything())
self.assertDictEqual({'10': {'ip': '192.168.1.11',
'last': '0',
'name': 'snowwhite',
'pbid': None,
'ping': '13',
'port': '51034',
'qport': '9992',
'rate': '15000',
'score': '0',
'slot': '10'},
'12': {'ip': '192.168.1.12',
'last': '0',
'name': 'superman',
'pbid': None,
'ping': '10',
'port': '53039',
'qport': '9993',
'rate': '15000',
'score': '0',
'slot': '12'}}
, result)
开发者ID:HaoDrang,项目名称:big-brother-bot,代码行数:35,代码来源:test_iourt41.py
示例2: test_swift_segment_checksum_etag_mismatch
def test_swift_segment_checksum_etag_mismatch(self):
"""This tests that when etag doesn't match segment uploaded checksum
False is returned and None for checksum and location"""
context = TroveContext()
# this backup_id will trigger fake swift client with calculate_etag
# enabled to spit out a bad etag when a segment object is uploaded
backup_id = 'bad_segment_etag_123'
user = 'user'
password = 'password'
backup_container = 'database_backups'
swift_client = FakeSwiftConnectionWithRealEtag()
when(swift).create_swift_client(context).thenReturn(swift_client)
storage_strategy = SwiftStorage(context)
with MockBackupRunner(filename=backup_id,
user=user,
password=password) as runner:
(success,
note,
checksum,
location) = storage_strategy.save(backup_container, runner)
self.assertEqual(success, False,
"The backup should have failed!")
self.assertTrue(note.startswith("Error saving data to Swift!"))
self.assertIsNone(checksum,
"Swift checksum should be None for failed backup.")
self.assertIsNone(location,
"Swift location should be None for failed backup.")
开发者ID:adamfokken,项目名称:trove,代码行数:30,代码来源:test_storage.py
示例3: test_should_raise_exception_when_loading_project_module_and_import_raises_exception
def test_should_raise_exception_when_loading_project_module_and_import_raises_exception(self):
when(imp).load_source("build", "spam").thenRaise(ImportError("spam"))
self.assertRaises(
PyBuilderException, self.reactor.load_project_module, "spam")
verify(imp).load_source("build", "spam")
开发者ID:Ferreiros-lab,项目名称:pybuilder,代码行数:7,代码来源:reactor_tests.py
示例4: setUp
def setUp(self):
B3TestCase.setUp(self)
self.console.gameName = 'f00'
self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
self.adminPlugin.onLoadConfig()
self.adminPlugin.onStartup()
self.conf = CfgConfigParser()
self.conf.loadFromString(dedent(r"""
[settings]
update_config_file: no
[commands]
cmdlevel: fulladmin
cmdalias: fulladmin
cmdgrant: superadmin
cmdrevoke: superadmin
cmduse: superadmin
"""))
self.p = CmdmanagerPlugin(self.console, self.conf)
self.p.onLoadConfig()
self.p.onStartup()
开发者ID:HaoDrang,项目名称:big-brother-bot,代码行数:26,代码来源:__init__.py
示例5: test_run_verify_checksum_mismatch
def test_run_verify_checksum_mismatch(self):
"""This tests that SwiftDownloadIntegrityError is raised and swift
download cmd does not run when original backup checksum does not match
swift object etag"""
context = TroveContext()
location = "/backup/location/123"
is_zipped = False
backup_checksum = "checksum_different_then_fake_swift_etag"
swift_client = FakeSwiftConnection()
when(swift).create_swift_client(context).thenReturn(swift_client)
storage_strategy = SwiftStorage(context)
download_stream = storage_strategy.load(context,
location,
is_zipped,
backup_checksum)
self.assertEqual(download_stream.container, "location")
self.assertEqual(download_stream.filename, "123")
self.assertRaises(SwiftDownloadIntegrityError,
download_stream.__enter__)
self.assertEqual(download_stream.process, None,
"SwiftDownloadStream process/cmd was not supposed"
"to run.")
开发者ID:adamfokken,项目名称:trove,代码行数:28,代码来源:test_storage.py
示例6: testVerifiesMultipleCallsOnClassmethod
def testVerifiesMultipleCallsOnClassmethod(self):
when(Dog).bark().thenReturn("miau!")
Dog.bark()
Dog.bark()
verify(Dog, times=2).bark()
开发者ID:kaste,项目名称:mockito-python,代码行数:7,代码来源:classmethods_test.py
示例7: without_container
def without_container(self, container):
"""
sets expectations for removing a container and subsequently throwing an
exception for further interactions
example:
if FAKE:
swift_stub.without_container('test-container-name')
# returns swift container information - mostly faked
component_using.swift.remove_container('test-container-name')
# throws exception "Resource Not Found - 404"
component_using_swift.get_container_info('test-container-name')
:param container: container name that is expected to be removed
"""
# first ensure container
self._ensure_container_exists(container)
# allow one call to get container and then throw exceptions (may need
# to be revised
when(swift_client.Connection).delete_container(container).thenRaise(
swiftclient.ClientException("Resource Not Found", http_status=404))
when(swift_client.Connection).get_container(container).thenRaise(
swiftclient.ClientException("Resource Not Found", http_status=404))
self._delete_container(container)
return self
开发者ID:NeCTAR-RC,项目名称:trove,代码行数:27,代码来源:swift.py
示例8: test_lookup_flavor
def test_lookup_flavor(self):
flavor = mock(Flavor)
flavor.name = 'flav_1'
when(self.flavor_mgr).get('1').thenReturn(flavor)
transformer = NovaNotificationTransformer(context=self.context)
self.assertThat(transformer._lookup_flavor('1'), Equals(flavor.name))
self.assertThat(transformer._lookup_flavor('2'), Equals('unknown'))
开发者ID:DJohnstone,项目名称:trove,代码行数:7,代码来源:test_models.py
示例9: _mock_get_soledad_doc
def _mock_get_soledad_doc(self, doc_id, doc):
soledad_doc = SoledadDocument(doc_id, json=json.dumps(doc.serialize()))
# when(self.soledad).get_doc(doc_id).thenReturn(defer.succeed(soledad_doc))
when(self.soledad).get_doc(doc_id).thenAnswer(lambda: defer.succeed(soledad_doc))
self.doc_by_id[doc_id] = soledad_doc
开发者ID:Josue23,项目名称:pixelated-user-agent,代码行数:7,代码来源:test_leap_attachment_store.py
示例10: testFailsOnNumberOfCalls
def testFailsOnNumberOfCalls(self):
when(os.path).exists("test").thenReturn(True)
os.path.exists("test")
self.assertRaises(VerificationError, verify(os.path, times=2).exists,
"test")
开发者ID:kaste,项目名称:mockito-python,代码行数:7,代码来源:modulefunctions_test.py
示例11: setUp
def setUp(self):
B3TestCase.setUp(self)
when(self.console.config).get_external_plugins_dir().thenReturn(external_plugins_dir)
self.conf = CfgConfigParser(testplugin_config_file)
self.plugin_list = [
{'name': 'admin', 'conf': '@b3/conf/plugin_admin.ini', 'path': None, 'disabled': False},
]
fp, pathname, description = imp.find_module('testplugin1', [os.path.join(b3.getB3Path(True), '..', 'tests', 'plugins', 'fakeplugins')])
pluginModule1 = imp.load_module('testplugin1', fp, pathname, description)
if fp:
fp.close()
fp, pathname, description = imp.find_module('testplugin3', [os.path.join(b3.getB3Path(True), '..', 'tests', 'plugins', 'fakeplugins')])
pluginModule3 = imp.load_module('testplugin3', fp, pathname, description)
if fp:
fp.close()
fp, pathname, description = imp.find_module('admin', [os.path.join(b3.getB3Path(True), 'plugins')])
adminModule = imp.load_module('admin', fp, pathname, description)
if fp:
fp.close()
when(self.console.config).get_plugins().thenReturn(self.plugin_list)
when(self.console).pluginImport('admin', ANY).thenReturn(adminModule)
when(self.console).pluginImport('testplugin1', ANY).thenReturn(pluginModule1)
when(self.console).pluginImport('testplugin3', ANY).thenReturn(pluginModule3)
开发者ID:82ndab-Bravo17,项目名称:big-brother-bot,代码行数:28,代码来源:test_plugin.py
示例12: test_repair_is_deferred
def test_repair_is_deferred(self):
soledad = mock()
when(soledad).get_all_docs().thenReturn(defer.succeed((1, [])))
d = SoledadMaintenance(soledad).repair()
self.assertIsInstance(d, defer.Deferred)
开发者ID:bwagnerr,项目名称:pixelated-user-agent,代码行数:7,代码来源:test_soledad_maintenance.py
示例13: test_glob_should_return_list_with_single_module_when_directory_contains_package
def test_glob_should_return_list_with_single_module_when_directory_contains_package(self):
when(os).walk("spam").thenReturn([("spam", ["eggs"], []),
("spam/eggs", [], ["__init__.py"])])
self.assertEquals(["eggs"], discover_modules_matching("spam", "*"))
verify(os).walk("spam")
开发者ID:AnudeepHemachandra,项目名称:pybuilder,代码行数:7,代码来源:utils_tests.py
示例14: test_should_only_match_py_files_regardless_of_glob
def test_should_only_match_py_files_regardless_of_glob(self):
when(os).walk("pet_shop").thenReturn([("pet_shop", [],
["parrot.txt", "parrot.py", "parrot.pyc", "parrot.py~", "slug.py"])])
expected_result = ["parrot"]
actual_result = discover_modules_matching("pet_shop", "*parrot*")
self.assertEquals(set(expected_result), set(actual_result))
verify(os).walk("pet_shop")
开发者ID:AnudeepHemachandra,项目名称:pybuilder,代码行数:7,代码来源:utils_tests.py
示例15: test_window_id_is_bool
def test_window_id_is_bool(self):
driver = MockWebDriver()
when(driver).execute_script(SCRIPT).thenReturn([True, "", "", ""]).thenReturn([False, "", "", ""])
info = driver.get_current_window_info()
self.assertEqual(info[1], True)
info = driver.get_current_window_info()
self.assertEqual(info[1], False)
开发者ID:ekasteel,项目名称:robotframework-selenium2library,代码行数:7,代码来源:test_webdrivermonkeypatches.py
示例16: testBuildWithNestedBundles
def testBuildWithNestedBundles(self):
import __builtin__, pickle
from mockito import when, unstub
b = os.path.join('/', 'b.js')
when(__builtin__).open(b).thenReturn(StrIO('b'))
@worker
def content(files, bundle):
for a in files:
assert a == 'a.js'
yield 'a'
@worker
def store(contents, bundle):
for content in contents:
assert content == 'ab'
yield 'ab.js'
env = ets.Environment(mode='development', map_from='/')
nested_bundle = ets.Bundle(assets=['a.js'], env=env,
development=[content])
#keep in mind that build() expects a relative path at the end of the pipe
bundle = ets.Bundle(assets=[nested_bundle, 'b.js'], env=env,
development=[ets.f.read, ets.f.merge, store])
assert bundle.build() == [os.path.join('/', 'ab.js')]
unstub()
开发者ID:kaste,项目名称:ass.ets,代码行数:31,代码来源:assets_test.py
示例17: test_window_id_is_empty_container
def test_window_id_is_empty_container(self):
driver = MockWebDriver()
when(driver).execute_script(SCRIPT).thenReturn([[], "", "", ""]).thenReturn([{}, "", "", ""])
info = driver.get_current_window_info()
self.assertEqual(info[1], [])
info = driver.get_current_window_info()
self.assertEqual(info[1], {})
开发者ID:ekasteel,项目名称:robotframework-selenium2library,代码行数:7,代码来源:test_webdrivermonkeypatches.py
示例18: test_level_generator_is_created
def test_level_generator_is_created(self):
"""
Test that portal adder has level generator set to it
"""
portal_config = [PortalAdderConfiguration(icons = (1, 2),
level_type = 'catacombs',
location_type = 'room',
chance = 100,
new_level = 'upper crypt',
unique = False)]
level_generator_factory = mock(LevelGeneratorFactory)
level_generator = mock(LevelGenerator)
when(level_generator_factory).get_generator(any()).thenReturn(level_generator)
factory = PortalAdderFactory(portal_config,
self.rng)
factory.level_generator_factory = level_generator_factory
portal_adders = factory.create_portal_adders('catacombs')
portal_adder = portal_adders[0]
assert_that(portal_adder.level_generator,
is_(same_instance(level_generator)))
开发者ID:briguy47,项目名称:pyherc,代码行数:26,代码来源:test_portaladder.py
示例19: with_container
def with_container(self, container_name):
"""
sets expectations for creating a container and subsequently getting its
information
example:
if FAKE:
swift_stub.with_container('test-container-name')
# returns swift container information - mostly faked
component_using.swift.create_container('test-container-name')
component_using_swift.get_container_info('test-container-name')
:param container_name: container name that is expected to be created
"""
def container_resp(container):
return ({'content-length': '2', 'x-container-object-count': '0',
'accept-ranges': 'bytes', 'x-container-bytes-used': '0',
'x-timestamp': '1363370869.72356',
'x-trans-id': 'tx7731801ac6ec4e5f8f7da61cde46bed7',
'date': 'Fri, 10 Mar 2013 18:07:58 GMT',
'content-type': 'application/json; charset=utf-8'},
self._objects[container])
# if this is called multiple times then nothing happens
when(swift_client.Connection).put_container(container_name).thenReturn(
None)
self._create_container(container_name)
# return container headers
when(swift_client.Connection).get_container(container_name).thenReturn(
container_resp(container_name))
return self
开发者ID:NeCTAR-RC,项目名称:trove,代码行数:35,代码来源:swift.py
示例20: test_transfert_debite_le_bon_compte
def test_transfert_debite_le_bon_compte(self):
"""Test si lors du transfert la valeur est bien debitee de la source"""
amount = 100
when(self.accountDest).can_accept_credit(amount).thenReturn(True)
self.transfer.transfer(amount)
verify(self.accountSrc, times=1).debit(amount)
开发者ID:BenjaminVanRyseghem,项目名称:SVL,代码行数:7,代码来源:test_bank.py
注:本文中的mockito.when函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论