本文整理汇总了Python中unittest.mock.MagicMock.return_value方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.return_value方法的具体用法?Python MagicMock.return_value怎么用?Python MagicMock.return_value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest.mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.return_value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gsssc
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def gsssc(definition, monkeypatch, event_loop):
server_id = 'test-000000'
database = MagicMock()
publish_cb = MagicMock()
use_observant = False
ignore_development = True
mkdir = MagicMock()
monkeypatch.setattr("os.mkdir", mkdir)
mkdir.return_value = True
chdir = MagicMock()
monkeypatch.setattr("os.chdir", chdir)
chdir.return_value = True
gssa.server.use_observant = False
gssa.server.GoSmartSimulationServerComponent._write_identity = MagicMock()
gsssc = gssa.server.GoSmartSimulationServerComponent(
server_id,
database,
publish_cb,
ignore_development,
use_observant
)
# In theory, this is redundant but ensures that we are not thinking
# about the thread callback timing
gsssc._db = MagicMock()
fd, fd_coro = magic_coro()
fd.side_effect = lambda g, resync=True, allow_many=False: (g, (definition if g == known_guid else False))
gsssc._fetch_definition = fd_coro
gsssc._fetch_definition_test = fd
gsssc.current[known_guid] = definition
return gsssc
示例2: test_bad_senza_yaml
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_bad_senza_yaml(app, monkeypatch, mock_senza):
data = {'keep_stacks': 0,
'stack_version': 1,
'new_traffic': 100,
'image_version': '1.0',
'stack_version': '40',
'senza_yaml': 'key: value'}
mock_senza = MagicMock()
mock_senza.return_value = mock_senza
monkeypatch.setattr('lizzy.api.Senza', mock_senza)
mock_senza.render_definition.side_effect = SenzaRenderError("Some error",
"output error")
request = app.post('/api/stacks', headers=GOOD_HEADERS,
data=json.dumps(data)) # type: flask.Response
assert request.status_code == 400
response = json.loads(request.data.decode())
assert response['title'] == 'Invalid senza yaml'
assert request.headers['X-Lizzy-Version'] == CURRENT_VERSION
mock_senza = MagicMock()
mock_senza.return_value = mock_senza
monkeypatch.setattr('lizzy.api.Senza', mock_senza)
mock_senza.render_definition.return_value = BAD_CF_DEFINITION
示例3: test_create_list_delete
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_create_list_delete(monkeypatch):
token = 'abc-123'
perform_implicit_flow = MagicMock()
perform_implicit_flow.return_value = {'access_token': token, 'expires_in': 1, 'token_type': 'test'}
monkeypatch.setattr('zign.api.perform_implicit_flow', perform_implicit_flow)
load_config = MagicMock()
load_config.return_value = {'authorize_url': 'https://localhost/authorize', 'token_url': 'https://localhost/token', 'client_id': 'foobar', 'business_partner_id': '123'}
monkeypatch.setattr('stups_cli.config.load_config', load_config)
runner = CliRunner()
with runner.isolated_filesystem():
result = runner.invoke(cli_zign, ['token', '-n', 'mytok', '--password', 'mypass'], catch_exceptions=False)
assert token == result.output.rstrip().split('\n')[-1]
result = runner.invoke(cli_zign, ['list', '-o', 'json'], catch_exceptions=False)
data = json.loads(result.output)
assert len(data) >= 1
assert 'mytok' in [r['name'] for r in data]
result = runner.invoke(cli_zign, ['delete', 'mytok'], catch_exceptions=False)
result = runner.invoke(cli_zign, ['list', '-o', 'json'], catch_exceptions=False)
data = json.loads(result.output)
assert 'mytok' not in [r['name'] for r in data]
# should work again for already deleted tokens
result = runner.invoke(cli_zign, ['delete', 'mytok'], catch_exceptions=False)
示例4: test_getClientFilesValidBinaryFilesReturn200OctetStreamAndContent
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_getClientFilesValidBinaryFilesReturn200OctetStreamAndContent(self):
testPath = "/blub"
testFileContent = bytes("testdata", "UTF-8")
self.handler._clientResourceBaseDir = "/testBaseDir/"
getFileEncodingMock = MagicMock()
getFileEncodingMock.return_value = None
readFileToBytesMock = MagicMock()
readFileToBytesMock.return_value = testFileContent
with patch('server.piledhttprequesthandler.getFileEncoding', new=getFileEncodingMock), \
patch('server.piledhttprequesthandler.readFileToBytes', new=readFileToBytesMock):
_sendResponseMock = MagicMock()
self.handler.send_response = _sendResponseMock
_sendHeaderMock = MagicMock()
self.handler.send_header = _sendHeaderMock
_endHeadersMock = MagicMock()
self.handler.end_headers = _endHeadersMock
self.handler.wfile = MagicMock()
_wFileWriteMock = MagicMock()
self.handler.wfile.write = _wFileWriteMock
self.handler._getClientFile(testPath)
getFileEncodingMock.assert_called_once_with(self.handler._clientResourceBaseDir + testPath[1:])
readFileToBytesMock.assert_called_once_with(self.handler._clientResourceBaseDir + testPath[1:], None)
_sendResponseMock.assert_called_once_with(200)
_sendHeaderMock.assert_called_once_with("Content-type", "application/octet-stream")
assert _endHeadersMock.called
_wFileWriteMock.assert_called_with(testFileContent)
示例5: test_get_elastigroup_entities
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_get_elastigroup_entities(monkeypatch):
stack_names = MagicMock()
stack_names.return_value = ['foo', 'bar']
monkeypatch.setattr('zmon_aws_agent.elastigroup.get_all_stack_names', stack_names)
elastigroup_resources = MagicMock()
elastigroup_resources.return_value = [Elastigroup('42', 'test', 'acct-id', 'acc-tkn')]
monkeypatch.setattr('zmon_aws_agent.elastigroup.get_elastigroup_resources', elastigroup_resources)
elastigroup = MagicMock()
elastigroup.return_value = {'name': 'test', 'created_at': 'now',
'compute': {'availability_zones': [{'name': 'az1'}],
'instance_types': ['type1', 'type2'],
'launch_specification': {
'tags': [{'tag_key': 'tag1', 'tag_value': 'value1'}]
}},
'capacity': {'target': 1, 'maximum': 1, 'minimum': 1},
'strategy': {'risk': 100, 'availability_vs_cost': 'balanced'}}
monkeypatch.setattr('zmon_aws_agent.elastigroup.get_elastigroup', elastigroup)
elastigroup_status = MagicMock()
elastigroup_status.return_value = [{"instance_id": "i-fake", "private_ip": "127.0.0.1"}]
monkeypatch.setattr('zmon_aws_agent.elastigroup.get_elastigroup_instances', elastigroup_status)
entities = zmon_aws_agent.elastigroup.get_elastigroup_entities('region1', 'acc1')
assert len(entities) == 2
first = entities[0]
assert first['type'] == 'elastigroup'
assert first['risk'] == 100
assert first['orientation'] == 'balanced'
assert first['tag1'] == 'value1' # validate that tags are added
first_instance = first['instances'][0]
assert first_instance['aws_id'] == 'i-fake'
assert first_instance['ip'] == '127.0.0.1'
示例6: test_getClientFilesValidTextFilesReturn200ContentTypeBasedOnFileNameAndContent
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_getClientFilesValidTextFilesReturn200ContentTypeBasedOnFileNameAndContent(self):
testPath = "/blub.css"
testFileContent = bytes("testdata", "UTF-8")
self.handler._clientResourceBaseDir = "/testBaseDir/"
getFileEncodingMock = MagicMock()
getFileEncodingMock.return_value = "UTF-8"
readFileToBytesMock = MagicMock()
readFileToBytesMock.return_value = testFileContent
with patch('server.piledhttprequesthandler.getFileEncoding', new=getFileEncodingMock), \
patch('server.piledhttprequesthandler.readFileToBytes', new=readFileToBytesMock):
_sendResponseMock = MagicMock()
self.handler.send_response = _sendResponseMock
_sendHeaderMock = MagicMock()
self.handler.send_header = _sendHeaderMock
_endHeadersMock = MagicMock()
self.handler.end_headers = _endHeadersMock
self.handler.wfile = MagicMock()
_wFileWriteMock = MagicMock()
self.handler.wfile.write = _wFileWriteMock
self.handler._getClientFile(testPath)
getFileEncodingMock.assert_called_once_with(self.handler._clientResourceBaseDir + testPath[1:])
readFileToBytesMock.assert_called_once_with(self.handler._clientResourceBaseDir + testPath[1:], "UTF-8")
_sendResponseMock.assert_called_once_with(200)
_sendHeaderMock.assert_called_once_with("Content-type", "text/css")
assert _endHeadersMock.called
_wFileWriteMock.assert_called_with(testFileContent)
示例7: test_loadJSONBodyExceptionRaisedOnEmptyBody
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_loadJSONBodyExceptionRaisedOnEmptyBody(self):
_contentLengthMock = MagicMock()
_contentLengthMock.return_value = 0
self.handler.headers = MagicMock()
self.handler.headers.get = _contentLengthMock
_rFileReadMock = MagicMock()
_rFileReadMock.return_value = ""
self.handler.rfile = MagicMock()
self.handler.rfile.read = _rFileReadMock
self.assertRaises(Exception, self.handler.loadJSONBody())
示例8: test_weighted_dns_load_balancer_v2
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_weighted_dns_load_balancer_v2(monkeypatch, boto_client, boto_resource): # noqa: F811
senza.traffic.DNS_ZONE_CACHE = {}
configuration = {
"Name": "MyLB",
"SecurityGroups": "",
"HTTPPort": "9999",
'MainDomain': 'great.api.zo.ne',
'VersionDomain': 'version.api.zo.ne',
# test overwritting specific properties in one of the resources
'TargetGroupAttributes': [{'Key': 'deregistration_delay.timeout_seconds', 'Value': '123'}],
# test that Security Groups are resolved
'SecurityGroups': ['foo-security-group']
}
info = {'StackName': 'foobar', 'StackVersion': '0.1'}
definition = {"Resources": {}}
args = MagicMock()
args.region = "foo"
mock_string_result = MagicMock()
mock_string_result.return_value = ['sg-foo']
monkeypatch.setattr('senza.components.elastic_load_balancer_v2.resolve_security_groups', mock_string_result)
get_ssl_cert = MagicMock()
get_ssl_cert.return_value = 'arn:aws:42'
monkeypatch.setattr('senza.components.elastic_load_balancer_v2.get_ssl_cert', get_ssl_cert)
result = component_weighted_dns_elastic_load_balancer_v2(definition,
configuration,
args,
info,
False,
AccountArguments('dummyregion'))
assert 'MyLB' in result["Resources"]
assert 'MyLBListener' in result["Resources"]
assert 'MyLBTargetGroup' in result["Resources"]
target_group = result['Resources']['MyLBTargetGroup']
lb_listener = result['Resources']['MyLBListener']
assert target_group['Properties']['HealthCheckPort'] == '9999'
assert lb_listener['Properties']['Certificates'] == [
{'CertificateArn': 'arn:aws:42'}
]
# test that our custom drain setting works
assert target_group['Properties']['TargetGroupAttributes'] == [
{'Key': 'deregistration_delay.timeout_seconds',
'Value': '123'}
]
assert result['Resources']['MyLB']['Properties']['SecurityGroups'] == ['sg-foo']
示例9: test_docker_image_exists
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_docker_image_exists(monkeypatch):
get = MagicMock()
monkeypatch.setattr('requests.get', get)
get.return_value = MagicMock(name='response')
get.return_value.json = lambda: {'1.0': 'foo'}
assert docker_image_exists('my-registry/foo/bar:1.0') == True
get.return_value = None
assert docker_image_exists('foo/bar:1.0') == False
get.return_value = None
assert docker_image_exists('my-registry/foo/bar:1.0') == False
示例10: test_cancel_recent
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_cancel_recent(
self,
query_choice: MagicMock,
configs_fetch: MagicMock
):
""" should cancel if indicated by user query response """
configs_fetch.return_value = ['a', 'b', 'c']
query_choice.return_value = (3, None)
r = Response()
result = open_actions.fetch_recent(r)
self.assertFalse(r.failed, 'should not have failed')
self.assertIsNone(result)
示例11: test_recent_choice
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_recent_choice(
self,
query_choice: MagicMock,
configs_fetch: MagicMock
):
""" should return path chosen by user query response """
configs_fetch.return_value = ['a', 'b', 'c']
query_choice.return_value = (1, 'b')
r = Response()
result = open_actions.fetch_recent(r)
self.assertFalse(r.failed, 'should not have failed')
self.assertEqual(result, 'b')
示例12: test_component_load_balancer_cert_arn
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_component_load_balancer_cert_arn(monkeypatch):
configuration = {
"Name": "test_lb",
"SecurityGroups": "",
"HTTPPort": "9999",
"SSLCertificateId": "foo2"
}
info = {'StackName': 'foobar', 'StackVersion': '0.1'}
definition = {"Resources": {}}
args = MagicMock()
args.region = "foo"
mock_string_result = MagicMock()
mock_string_result.return_value = "foo"
monkeypatch.setattr('senza.components.elastic_load_balancer.resolve_security_groups', mock_string_result)
m_acm = MagicMock()
m_acm_certificate = MagicMock()
m_acm_certificate.arn = "foo"
m_acm.get_certificates.return_value = iter([m_acm_certificate])
m_acm_certificate.is_arn_certificate.return_value = True
m_acm_certificate.get_by_arn.return_value = True
monkeypatch.setattr('senza.components.elastic_load_balancer.ACM', m_acm)
monkeypatch.setattr('senza.components.elastic_load_balancer.ACMCertificate', m_acm_certificate)
# issue 105: support additional ELB properties
result = component_elastic_load_balancer(definition, configuration, args, info, False, MagicMock())
assert "foo2" == result["Resources"]["test_lb"]["Properties"]["Listeners"][0]["SSLCertificateId"]
示例13: test_component_load_balancer_idletimeout
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_component_load_balancer_idletimeout(monkeypatch):
configuration = {
"Name": "test_lb",
"SecurityGroups": "",
"HTTPPort": "9999",
"ConnectionSettings": {"IdleTimeout": 300}
}
info = {'StackName': 'foobar', 'StackVersion': '0.1'}
definition = {"Resources": {}}
args = MagicMock()
args.region = "foo"
mock_string_result = MagicMock()
mock_string_result.return_value = "foo"
monkeypatch.setattr('senza.components.elastic_load_balancer.resolve_security_groups', mock_string_result)
m_acm = MagicMock()
m_acm_certificate = MagicMock()
m_acm_certificate.arn = "foo"
m_acm.get_certificates.return_value = iter([m_acm_certificate])
monkeypatch.setattr('senza.components.elastic_load_balancer.ACM', m_acm)
# issue 105: support additional ELB properties
result = component_elastic_load_balancer(definition, configuration, args, info, False, MagicMock())
assert 300 == result["Resources"]["test_lb"]["Properties"]["ConnectionSettings"]["IdleTimeout"]
assert 'HTTPPort' not in result["Resources"]["test_lb"]["Properties"]
示例14: test_render_definition
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def test_render_definition(monkeypatch, popen):
senza = Senza('region')
senza.logger = MagicMock()
mock_named_tempfile = MagicMock()
mock_tempfile = MagicMock()
mock_tempfile.name = 'lizzy.yaml'
mock_named_tempfile.__enter__.return_value = mock_tempfile
mock_named_tempfile.return_value = mock_named_tempfile
monkeypatch.setattr('tempfile.NamedTemporaryFile', mock_named_tempfile)
senza.render_definition('yaml content', 'version42', 'imgversion22',
['Param1=app', 'SecondParam=3'])
cmd = 'senza print --region region -o json --force lizzy.yaml version42 ' \
'imgversion22 Param1=app SecondParam=3'
popen.assert_called_with(cmd.split(" "), stdout=-1, stderr=-1)
assert not senza.logger.error.called
senza.render_definition('yaml content', None, 'imgversion22',
['Param1=app', 'SecondParam=3'])
assert not senza.logger.error.called
# test error case
popen.side_effect = ExecutionError('', '')
with pytest.raises(SenzaRenderError):
senza.render_definition('yaml content', 'version42', 'imgversion22',
['Param1=app', 'SecondParam=3'])
示例15: popen
# 需要导入模块: from unittest.mock import MagicMock [as 别名]
# 或者: from unittest.mock.MagicMock import return_value [as 别名]
def popen(monkeypatch):
mock_popen = MagicMock()
mock_popen.return_value = mock_popen
mock_popen.returncode = 0
mock_popen.communicate.return_value = b'{"stream": "stdout"}', b'stderr'
monkeypatch.setattr('lizzy.apps.common.Popen', mock_popen)
return mock_popen