def test__config_is_written_to_the_right_place(self, mock_yaml, mock_path):
dummy_path = '/config/path'
mock_path.return_value = dummy_path
with mock.patch(open_mock_string) as mock_open:
config._create_default_config()
mock_open.assert_called_with(dummy_path, 'w+')
python类mock_open()的实例源码
def test__yaml_file_is_written_with_the_full_configuration(self, mock_yaml):
mock_open = mock.mock_open()
with mock.patch(open_mock_string, mock_open):
config._create_default_config()
mock_yaml.dump.assert_called_with(config._default_config, mock_open.return_value, default_flow_style=False)
def test_prompts_update_needed():
"""Test Config object will suggest update if needed."""
tmp_config_data = json.loads(CONFIG_DATA)
# set an old timestamp
tmp_config_data['last_update_check'] = 0.0
mock_config = mock.mock_open(read_data=json.dumps(tmp_config_data))
with mock.patch('two1.commands.util.config.Config.save', return_value=None):
with mock.patch('two1.commands.util.config.open', mock_config, create=True):
with capture_stderr(
config.Config, 'config_file', check_update=True) as output:
output = output.strip()
assert(len(output) > 0)
assert(output in uxstring.UxString.update_required)
def test_needs_update_legacy_last_update_check():
"""Test for a legacy two1.json with an older last_update_check, and that
it does not throw an error"""
mock_config = mock.mock_open(read_data=CONFIG_DATA)
with mock.patch('two1.commands.util.config.open', mock_config, create=True):
c = config.Config('config_file')
c.set('last_update_check', "", should_save=True)
try:
c.check_update()
except ValueError:
pytest.fail("Error dealing with legacy timestamp")
def test_last_update_check_set():
"""Asert last_update_check is set in a config with none."""
mock_config = mock.mock_open(read_data=CONFIG_DATA)
assert 'last_update_check' not in CONFIG_DATA
with mock.patch('two1.commands.util.config.open', mock_config, create=True):
conf = config.Config('config_file', check_update=True)
# last_update_check should now be set after
# initalizing the config object.
assert hasattr(conf, 'last_update_check')
assert 'last_update_check' in json.loads(
mock_config.return_value.write.call_args[0][0])
def test_needs_old_last_update_check_with_new_version():
"""Test for a last_update_check more than 3600 seconds ago, but version is new
and that it does not suggest an update"""
mock_config = mock.mock_open(read_data=CONFIG_DATA)
with mock.patch('two1.commands.util.config.open', mock_config, create=True):
c = config.Config('config_file', check_update=True)
c.set('last_update_check', 000000.000, should_save=True)
with capture_stdout(config.Config, 'config_file', check_update=True) as output:
assert len(output.strip()) == 0
def test_invalid_config_file():
"""Test that an invalid `two1.json` file cannot be imported."""
mock_config = mock.mock_open(mock=mock.Mock(side_effect=ValueError))
with mock.patch('two1.commands.util.config.open', mock_config, create=True), pytest.raises(exceptions.FileDecodeError): # nopep8
config.Config('config_file')
mock_config.assert_called_with('config_file', mode='r')
def setup_method(self, method):
singletons.settings.use_settings(MockConfig)
mocked_file = mock.mock_open(read_data=self.JSON_DATA)
def mocked_exists(path): return path == self.JSON_PATH
self.open_patch = mock.patch('omnic.web.viewer.open', mocked_file)
self.exists_patch = mock.patch('os.path.exists', mocked_exists)
self.open_patch.start()
self.exists_patch.start()
def test_should_load_data_from_file(self, pickle_mock):
with patch('builtins.open', mock_open()) as file_mock:
load('dir/filename/')
file_mock.assert_called_with('dir/filename/', 'rb')
pickle_mock.load.assert_called_with(file_mock())
def test_should_save_data_to_file_using_highest_protocol(self, pickle_mock):
data = 'data'
with patch('builtins.open', mock_open(read_data=data)) as file_mock:
save('dir/filename/', data)
file_mock.assert_called_with('dir/filename/', 'wb')
pickle_mock.dump.assert_called_with(data, file_mock(), pickle.HIGHEST_PROTOCOL)
def test_should_save_data_to_file_using_default_protocol(self, pickle_mock):
data = 'data'
with patch('builtins.open', mock_open(read_data=data)) as file_mock:
save('dir/filename/', data, pickle.DEFAULT_PROTOCOL)
file_mock.assert_called_with('dir/filename/', 'wb')
pickle_mock.dump.assert_called_with(data, file_mock(), pickle.DEFAULT_PROTOCOL)
def test_get_config(self):
mock_open = mock.mock_open(read_data=self.config)
with mock.patch('fleece.cli.run.run.open', mock_open, create=True):
config = run.get_config('./wat')
self.assertDictEqual(yaml.load(self.config), config)
def test_config_attribute_returns_list_of_given_file(baseline):
"""
Config attribute should return given config file as a list.
"""
config = baseline.split('\n')
data = mock.mock_open(read_data=baseline)
with mock.patch('diffios.config.open', data, create=True) as mock_open:
assert config == diffios.Config(data).config
def test_config_is_grouped_correctly_with_file(baseline, baseline_blocks):
"""
Should return valid config as list of hierarchical blocks,
from a config given in a file.
"""
with mock.patch('diffios.config.os.path.isfile') as mock_isfile:
mock_isfile.return_value = True
config_data = mock.mock_open(read_data=baseline)
with mock.patch(
'diffios.config.open', config_data, create=True) as mock_open:
actual = diffios.Config(
'baseline.conf', ignore_lines=[]).included()
mock_open.assert_called_once_with('baseline.conf')
assert baseline_blocks == actual
def test_ignore_lines_from_file(ignores_file):
"""
Should return the lines in the given ignores file as list of lowercase strings.
"""
config = ['hostname ROUTER']
expected = ignores_file.lower().split('\n')
ignores_data = mock.mock_open(read_data=ignores_file)
with mock.patch('diffios.config.os.path.isfile') as mock_isfile:
mock_isfile.return_value = True
with mock.patch(
'diffios.config.open', ignores_data, create=True) as mock_open:
actual = diffios.Config(
config, ignore_lines='ignores_file').ignore_lines
mock_open.assert_called_once_with('ignores_file')
assert expected == actual
def test_returns_main_paths_if_cra_is_not_running(self):
open_mock = mock_open(
read_data='''{
"main.js": "static/js/main.1234.js",
"main.css": "static/css/main.1234.css"
}'''
)
with patch('builtins.open', open_mock):
self.assertEqual(asset_manifest.generate_manifest(False, server_url, '.'), {
'main_js': 'js/main.1234.js',
'main_css': 'css/main.1234.css',
})
def test_load_secret():
with patch('ssb.util.open', mock_open(read_data=CONFIG_FILE), create=True):
secret = load_ssb_secret()
priv_key = b'\xfd\xba\x83\x04\x8f\xef\x18\xb0\xf9\xab-\xc6\xc4\xcb \x1cX\x18"\xba\xd8\xd3\xc2_O5\x1a\t\x84\xfa\xc7A'
assert secret['id'] == '@rsYpBIcXsxjQAf0JNes+MHqT2DL+EfopWKAp4rGeEPQ=.ed25519'
assert bytes(secret['keypair']) == priv_key
assert bytes(secret['keypair'].verify_key) == b64decode('rsYpBIcXsxjQAf0JNes+MHqT2DL+EfopWKAp4rGeEPQ=')
def test_load_exception():
with pytest.raises(ConfigException):
with patch('ssb.util.open', mock_open(read_data=CONFIG_FILE_INVALID), create=True):
load_ssb_secret()
def test_client_script_put(self):
"""
Verify use cases for the client_script put requests.
"""
sys.argv = ['']
read_data = six.b('1234567890')
with mock.patch('requests.Session.put') as _put, \
mock.patch('os.path.realpath') as _realpath, \
mock.patch(
'argparse.FileType.__call__',
mock.mock_open(read_data=read_data),
create=True) as _filetype:
_realpath.return_value = self.conf
for cmd in (
['cluster', 'create'],
['cluster', 'create', '-n', 'default'],
['cluster', 'create', '-t', 'kubernetes'],
['cluster', 'create', '-t', 'kubernetes', '-n', 'default'],
['cluster', 'deploy', 'start'],
['cluster', 'restart', 'start'],
['cluster', 'upgrade', 'start'],
['container_manager', 'create'],
['container_manager', 'create', '-o', '{}'],
['container_manager', 'create'],
['host', 'create', '-c', 'honeynut', '1.2.3.4'],
['host', 'join', '1.2.3.4'],
['network', 'create', '-n', 'test']):
mock_return = requests.Response()
mock_return._content = six.b('{}')
mock_return.status_code = 201
mock_return.request = mock.MagicMock(path_url='/fake/path')
_put.return_value = mock_return
sys.argv[1:] = cmd + ['test']
if cmd[1] == 'deploy':
sys.argv.append('1') # arbitrary version
print(sys.argv)
client_script.main()
self.assertEquals(1, _put.call_count)
_put.reset_mock()