本文整理汇总了Python中mock.mock_open方法的典型用法代码示例。如果您正苦于以下问题:Python mock.mock_open方法的具体用法?Python mock.mock_open怎么用?Python mock.mock_open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock
的用法示例。
在下文中一共展示了mock.mock_open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _assert_mock_read
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def _assert_mock_read(self, page_content):
mock_config = {
'colors': {
'command': 'cyan',
'description': 'blue',
'usage': 'green'
},
'platform': 'linux',
'repo_directory': '/tmp/tldr'
}
expected_result = (
'\n'
'\x1b[0m\x1b[34m Main node command\n'
'\x1b[0m\n\x1b[0m\x1b[32m- Call an interactive node shell'
'\n\x1b[0m\n\x1b[0m\x1b[36m node\n'
'\x1b[0m\n\x1b[0m\x1b[32m- Execute node on a JS file\n'
'\x1b[0m\n\x1b[0m\x1b[36m node {{FILENAME}}.js\n'
'\x1b[0m\n\x1b[0m'
)
with mock.patch('tldr.parser.get_config', return_value=mock_config):
with mock.patch('io.open', mock.mock_open(read_data=page_content)):
result = parse_page('/repo_directory/pages/common/node.md')
assert ''.join(result) == expected_result
示例2: test_categorization_response_error
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_categorization_response_error(self):
"""Tests whether the ResponseError is raised when the response
returned from the actual API call is empty.
"""
domains = ['yosemite.gov', 'joushuatree.gov', 'deathvalley.gov']
# empty responses should raise an error
all_responses = [{}]
# mock cache file
mock_read = mock_open(read_data="{}")
with patch.object(
builtins, 'open', mock_read, create=True
), patch.object(
ApiCache, 'bulk_lookup', autospec=True, return_value={}
), patch.object(
MultiRequest, 'multi_post', autospec=True, return_value=all_responses
):
i = InvestigateApi('hocus pocus', 'cache.json')
with T.assert_raises(ResponseError):
i.categorization(domains)
示例3: _open_cache
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def _open_cache(self, initial_contents=None, update_cache=True):
"""Creates an ApiCache object, mocking the contents of the cache on disk.
Args:
initial_contents: A dict containing the initial contents of the cache
update_cache: Specifies whether ApiCache should write out the
cache file when closing it
Returns:
ApiCache
"""
if not initial_contents:
initial_contents = {}
file_contents = simplejson.dumps(initial_contents)
mock_read = mock_open(read_data=file_contents)
with patch.object(builtins, 'open', mock_read, create=True):
api_cache = ApiCache(self._file_name, update_cache=update_cache)
return api_cache
示例4: _close_cache
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def _close_cache(self, api_cache, cache_written=True):
"""Closes an ApiCache and reads the final contents that were written to disk.
Args:
api_cache: An ApiCache instance
cache_written: Specifies whether it should test that the cache
was written out to the cache file or whether to
test that it was not written out
Returns:
A dict representing the contents of the cache that was written
out to the cache file or `None` in case cache was not expected
to be written out
"""
mock_write = mock_open()
with patch.object(builtins, 'open', mock_write, create=True) as patched_open:
api_cache.close()
if cache_written:
return assert_cache_written(mock_write, patched_open)
return assert_cache_not_written(mock_write)
示例5: test_user_agent
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_user_agent(self):
standard = "RIPE Atlas Tools (Magellan) {}".format(__version__)
tests = {
standard: standard,
"Some custom agent": "Some custom agent",
"Some custom agent\nwith a second line": "Some custom agent",
"x" * 3000: "x" * 128,
"Πράκτορας χρήστη": "Πράκτορας χρήστη",
"이것은 테스트 요원": "이것은 테스트 요원",
}
self.assertEqual(self.cmd.user_agent, standard)
for in_string, out_string in tests.items():
path = "ripe.atlas.tools.commands.base.open"
content = mock.mock_open(read_data=in_string)
with mock.patch(path, content, create=True):
self.assertEqual(Command().user_agent, out_string)
示例6: test_load_hints
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_load_hints(self):
"""
Test the load_hints() function
"""
from flashre.hints import load_hints
from flashre.binaries_helpers import ReverseFlashairBinary
# Build a fake ReverseFlashairBinary object
# Note: get_r2pipe() could be mocked too!
rfb = ReverseFlashairBinary("", 0)
rfb.strings = mock.MagicMock(return_value=list())
# Some bad inputs
bad_inputs = list()
bad_inputs.append("x\n")
bad_inputs.append("x:\n")
bad_inputs.append(" 2dc6e0: d0 01 mov $1,$tp\n")
bad_inputs.append(" 100: 00 70 di\n")
# Mock the open() builtin
m_open = mock.mock_open()
m_open.return_value = bad_inputs
with mock.patch("flashre.hints.open", m_open):
assert load_hints(rfb, "") is None
示例7: test_remove_permissions_from_roles
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_remove_permissions_from_roles(self, mock_hooks):
import json
cli = repokid.cli.repokid_cli
arns = [role["Arn"] for role in ROLES]
arns = json.dumps(arns)
class Hooks:
def call_hooks(hooks, tag, role_dict):
assert tag == "AFTER_REPO"
mock_hooks = Hooks()
with patch("builtins.open", mock_open(read_data=arns)) as mock_file:
assert open("somefile.json").read() == arns
mock_file.assert_called_with("somefile.json")
cli.remove_permissions_from_roles(
["s3:putobjectacl"],
"somefile.json",
None,
None,
mock_hooks,
commit=False,
)
示例8: test_default_model_fn
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_default_model_fn(path_exists, mx_load_checkpoint, mx_module, mx_cpu):
sym = Mock()
args = Mock()
aux = Mock()
mx_load_checkpoint.return_value = [sym, args, aux]
mx_context = Mock()
mx_cpu.return_value = mx_context
data_name = 'foo'
data_shape = [1]
signature = json.dumps([{'name': data_name, 'shape': data_shape}])
with patch('six.moves.builtins.open', mock_open(read_data=signature)):
DefaultMXNetInferenceHandler().default_model_fn(MODEL_DIR)
mx_load_checkpoint.assert_called_with(os.path.join(MODEL_DIR, 'model'), 0)
init_call = call(symbol=sym, context=mx_context, data_names=[data_name], label_names=None)
assert init_call in mx_module.mock_calls
model = mx_module.return_value
model.bind.assert_called_with(for_training=False, data_shapes=[(data_name, data_shape)])
model.set_params.assert_called_with(args, aux, allow_missing=True)
示例9: test_default_model_fn_with_accelerator
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_default_model_fn_with_accelerator(path_exists, mx_load_checkpoint, mx_module, mx_eia):
sym = Mock()
args = Mock()
aux = Mock()
mx_load_checkpoint.return_value = [sym, args, aux]
eia_context = Mock()
mx_eia.return_value = eia_context
data_name = 'foo'
data_shape = [1]
signature = json.dumps([{'name': data_name, 'shape': data_shape}])
with patch('six.moves.builtins.open', mock_open(read_data=signature)):
DefaultMXNetInferenceHandler().default_model_fn(MODEL_DIR)
mx_load_checkpoint.assert_called_with(os.path.join(MODEL_DIR, 'model'), 0)
init_call = call(symbol=sym, context=eia_context, data_names=[data_name], label_names=None)
assert init_call in mx_module.mock_calls
model = mx_module.return_value
model.bind.assert_called_with(for_training=False, data_shapes=[(data_name, data_shape)])
model.set_params.assert_called_with(args, aux, allow_missing=True)
示例10: test_put_file
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_put_file(self, fake_sftp_client, fake_ssh_client):
inventory = make_inventory(hosts=('anotherhost',))
state = State(inventory, Config())
host = inventory.get_host('anotherhost')
host.connect(state)
fake_open = mock_open(read_data='test!')
with patch('pyinfra.api.util.open', fake_open, create=True):
status = host.put_file(
state, 'not-a-file', 'not-another-file',
print_output=True,
)
assert status is True
fake_sftp_client.from_transport().putfo.assert_called_with(
fake_open(), 'not-another-file',
)
示例11: test_get_file
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_get_file(self, fake_sftp_client, fake_ssh_client):
inventory = make_inventory(hosts=('somehost',))
state = State(inventory, Config())
host = inventory.get_host('somehost')
host.connect(state)
fake_open = mock_open(read_data='test!')
with patch('pyinfra.api.util.open', fake_open, create=True):
status = host.get_file(
state, 'not-a-file', 'not-another-file',
print_output=True,
)
assert status is True
fake_sftp_client.from_transport().getfo.assert_called_with(
'not-a-file', fake_open(),
)
示例12: test_get_osinfo_from_os_release
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_get_osinfo_from_os_release(self):
data = ['NAME="Ubuntu"', 'VERSION="14.04.4 LTS, Trusty Tahr"',
'ID=ubuntu', 'ID_LIKE=debian',
'PRETTY_NAME="Ubuntu 14.04.4 LTS"', 'VERSION_ID="14.04"',
'HOME_URL="http://www.ubuntu.com/"',
'SUPPORT_URL="http://help.ubuntu.com/"',
'BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"'
]
with mock.patch(
'__builtin__.open', mock.mock_open(read_data="\n".join(data)),
create=True) as m:
m.return_value.__iter__.return_value = data
result = get_osinfo_from_os_release()
self.assertEqual(result['os'], 'ubuntu')
self.assertEqual(result['version'], '14.04')
示例13: test_readline_data
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_readline_data(self):
# Check that readline will return all the lines from the fake file
mock = mock_open(read_data='foo\nbar\nbaz\n')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
line1 = h.readline()
line2 = h.readline()
line3 = h.readline()
self.assertEqual(line1, 'foo\n')
self.assertEqual(line2, 'bar\n')
self.assertEqual(line3, 'baz\n')
# Check that we properly emulate a file that doesn't end in a newline
mock = mock_open(read_data='foo')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
result = h.readline()
self.assertEqual(result, 'foo')
示例14: test_readlines_data
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_readlines_data(self):
# Test that emulating a file that ends in a newline character works
mock = mock_open(read_data='foo\nbar\nbaz\n')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
result = h.readlines()
self.assertEqual(result, ['foo\n', 'bar\n', 'baz\n'])
# Test that files without a final newline will also be correctly
# emulated
mock = mock_open(read_data='foo\nbar\nbaz')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
result = h.readlines()
self.assertEqual(result, ['foo\n', 'bar\n', 'baz'])
示例15: test_interleaved_reads
# 需要导入模块: import mock [as 别名]
# 或者: from mock import mock_open [as 别名]
def test_interleaved_reads(self):
# Test that calling read, readline, and readlines pulls data
# sequentially from the data we preload with
mock = mock_open(read_data='foo\nbar\nbaz\n')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
line1 = h.readline()
rest = h.readlines()
self.assertEqual(line1, 'foo\n')
self.assertEqual(rest, ['bar\n', 'baz\n'])
mock = mock_open(read_data='foo\nbar\nbaz\n')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
line1 = h.readline()
rest = h.read()
self.assertEqual(line1, 'foo\n')
self.assertEqual(rest, 'bar\nbaz\n')