本文整理匯總了Python中asynctest.Mock類的典型用法代碼示例。如果您正苦於以下問題:Python Mock類的具體用法?Python Mock怎麽用?Python Mock使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Mock類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_matrix_list_context_superset
def test_matrix_list_context_superset(JobSpec):
from jenkins_yml import Job
from jenkins_epo.jenkins import MatrixJob
api_instance = Mock(spec=['_get_config_element_tree', 'get_params'])
api_instance.name = 'matrix'
api_instance._data = dict(activeConfigurations=[
{'name': 'A=0,B=a'},
{'name': 'A=1,B=a'},
{'name': 'A=0,B=b'},
{'name': 'A=1,B=b'},
{'name': 'A=0,B=c'},
{'name': 'A=1,B=c'},
])
xml = api_instance._get_config_element_tree.return_value
xml.findall.return_value = []
xml.find.return_value = None
jenkins_spec = JobSpec.from_xml.return_value
jenkins_spec.config = dict(axis={'A': [0, 1], 'B': 'abc'})
job = MatrixJob(api_instance)
spec = Job('matrix', dict(axis={'B': 'acd'}))
contexts = [c for c in job.list_contexts(spec)]
haystack = '\n'.join(contexts)
assert 'A=0' in haystack
assert 'A=1' not in haystack
assert 'B=b' not in haystack
assert 2 == len(contexts)
示例2: test_matrix_list_context_node
def test_matrix_list_context_node():
from jenkins_yml import Job
from jenkins_epo.jenkins import MatrixJob
api_instance = Mock(spec=['_get_config_element_tree', 'get_params'])
api_instance.name = 'matrix'
api_instance._data = dict(activeConfigurations=[
{'name': 'NODE=slave-legacy,P=a'},
{'name': 'NODE=slave-ng,P=a'},
{'name': 'NODE=slave-legacy,P=b'},
{'name': 'NODE=slave-ng,P=b'},
])
xml = api_instance._get_config_element_tree.return_value
xml.findall.return_value = []
xml.find.return_value = None
job = MatrixJob(api_instance)
job._node_axis = 'NODE'
spec = Job('matrix', dict(
node='slave-ng',
axis={'P': ['a', 'b', 4.3]},
))
contexts = [c for c in job.list_contexts(spec)]
assert 2 == len(contexts)
assert 'NODE=slave-legacy' not in ''.join(contexts)
assert 'NODE=slave-ng' in ''.join(contexts)
示例3: test_create_job
def test_create_job(mocker, SETTINGS):
from jenkins_epo.jenkins import LazyJenkins
JENKINS = LazyJenkins(Mock())
JENKINS.rest = Mock()
JENKINS.rest.createItem.apost = CoroutineMock()
JENKINS.rest.job().api.python.aget = CoroutineMock(return_value=dict(
url='url://', name='job',
))
JENKINS.rest.job()('config.xml').aget = CoroutineMock(
return_value=Mock(data='<project/>')
)
spec = Mock(config=dict())
spec.name = 'job'
SETTINGS.DRY_RUN = 1
job = yield from JENKINS.create_job(spec)
assert job is None
assert 'updated_at' in spec.config['description']
assert not JENKINS.rest.createItem.apost.mock_calls
SETTINGS.DRY_RUN = 0
job = yield from JENKINS.create_job(spec)
assert job
assert JENKINS.rest.createItem.apost.mock_calls
assert JENKINS.rest.job().api.python.aget.mock_calls
assert JENKINS.rest.job()().aget.mock_calls
示例4: test_matrix_build
def test_matrix_build(mocker, SETTINGS):
JENKINS = mocker.patch('jenkins_epo.jenkins.JENKINS')
from jenkins_epo.jenkins import MatrixJob, JobSpec
SETTINGS.DRY_RUN = 0
api_instance = Mock()
api_instance.name = 'matrix'
api_instance._data = {'url': 'https://jenkins/job'}
xml = api_instance._get_config_element_tree.return_value
xml.findall.return_value = []
xml.find.return_value = None
spec = JobSpec(api_instance.name)
spec.config['parameters'] = {'PARAM': 1}
job = MatrixJob(api_instance)
job._node_axis = job._revision_param = None
job._combination_param = 'C'
job._revision_param = 'R'
yield from job.build(
Mock(url='url://', fullref='refs/heads/master'), spec, 'matrix',
)
assert JENKINS.rest.job().buildWithParameters.mock_calls
示例5: test_run_extension
def test_run_extension(mocker):
pkg_resources = mocker.patch('jenkins_epo.bot.pkg_resources')
from jenkins_epo.bot import Bot
ep = Mock()
ep.name = 'ext'
pkg_resources.iter_entry_points.return_value = [ep]
ext = ep.resolve.return_value.return_value
ext.DEFAULTS = {}
ext.SETTINGS = {}
ext.run.return_value = []
bot = Bot()
assert 'ext' in bot.extensions_map
pr = Mock(name='pr', payload=dict())
pr.fetch_commits = CoroutineMock()
commits = [Mock()]
pr.repository.process_commits.return_value = commits
pr.fetch_comments = CoroutineMock(return_value=[])
commits[0].fetch_statuses = CoroutineMock()
yield from bot.run(pr)
assert pr.fetch_commits.mock_calls
assert pr.fetch_comments.mock_calls
assert ext.begin.mock_calls
assert ext.run.mock_calls
示例6: test_update_job
def test_update_job(mocker, SETTINGS):
aget_job = mocker.patch(
'jenkins_epo.jenkins.JENKINS.aget_job',
CoroutineMock(),
)
rest = mocker.patch('jenkins_epo.jenkins.JENKINS.rest')
url = rest.job()
url.api.python.aget = CoroutineMock()
url().aget = CoroutineMock()
url().apost = CoroutineMock()
from jenkins_epo.jenkins import Job
SETTINGS.DRY_RUN = 1
spec = Mock(config=dict())
spec.name = 'job'
job = Job(Mock(_data=dict()))
new_job = yield from job.update(spec)
assert new_job is job
SETTINGS.DRY_RUN = 0
new_job = yield from job.update(spec)
assert new_job is not job
assert aget_job.mock_calls
示例7: test_handler_logger
async def test_handler_logger(self):
mock = Mock()
record = {"request": None, "response": None}
class App(jj.App):
resolver = self.resolver
@LoggerMiddleware(self.resolver, mock)
@MethodMatcher(resolver, "*")
async def handler(request):
record["request"] = request
response = Response(status=200)
record["response"] = response
return response
async with run(App()) as client:
response = await client.get("/")
self.assertEqual(response.status, 200)
mock.assert_has_calls([
call.info(record["request"], extra={
"jj_request": record["request"],
}),
call.info(record["response"], extra={
"jj_request": record["request"],
"jj_response": record["response"],
}),
])
self.assertEqual(mock.info.call_count, 2)
示例8: test_app_middleware_with_handlers
async def test_app_middleware_with_handlers(self):
mock = Mock()
class Middleware(BaseMiddleware):
async def do(self, r, h, a):
mock(r, h, a)
return await h(r)
@Middleware(self.resolver)
class App(jj.App):
resolver = self.resolver
@MethodMatcher(resolver, "*")
async def handler(request):
return Response(status=200)
app = App()
async with run(app) as client:
response = await client.get("/")
self.assertEqual(response.status, 200)
mock.assert_called_once()
request_arg, handler_arg, app_arg = mock.call_args[0]
self.assertIsInstance(request_arg, Request)
self.assertEqual(handler_arg, App.handler)
self.assertEqual(app_arg, app)
示例9: test_send_membership
def test_send_membership(self):
account = Account("test_salt", "H8uYXvyF6GWeCr8cwFJ6V5B8tNprwRdjepFNJBqivrzr",
"test_account", [], [], [],
self.identities_registry)
account_identity = MagicMock(autospec='sakia.core.registry.Identity')
account_identity.selfcert = CoroutineMock(return_value=SelfCertification(2, "meta_brouzouf",
"H8uYXvyF6GWeCr8cwFJ6V5B8tNprwRdjepFNJBqivrzr", "test_account", 1000000000, ""))
community = MagicMock(autospec='sakia.core.Community')
community.blockUID = CoroutineMock(return_value=BlockUID(3102, "0000C5336F0B64BFB87FF4BC858AE25726B88175"))
self.identities_registry.future_find = CoroutineMock(return_value=account_identity)
community.bma_access = MagicMock(autospec='sakia.core.net.api.bma.access.BmaAccess')
response = Mock()
response.json = CoroutineMock(return_value={
"signature": "H41/8OGV2W4CLKbE35kk5t1HJQsb3jEM0/QGLUf80CwJvGZf3HvVCcNtHPUFoUBKEDQO9mPK3KJkqOoxHpqHCw==",
"membership": {
"version": 2,
"currency": "beta_brouzouf",
"issuer": "HsLShAtzXTVxeUtQd7yi5Z5Zh4zNvbu8sTEZ53nfKcqY",
"membership": "IN",
"sigDate": 1390739944,
"uid": "superman63"
}
})
response.status = 200
community.bma_access.broadcast = CoroutineMock(return_value=[response])
async def exec_test():
result = await account.send_membership("test_password", community, "IN")
self.assertTrue(result)
self.lp.run_until_complete(exec_test())
示例10: test_run_skip_closed
def test_run_skip_closed(mocker):
pkg_resources = mocker.patch('jenkins_epo.bot.pkg_resources')
from jenkins_epo.bot import Bot
pkg_resources.iter_entry_points.return_value = []
pr = Mock(name='pr')
pr.payload = dict(state='closed')
yield from Bot().run(pr)
示例11: test_fetch_builds
def test_fetch_builds(mocker):
Client = mocker.patch('jenkins_epo.jenkins.rest.Client')
Client().api.python.aget = aget = CoroutineMock(
return_value=dict(builds=[])
)
from jenkins_epo.jenkins import Job
api_instance = Mock(_data=dict())
api_instance.name = 'freestyle'
job = Job(api_instance)
yield from job.fetch_builds()
assert aget.mock_calls
示例12: request
def request(method, url, data, headers):
eq_(method, 'get')
eq_(url, 'url')
eq_(data, '{"message": "text"}')
eq_(headers, {
'Content-Type': 'application/json',
'Accept': 'application/json'
})
m = Mock()
m.status = 200
@future_func
def to_json():
return {'response': 'text'}
m.json = to_json
return m
示例13: test_004_patch_rest_configuration
async def test_004_patch_rest_configuration(self, bus_stop_mock):
req = Mock()
async def json():
return {
'bus': {'jid': '[email protected]'},
'new': True
}
req.headers = {'Content-Type': 'application/json'}
req.json = json
await self.apiconf.patch(req)
eq_(self.nyuki._config['new'], True)
eq_(self.nyuki._config['bus']['jid'], '[email protected]')
# finish coroutines
await exhaust_callbacks(self.loop)
bus_stop_mock.assert_called_once_with()
示例14: test_main_sync
def test_main_sync(mocker):
COMMANDS = []
mocker.patch('jenkins_epo.main.COMMANDS', COMMANDS)
command = Mock()
command.__name__ = 'bot'
command.__code__ = Mock(co_varnames=(), co_argcount=0)
command._is_coroutine = None
COMMANDS.append(command)
from jenkins_epo.main import main
assert not asyncio.iscoroutinefunction(command)
main(argv=['bot'])
assert command.mock_calls
示例15: test_apost
def test_apost(mocker):
from jenkins_epo.github import CustomGitHub, ApiError
aiohttp = mocker.patch('jenkins_epo.github.aiohttp')
session = aiohttp.ClientSession.return_value
response = Mock(spec=['headers', 'json', 'status'])
session.post = CoroutineMock(return_value=response)
response.status = 304
response.content_type = 'application/json'
response.headers = {'ETag': 'cafed0d0'}
response.json = CoroutineMock(return_value={'message': 'Not found'})
GITHUB = CustomGitHub(access_token='cafed0d0')
with pytest.raises(ApiError):
yield from GITHUB.user.apost(pouet=True)