本文整理汇总了Python中testutils.mock.mock函数的典型用法代码示例。如果您正苦于以下问题:Python mock函数的具体用法?Python mock怎么用?Python mock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_createJob
def test_createJob(self):
job = self.job
mock.mock(dispatcher, 'getHandlerClass')
dispatcher.getHandlerClass._mock.setReturn(MockHandler, 'test')
saved = []
def db_createJob(newJob, frozen_handler, callback=None):
self.assertEqual(job.job_uuid, newJob.job_uuid)
ret = newJob.freeze()
saved.append(ret)
return defer.succeed(ret)
self.disp.db._mock.set(createJob=db_createJob)
fh_uuid = uuid.uuid4()
d = self.disp.createJob(job, firehose=str(fh_uuid))
assert isinstance(d, defer.Deferred)
def callback(result):
handler = self.disp.jobs.values()[0]
self.assertEqual(handler.job.freeze(), saved[0])
self.assertEqual(handler.started, True)
self.disp.firehose.subscribe._mock.assertCalled(
('job', str(job.job_uuid)), fh_uuid)
self.disp.firehose.publish._mock.assertCalled(
('job', str(job.job_uuid), 'self'), 'created')
d.addCallback(callback)
return d
示例2: _setupMockNode
def _setupMockNode(self):
from rmake.messagebus import messages
from rmake.multinode import messages as mnmessages
from rmake.multinode import workernode
# test how the node responds to various messages sent in from our
# fake client.
cfg = self.getNodeCfg()
server = workernode.rMakeWorkerNodeServer(cfg,
messageBusInfo=('localhost', None))
sessionClient = server.client.getBusClient().getSession()
mock.mockMethod(sessionClient.poll)
mock.mockMethod(sessionClient.connect)
mock.mockMethod(sessionClient.disconnect)
mock.mockMethod(sessionClient.messageProcessor.sendMessage)
mock.mock(sessionClient, 'logger')
sessionClient.handle_connect()
self._check(sessionClient, messages.ConnectionRequest,
sessionClass='WORKER')
m = messages.ConnectedResponse()
m.set(sessionId='WORKER-foo')
sessionClient.handle_message(m)
self._check(sessionClient, mnmessages.RegisterNodeMessage,
nodeType='WORKER', destination='/register')
self._check(sessionClient, messages.SubscribeRequest,
destination='/command?targetNode=WORKER-foo')
server._serveLoopHook()
self._check(sessionClient, mnmessages.NodeInfo,
destination='/nodestatus')
return server, sessionClient
示例3: testCreateProductVersion
def testCreateProductVersion(self):
db = self.openMintDatabase(createRepos=False)
self.createUser('admin', admin=True)
self.createProduct('foo', owners=['admin'], db=db)
self.assertRaises(mint_error.ProductVersionInvalid,
self.createProductVersion, db, 'foo', '/',
description='desc', platformLabel=None)
self.assertRaises(mint_error.InvalidLabel,
self.createProductVersion, db, 'foo', '1',
namespace='/',
description='desc', platformLabel=None)
self.assertRaises(mint_error.InvalidNamespace,
self.createProductVersion, db, 'foo', '1',
namespace='1'*20,
description='desc', platformLabel=None)
self.createProductVersion(db, 'foo', '1', description='desc',
platformLabel=None)
args, kw = db.productMgr.reposMgr.createSourceTrove._mock.popCall()
assert(not kw)
assert(len(args) == 6)
assert(args[0:4] == ('foo', 'group-foo-appliance',
'[email protected]:foo-1-devel', '1'))
assert(args[4].keys() == ['group-foo-appliance.recipe'])
assert(args[5] == 'Initial appliance image group template')
self.assertRaises(mint_error.DuplicateProductVersion,
self.createProductVersion,
db, 'foo', '1')
mock.mock(proddef.ProductDefinition, 'rebase')
self.createProductVersion(db, 'foo', '2',
platformLabel='[email protected]:1')
args, kw = proddef.ProductDefinition.rebase._mock.popCall()
assert(args[1] == '[email protected]:1')
示例4: testGetPackagePath
def testGetPackagePath(self):
realListDir = os.listdir
realExists = os.path.exists
def mockListDir(path):
if path.endswith('/qa'):
return ['asdf' ]
return realListDir(path)
def mockExists(path):
if path.endswith('CONARY'):
return True
if path.startswith('/PROD'):
return True
return realExists(path)
self.mock(os, 'listdir', lambda *args: mockListDir(*args))
self.mock(os.path, 'exists', lambda *args: mockExists(*args))
productStore = mock.MockInstance(dirstore.CheckoutProductStore)
productStore._mock.enableMethod('getPackagePath')
productStore.getStageDirectory._mock.setDefaultReturn('/PROD/qa')
handle = self.getRbuildHandle(productStore=productStore)
productStore._handle.facade.conary = mock.MockObject()
stateObj = mock.MockObject()
stateObj.getSourceState().getName._mock.setDefaultReturn('asdf:source')
mock.mock(state, 'ConaryStateFromFile')
state.ConaryStateFromFile._mock.setDefaultReturn(stateObj)
productStore._handle.facade.conary.getNameForCheckout._mock.setDefaultReturn('asdf')
productStore._handle.facade.conary.isGroupName._mock.setDefaultReturn(False)
packagePath = productStore.getPackagePath('asdf')
assert(packagePath == '/PROD/qa/asdf')
packagePath = productStore.getPackagePath('blah')
assert(packagePath is None)
示例5: testCancel
def testCancel(self):
from rbuild_plugins import images
mock.mockMethod(self.handle.DescriptorConfig.createDescriptorData)
mock.mock(images, 'xobj')
_doc = mock.MockObject()
_doc._mock.enable('job')
images.xobj.Document._mock.setReturn(_doc)
_job = mock.MockObject()
_job._mock.enable('job_type', 'descriptor')
images.xobj.XObj._mock.setReturn(_job)
_image_action = mock.MockObject()
_image_action._mock.set(key=images.Images.CANCEL)
_image_action._root._mock.set(job_type='job_type',
descriptor='descriptor')
_image = mock.MockObject()
_image._mock.set(key=images.Images.CANCEL, image_id='10', status='100',
actions=[_image_action])
_image.jobs.append._mock.setReturn(_doc, _doc)
rv = self.handle.Images.cancel(_image)
self.assertEqual(rv, _doc)
self.assertEqual(rv.job, _job)
self.assertEqual('job_type', rv.job.job_type)
self.assertEqual('descriptor', rv.job.descriptor)
示例6: testImageCommand
def testImageCommand(self):
eventHandler = mock.MockObject()
mock.mock(rbuilderclient, "RbuilderClient")
self.buildCfg.configLine("rmakeUser foo bar")
self.buildCfg.rbuilderUrl = "http://foo"
trv = imagetrove.ImageTrove(1, *self.makeTroveTuple("group-foo"))
trv.setProductName("product")
cmd = imagecommand.ImageCommand(self.rmakeCfg, "commandId", 1, eventHandler, self.buildCfg, trv)
client = cmd.client
client.newBuildWithOptions._mock.setDefaultReturn(21)
cmd.logger = mock.MockObject()
mock.mockMethod(cmd.watchImage)
cmd.runAttachedCommand()
cmd.watchImage._mock.assertCalled(21)
client.startImage._mock.assertCalled(21)
client.newBuildWithOptions._mock.assertCalled(
"product",
"group-foo",
trv.getVersion(),
trv.getFlavor(),
trv.getImageType(),
trv.getBuildName(),
trv.getImageOptions(),
)
client.newBuildWithOptions._mock.raiseErrorOnAccess(RuntimeError("error!"))
cmd.runAttachedCommand()
assert trv.isFailed()
assert str(trv.getFailureReason()) == "Failed while building: error!"
示例7: testVirtualHardwareVersion
def testVirtualHardwareVersion(self):
img = self.img
Mocked = set(['mkfs.ext3', 'tune2fs', ])
origLogCall = raw_hd_image.logCall
logCallArgs = []
def mockLogCall(cmd, **kw):
logCallArgs.append((cmd, kw))
if (isinstance(cmd, list) and cmd[0] in Mocked) or cmd.startswith('mount') or cmd.startswith('umount') or cmd.startswith('chroot'):
return
return origLogCall(cmd, **kw)
self.mock(raw_hd_image, 'logCall', mockLogCall)
self.mock(bootable_image, 'logCall', mockLogCall)
self.mock(bootable_image.loophelpers, 'logCall', mockLogCall)
mknodArgs = []
def mockMknod(*args):
mknodArgs.append(args)
self.mock(os, 'mknod', mockMknod)
chmodArgs = []
def mockChmod(*args):
chmodArgs.append(args)
self.mock(os, 'chmod', mockMknod)
util.mkdirChain(os.path.join(img.root, "root"))
file(os.path.join(img.root, "root", "conary-tag-script.in"), "w").write(
"echo nothing here")
util.mkdirChain(img.changesetDir)
mock.mockMethod(img.downloadChangesets)
mock.mockMethod(img.postOutput)
mock.mockMethod(img.loadRPM)
mock.mock(bootable_image.Filesystem, '_get_uuid')
bootable_image.Filesystem._get_uuid()._mock.setDefaultReturn('abc123')
self.mock(img, 'updateGroupChangeSet', lambda x: None)
img.write()
示例8: testUpdateOnBoot
def testUpdateOnBoot(self):
from conary.cmds import conarycmd
mock.mock(conarycmd, 'main')
r = self.Runner()
r.processProperties({'com.sas.app-engine.update-on-boot' : [ 'true' ]})
self.assertEquals(conarycmd.main._mock.calls,
[((['conary', 'updateall', '--no-interactive'],), ())])
示例9: testCreateProjectInteractive
def testCreateProjectInteractive(self):
handle = self.getRbuildHandle(mock.MockObject())
handle.Create.registerCommands()
handle.CreateProjectBranch.registerCommands()
handle.CreateProjectBranch.initialize()
mock.mockMethod(handle.facade.rbuilder.createProject)
mock.mock(handle, 'ui')
handle.ui.getResponse._mock.appendReturn(
'project name', "Project name (required)", required=True)
handle.ui.getResponse._mock.appendReturn(
'desc', "Project description (optional)")
handle.ui.getResponse._mock.appendReturn(
'shortname', "Unique name (required)",
validationFn=handle.facade.rbuilder.isValidShortName,
required=True)
handle.ui.getResponse._mock.appendReturn(
'domain.name', "Domain name (blank for default)",
validationFn=handle.facade.rbuilder.isValidDomainName)
cmd = handle.Commands.getCommandClass('create')()
cmd.runCommand(handle, {}, ['rbuild', 'create', 'project'])
handle.facade.rbuilder.createProject._mock.assertCalled(
title='project name',
shortName='shortname',
domainName='domain.name',
description='desc',
)
示例10: testDelete
def testDelete(self):
handle = self.handle
_target1 = mock.MockObject(name="foo", id="1")
_target2 = mock.MockObject(name="bar", id="2")
mock.mockMethod(handle.facade.rbuilder.getTargets)
handle.facade.rbuilder.getTargets._mock.setReturn(
[_target1, _target2])
handle.facade.rbuilder.getTargets._mock.appendReturn(
[_target1], target_id="1")
handle.facade.rbuilder.getTargets._mock.appendReturn(
[], target_id="bar")
mock.mock(handle, "ui")
handle.ui.getYn._mock.setDefaultReturn(False)
handle.ui.getYn._mock.setReturn(True, "Delete foo?", default=False)
handle.ui.getYn._mock.setReturn(True, "Delete bar?", default=False)
handle.Targets.delete("1", force=True)
handle.facade.rbuilder.getTargets._mock.assertCalled(target_id="1")
handle.ui.getYn._mock.assertNotCalled()
_target1.delete._mock.assertCalled()
handle.Targets.delete("1")
handle.facade.rbuilder.getTargets._mock.assertCalled(target_id="1")
handle.ui.getYn._mock.assertCalled("Delete foo?", default=False)
_target1.delete._mock.assertCalled()
handle.Targets.delete("bar")
handle.facade.rbuilder.getTargets._mock.assertCalled(target_id="bar")
handle.facade.rbuilder.getTargets._mock.assertCalled()
handle.ui.getYn._mock.assertCalled("Delete bar?", default=False)
_target2.delete._mock.assertCalled()
示例11: testGetWindowsBuildService
def testGetWindowsBuildService(self):
client = rbuilderfacade.RbuilderRESTClient('http://localhost', 'foo',
'bar', mock.MockObject())
mock.mock(client, '_api')
client._api._mock.set(inventory=mock.MockObject())
notwbs = mock.MockObject(system_type=mock.MockObject(
name='foobar'))
# Correct WBS system.
wbs = mock.MockObject(system_type=mock.MockObject(
name='infrastructure-windows-build-node'),
networks=[mock.MockObject(ip_address='1.2.3.4',
dns_name='foo.example.com'), ])
client._api.inventory._mock.set(infrastructure_systems=[wbs, notwbs])
address = client.getWindowsBuildService()
self.failUnlessEqual(address, '1.2.3.4')
# No WBS systems found.
wbs2 = mock.MockObject(system_type=mock.MockObject(name='bar'))
client._api.inventory._mock.set(infrastructure_systems=[wbs2, notwbs])
self.failUnlessRaises(errors.RbuildError, client.getWindowsBuildService)
# Selected WBS system doesn't have any networks.
wbs3 = mock.MockObject(system_type=mock.MockObject(
name='infrastructure-windows-build-node'),
networks=[])
client._api.inventory._mock.set(infrastructure_systems=[wbs3, notwbs])
self.failUnlessRaises(errors.RbuildError, client.getWindowsBuildService)
示例12: testIterRepositoryDiff
def testIterRepositoryDiff(self):
_, facade = self.prep()
repos, sourceState = self.prepReposState(facade)
ver = mock.MockObject()
lastver = mock.MockObject()
sourceState.getName._mock.setDefaultReturn('name')
sourceState.getVersion._mock.setDefaultReturn(ver)
mock.mockMethod(facade._getNewerRepositoryVersions)
facade._getNewerRepositoryVersions._mock.setDefaultReturn(['broken'])
mock.mock(facade, '_getVersion')
facade._getVersion._mock.setReturn(lastver, lastver)
mockedGetIterRdiff = mock.MockObject()
mockedGetIterRdiff._mock.setDefaultReturn(['asdf'])
self.mock(checkin, '_getIterRdiff', mockedGetIterRdiff)
output = [x for x in facade.iterRepositoryDiff('targetDirName',
lastver=lastver)]
mockedGetIterRdiff._mock.assertCalled(repos, ver.branch().label(),
'name', ver.asString(), lastver.asString())
self.assertEquals(output, ['asdf'])
facade._getNewerRepositoryVersions._mock.setDefaultReturn(
[None, None, None, lastver])
output = [x for x in facade.iterRepositoryDiff('targetDirName')]
mockedGetIterRdiff._mock.assertCalled(repos, ver.branch().label(),
'name', ver.asString(), lastver.asString())
self.assertEquals(output, ['asdf'])
示例13: testCheckoutBinaryPackage
def testCheckoutBinaryPackage(self):
_, facade = self.prep()
mock.mock(facade, '_getVersion')
mock.mock(facade, '_getFlavor')
mockConaryCfg = mock.MockObject()
mockConaryCfg._mock.enable('root')
mock.mockMethod(facade.getConaryConfig)
facade.getConaryConfig._mock.setDefaultReturn(mockConaryCfg)
# Pin callback object
callback = conaryfacade._QuietUpdateCallback()
self.mock(conaryfacade, '_QuietUpdateCallback', lambda: callback)
# quiet
savedArgs = []
doUpdateFn = lambda *args, **kwargs: mockedFunction(None, savedArgs,
None, *args, **kwargs)
self.mock(updatecmd, 'doUpdate', doUpdateFn)
facade.checkoutBinaryPackage('packageName', 'packageVersion',
'packageFlavor', 'targetDir')
self.assertEquals(mockConaryCfg.root, 'targetDir')
self.assertEquals(savedArgs, [
((mockConaryCfg, 'packageName=packageVersion[packageFlavor]'),
{'tagScript': None, 'callback': callback, 'depCheck': False})
])
# noisy
savedArgs = []
facade.checkoutBinaryPackage('packageName', 'packageVersion',
'packageFlavor', 'targetDir', quiet=False)
self.assertEquals(savedArgs, [
((mockConaryCfg, 'packageName=packageVersion[packageFlavor]'),
{'tagScript': None, 'callback': None, 'depCheck': False})
])
示例14: setUp
def setUp(self):
testcase.TestCaseWithWorkDir.setUp(self)
# Delete all root handlers
for handler in logging.root.handlers:
logging.root.removeHandler(handler)
logging.basicConfig(level=logging.DEBUG)
self.logHandler = logging.root.handlers[0]
mock.mockMethod(self.logHandler.handle)
self.cfg = config.UpsrvConfig()
self.cfg.downloadDB = "sqlite:///%s/%s" % (self.workDir, "upsrv.sqlite")
salt = file("/dev/urandom").read(8).encode('hex')
self.cfg.configLine('password %s %s' % (
self.Username, crypt.crypt(self.Password, '$1$%s$' % salt)))
self.wcfg = app.configure(self.cfg)
maker = self.wcfg.registry.settings['db.sessionmaker']
# New maker, without extensions, we don't need transaction
# management
makerArgs = maker.kw.copy()
del makerArgs['extension']
maker = maker.__class__(**makerArgs)
conn = maker()
db.schema.updateSchema(conn)
conn.commit()
self.conn = conn
self.app = self.wcfg.make_wsgi_app()
# Mock the conary config object
self.conaryCfg = conarycfg.ConaryConfiguration(False)
self.conaryCfg.root = "%s/%s" % (self.workDir, "__root__")
mock.mock(conarycfg, 'ConaryConfiguration', self.conaryCfg)
示例15: testGetCheckoutLog
def testGetCheckoutLog(self):
_, facade = self.prep()
repos, sourceState = self.prepReposState(facade)
sourceState.getName._mock.setDefaultReturn('name')
mock.mockMethod(facade._getRepositoryVersions)
mock.mockMethod(facade._getNewerRepositoryVersions)
facade._getRepositoryVersions._mock.setDefaultReturn(['1'])
facade._getNewerRepositoryVersions._mock.setDefaultReturn(['broken'])
flavor = mock.MockObject()
flavor._mock.setDefaultReturn(flavor)
self.mock(deps, 'Flavor', flavor)
trove = mock.MockObject()
repos.getTroves._mock.setReturn(trove, [('name', '1', flavor)])
mockedIterLogMessages = mock.MockObject()
mockedIterLogMessages._mock.setDefaultReturn(['asdf'])
self.mock(checkin, 'iterLogMessages', mockedIterLogMessages)
ret = facade.getCheckoutLog('targetDirName')
mockedIterLogMessages._mock.assertCalled(trove)
self.assertEquals(ret, ['asdf'])
facade._getNewerRepositoryVersions._mock.setDefaultReturn(['1'])
facade._getRepositoryVersions._mock.setDefaultReturn(['broken'])
ret = facade.getCheckoutLog('dir2', newerOnly=True)
mockedIterLogMessages._mock.assertCalled(trove)
self.assertEquals(ret, ['asdf'])
mock.mock(facade, '_getVersion')
facade._getVersion._mock.setReturn('1', 'string')
ret = facade.getCheckoutLog('dir3', versionList=['string'])
mockedIterLogMessages._mock.assertCalled(trove)
self.assertEquals(ret, ['asdf'])