Here are the examples of the python api unittest.mock.mock_open taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
590 Examples
3
Source : test_utils.py
with Apache License 2.0
from airflowdocker
with Apache License 2.0
from airflowdocker
def test_empty_file_exists(self):
with patch("os.path.exists", return_value=True), patch(
"builtins.open", mock_open(read_data="{}")
):
result = get_config()
assert result == {"airflow-docker": {}}
def test_file_exists_with_data(self):
3
Source : test_utils.py
with Apache License 2.0
from airflowdocker
with Apache License 2.0
from airflowdocker
def test_file_exists_with_data(self):
with patch("os.path.exists", return_value=True), patch(
"builtins.open", mock_open(read_data='{"foo": 4}')
):
result = get_config()
assert result == {"airflow-docker": {}, "foo": 4}
def test_file_exists_with_airflow_docker_section(self):
3
Source : test_utils.py
with Apache License 2.0
from airflowdocker
with Apache License 2.0
from airflowdocker
def test_file_exists_with_airflow_docker_section(self):
with patch("os.path.exists", return_value=True), patch(
"builtins.open", mock_open(read_data='{"airflow-docker": {"anything": 4}}')
):
result = get_config()
assert result == {"airflow-docker": {"anything": 4}}
def test_explicit_path(self):
3
Source : hostsmanager_test.py
with MIT License
from anned20
with MIT License
from anned20
def test_has_begoneads():
with patch('builtins.open', mock_open(read_data=without_begoneads)) as mock_file:
hosts_manager = HostsManager('/etc/hosts')
mock_file.assert_called_with('/etc/hosts', 'r', encoding='utf-8')
assert hosts_manager.has_begoneads() is None
with patch('builtins.open', mock_open(read_data=with_begoneads)) as mock_file:
hosts_manager = HostsManager('/etc/hosts')
mock_file.assert_called_with('/etc/hosts', 'r', encoding='utf-8')
assert hosts_manager.has_begoneads()
def test_apply_hosts():
3
Source : hostsmanager_test.py
with MIT License
from anned20
with MIT License
from anned20
def test_apply_hosts():
with patch('builtins.open', mock_open(read_data=without_begoneads)) as mock_file:
hosts_manager = HostsManager('/etc/hosts')
mock_file.assert_called_with('/etc/hosts', 'r', encoding='utf-8')
assert hosts_manager.has_begoneads() is None
hosts_manager.apply_hosts('0.0.0.0 some.test')
assert hosts_manager.has_begoneads()
def test_remove_begoneads():
3
Source : hostsmanager_test.py
with MIT License
from anned20
with MIT License
from anned20
def test_remove_begoneads():
with patch('builtins.open', mock_open(read_data=with_begoneads)) as mock_file:
hosts_manager = HostsManager('/etc/hosts')
mock_file.assert_called_with('/etc/hosts', 'r', encoding='utf-8')
assert hosts_manager.has_begoneads()
hosts_manager.remove_begoneads()
assert hosts_manager.has_begoneads() is None
3
Source : test_resources.py
with BSD 3-Clause "New" or "Revised" License
from apriha
with BSD 3-Clause "New" or "Revised" License
from apriha
def test_download_example_datasets(self):
def f():
with patch("urllib.request.urlopen", mock_open(read_data=b"")):
return self.resource.download_example_datasets()
paths = (
self.resource.download_example_datasets() if self.downloads_enabled else f()
)
for path in paths:
if not path or not os.path.exists(path):
warnings.warn("Example dataset(s) not currently available")
return
def test_get_paths_reference_sequences_invalid_assembly(self):
3
Source : test_resources.py
with BSD 3-Clause "New" or "Revised" License
from apriha
with BSD 3-Clause "New" or "Revised" License
from apriha
def run_reference_sequences_test(self, f, assembly="GRCh37"):
if self.downloads_enabled:
f()
else:
s = f">MT dna:chromosome chromosome:{assembly}:MT:1:16569:1 REF\n"
for i in range(276):
s += "A" * 60
s += "\n"
s += "A" * 9
s += "\n"
with patch(
"urllib.request.urlopen", mock_open(read_data=gzip.compress(s.encode()))
):
f()
def run_create_reference_sequences_test(self, assembly_expect, url_expect):
3
Source : test_main.py
with MIT License
from arthurk
with MIT License
from arthurk
def test_get_symbols(symbols_fixture):
"""
Should return a json of all available markets
"""
# content of "symbols.json"
json_data = '["btcusd", "ltcbtc", "ethusd"]'
m = mock_open(read_data=json_data)
with patch('bitfinex.main.open', m):
symbols = get_symbols()
# should read symbols.json file and return json
m.assert_called_once_with('symbols.json')
assert symbols == symbols_fixture
3
Source : test_manager.py
with GNU General Public License v3.0
from atlassistant
with GNU General Public License v3.0
from atlassistant
def test_it_should_not_allow_installation_of_incompatible_skills(self):
s = SkillsManager('skills')
p = os.path.abspath('skills')
incompatible_version_spec = f'{__title__}[snips]~={int(__version__[0]) - 1}.0'
with patch('subprocess.check_output') as sub_mock:
with patch('os.path.isfile', return_value=True):
with patch('builtins.open', mock_open(read_data=f'{incompatible_version_spec}\n\nrequests~=2.22')):
with patch('pytlas.supporting.manager.rmtree') as rm_mock:
succeeded, failed = s.install('incompatible/skill')
expect(succeeded).to.be.empty
expect(failed).to.equal(['incompatible/skill'])
rm_mock.assert_called_once_with(os.path.join(p, 'incompatible__skill'), ignore_errors=True)
def test_it_should_allow_installation_of_compatible_skills(self):
3
Source : test_manager.py
with GNU General Public License v3.0
from atlassistant
with GNU General Public License v3.0
from atlassistant
def test_it_should_allow_installation_of_compatible_skills(self):
s = SkillsManager('skills')
p = os.path.abspath('skills')
compatible_version_spec = f'{__title__}[snips]~={__version__[0]}.0'
with patch('subprocess.check_output') as sub_mock:
with patch('os.path.isfile', return_value=True):
with patch('builtins.open', mock_open(read_data=f'{compatible_version_spec}\n\nrequests~=2.22')):
succeeded, failed = s.install('incompatible/skill')
expect(failed).to.be.empty
expect(succeeded).to.equal(['incompatible/skill'])
def test_it_should_complain_when_install_failed_and_cleanup_skill_folder(self):
3
Source : test_ioutils.py
with GNU General Public License v3.0
from atlassistant
with GNU General Public License v3.0
from atlassistant
def test_it_should_read_the_file_correctly(self):
with patch('builtins.open', mock_open(read_data='some content')) as mopen:
expect(read_file('somepath')).to.equal('some content')
mopen.assert_called_once_with('somepath', encoding='utf-8')
def test_it_should_read_the_file_relative_to_another_one(self):
3
Source : test_ioutils.py
with GNU General Public License v3.0
from atlassistant
with GNU General Public License v3.0
from atlassistant
def test_it_should_read_the_file_relative_to_another_one(self):
with patch('builtins.open', mock_open(read_data='some content')) as mopen:
with patch('os.path.isdir', return_value=False):
expect(read_file(
'somepath', relative_to='/home/julien/pytlas/a.file')).to.equal('some content')
mopen.assert_called_once_with(
'/home/julien/pytlas%ssomepath' % os.path.sep, encoding='utf-8')
def test_it_should_read_the_file_relative_to_a_folder(self):
3
Source : test_ioutils.py
with GNU General Public License v3.0
from atlassistant
with GNU General Public License v3.0
from atlassistant
def test_it_should_read_the_file_relative_to_a_folder(self):
with patch('builtins.open', mock_open(read_data='some content')) as mopen:
with patch('os.path.isdir', return_value=True):
expect(read_file(
'somepath', relative_to='/home/julien/pytlas/folder')).to.equal('some content')
mopen.assert_called_once_with(
'/home/julien/pytlas/folder%ssomepath' % os.path.sep, encoding='utf-8')
3
Source : test_type_configuration.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_get_type_configuration_with_not_exist_file():
with patch("builtins.open", mock_open()) as f:
f.side_effect = FileNotFoundError()
try:
TypeConfiguration.get_type_configuration()
except FileNotFoundError:
pass
@patch("builtins.open", mock_open(read_data=TYPE_CONFIGURATION_TEST_SETTING))
3
Source : test_type_configuration.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_get_hook_configuration_with_not_exist_file():
with patch("builtins.open", mock_open()) as f:
f.side_effect = FileNotFoundError()
try:
TypeConfiguration.get_hook_configuration()
except FileNotFoundError:
pass
3
Source : test_type_schema_loader.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_load_type_schema_from_file(loader):
patch_file = patch("builtins.open", mock_open(read_data=TEST_TARGET_SCHEMA_JSON))
patch_path_is_file = patch(
"rpdk.core.type_schema_loader.os.path.isfile", return_value=True
)
patch_load_file = patch.object(
loader, "load_type_schema_from_file", wraps=loader.load_type_schema_from_file
)
with patch_file as mock_file, patch_path_is_file as mock_path_is_file, patch_load_file as mock_load_file:
type_schema = loader.load_type_schema(TEST_TARGET_SCHEMA_FILE_PATH)
assert_dict_equals(TEST_TARGET_SCHEMA, type_schema)
mock_path_is_file.assert_called_with(TEST_TARGET_SCHEMA_FILE_PATH)
mock_load_file.assert_called_with(TEST_TARGET_SCHEMA_FILE_PATH, None)
mock_file.assert_called_with(TEST_TARGET_SCHEMA_FILE_PATH, "r")
def test_load_type_schema_from_file_file_not_found(loader):
3
Source : test_type_schema_loader.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_load_type_schema_from_file_uri(loader):
patch_file = patch("builtins.open", mock_open(read_data=TEST_TARGET_SCHEMA_JSON))
patch_load_from_uri = patch.object(
loader, "load_type_schema_from_uri", wraps=loader.load_type_schema_from_uri
)
patch_load_file = patch.object(
loader, "load_type_schema_from_file", wraps=loader.load_type_schema_from_file
)
with patch_file as mock_file, patch_load_from_uri as mock_load_from_uri, patch_load_file as mock_load_file:
type_schema = loader.load_type_schema(TEST_TARGET_SCHEMA_FILE_URI)
assert_dict_equals(TEST_TARGET_SCHEMA, type_schema)
mock_load_from_uri.assert_called_with(TEST_TARGET_SCHEMA_FILE_URI, None)
mock_load_file.assert_called_with(TEST_TARGET_SCHEMA_FILE_PATH, None)
mock_file.assert_called_with(TEST_TARGET_SCHEMA_FILE_PATH, "r")
def test_load_type_schema_from_file_uri_file_not_found(loader):
3
Source : test_BuildCommand.py
with Apache License 2.0
from aws-greengrass
with Apache License 2.0
from aws-greengrass
def test_create_recipe_file_json_valid(self):
# Tests if a new recipe file is created with updated values - json
build = BuildCommand({})
pc = self.mock_get_proj_config.return_value
file_name = Path(pc["gg_build_recipes_dir"]).joinpath(pc["component_recipe_file"].name).resolve()
mock_json_dump = self.mocker.patch("json.dumps")
mock_yaml_dump = self.mocker.patch("yaml.dump")
with patch("builtins.open", mock_open()) as mock_file:
build.create_build_recipe_file()
mock_file.assert_any_call(file_name, "w")
mock_json_dump.call_count == 1
assert not mock_yaml_dump.called
def test_create_recipe_file_yaml_valid(self):
3
Source : test_BuildCommand.py
with Apache License 2.0
from aws-greengrass
with Apache License 2.0
from aws-greengrass
def test_create_recipe_file_yaml_valid(self):
# Tests if a new recipe file is created with updated values - yaml
# Tests if a new recipe file is created with updated values - json
build = BuildCommand({})
pc = self.mock_get_proj_config.return_value
build.project_config["component_recipe_file"] = Path("some-yaml.yaml").resolve()
file_name = (
Path(pc["gg_build_recipes_dir"]).joinpath(build.project_config["component_recipe_file"].resolve().name).resolve()
)
mock_json_dump = self.mocker.patch("json.dumps")
mock_yaml_dump = self.mocker.patch("yaml.dump")
with patch("builtins.open", mock_open()) as mock_file:
build.create_build_recipe_file()
mock_file.assert_called_once_with(file_name, "w")
mock_json_dump.call_count == 1
assert mock_yaml_dump.called
def test_create_recipe_file_json_invalid(self):
3
Source : test_project_utils.py
with Apache License 2.0
from aws-greengrass
with Apache License 2.0
from aws-greengrass
def test_get_supported_component_builds_exists(mocker):
mock_file_path = Path(".").resolve()
mock_file_not_exists = mocker.patch("gdk.common.utils.get_static_file_path", return_value=mock_file_path)
mock_json_loads = mocker.patch("json.loads")
with patch("builtins.open", mock_open(read_data="{}")) as mock_file:
project_utils.get_supported_component_builds()
mock_file.assert_called_once_with(mock_file_path, "r")
assert mock_file_not_exists.called
assert mock_json_loads.called
3
Source : test_PublishCommand.py
with Apache License 2.0
from aws-greengrass
with Apache License 2.0
from aws-greengrass
def test_create_gg_component(self):
publish = PublishCommand({})
mock_client = self.mocker.patch("boto3.client", return_value=None)
publish.service_clients = {"greengrass_client": mock_client}
mock_create_component = self.mocker.patch("boto3.client.create_component_version", return_value=None)
publish.project_config["publish_recipe_file"] = Path("some-recipe.yaml")
component_name = "component_name"
component_version = "1.0.0"
with mock.patch("builtins.open", mock.mock_open()) as mock_file:
publish.create_gg_component(component_name, component_version)
mock_file.assert_any_call(publish.project_config["publish_recipe_file"])
assert mock_create_component.call_count == 1
def test_create_gg_component_exception(self):
3
Source : test_PublishCommand.py
with Apache License 2.0
from aws-greengrass
with Apache License 2.0
from aws-greengrass
def test_create_gg_component_exception(self):
publish = PublishCommand({})
mock_client = self.mocker.patch("boto3.client", return_value=None)
publish.service_clients = {"greengrass_client": mock_client}
mock_create_component = self.mocker.patch(
"boto3.client.create_component_version", return_value=None, side_effect=HTTPError("error")
)
publish.project_config["publish_recipe_file"] = Path("some-recipe.yaml")
component_name = "component_name"
component_version = "1.0.0"
with mock.patch("builtins.open", mock.mock_open()) as mock_file:
with pytest.raises(Exception) as e:
publish.create_gg_component(component_name, component_version)
assert "Creating private version '1.0.0' of the component 'component_name' failed." in e.value.args[0]
mock_file.assert_any_call(publish.project_config["publish_recipe_file"])
assert mock_create_component.call_count == 1
def test_create_bucket_exists(self):
3
Source : test_model_actions.py
with Apache License 2.0
from aws-greengrass
with Apache License 2.0
from aws-greengrass
def test_get_validated_model_file_exists(mocker):
file_path = Path("path/to/open")
mock_get_static_file_path = mocker.patch("gdk.common.utils.get_static_file_path", return_value=file_path)
mock_is_valid_model = mocker.patch("gdk.common.model_actions.is_valid_model", return_value=True)
with patch("builtins.open", mock_open(read_data="{}")) as mock_file:
model_actions.get_validated_model()
assert open(file_path).read() == "{}"
mock_file.assert_called_with(file_path)
assert not mock_is_valid_model.called
assert mock_get_static_file_path.call_count == 1
def test_get_validated_model_with_valid_model(mocker):
3
Source : test_codecs.py
with Apache License 2.0
from bouffalolab
with Apache License 2.0
from bouffalolab
def test_file_closes_if_lookup_error_raised(self):
mock_open = mock.mock_open()
with mock.patch('builtins.open', mock_open) as file:
with self.assertRaises(LookupError):
codecs.open(support.TESTFN, 'wt', 'invalid-encoding')
file().close.assert_called()
class StreamReaderTest(unittest.TestCase):
3
Source : test_chemicalReactionNetwork.py
with BSD 3-Clause "New" or "Revised" License
from BuildACell
with BSD 3-Clause "New" or "Revised" License
from BuildACell
def test_write_sbml_file(self):
s1, s2 = Species("S1"), Species("S2")
rx1 = Reaction.from_massaction(inputs=[s1], outputs=[s2], k_forward=0.1)
crn = ChemicalReactionNetwork(species = [s1, s2], reactions = [rx1])
model_id = 'test_model'
document, _ = crn.generate_sbml_model(model_id=model_id)
sbml_string = libsbml.writeSBMLToString(document)
file_name = 'test_sbml.xml'
with patch("builtins.open", new=mock_open()) as _file:
crn.write_sbml_file(file_name, model_id=model_id)
_file.assert_called_once_with(file_name, 'w')
_file().write.assert_called_once_with(sbml_string)
3
Source : test_utils.py
with Apache License 2.0
from capitalone
with Apache License 2.0
from capitalone
def test_parse_reqs(mock_pathlib):
"""Test creating a configuration from requirements."""
mock_pathlib.return_value.is_file.return_value = True
with patch("edgetest.utils.open", mock_open(read_data=REQS)):
cfg = gen_requirements_config("filename")
assert cfg == {
"envs": [
{"name": "mydep1", "upgrade": "mydep1"},
{"name": "mydep2", "upgrade": "mydep2"},
{"name": "all-requirements", "upgrade": "mydep1\nmydep2"},
]
}
validator = EdgetestValidator(schema=BASE_SCHEMA)
assert validator.validate(cfg)
def test_parse_cfg(tmpdir):
3
Source : testmock.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_reuse_issue_21750(self):
mocked_open = mock.mock_open(read_data='data')
f1 = mocked_open('a-name')
f1_data = f1.read()
f2 = mocked_open('another-name')
f2_data = f2.read()
self.assertEqual(f1_data, f2_data)
def test_mock_open_dunder_iter_issue(self):
3
Source : testmock.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_dunder_iter_issue(self):
# Test dunder_iter method generates the expected result and
# consumes the iterator.
mocked_open = mock.mock_open(read_data='Remarkable\nNorwegian Blue')
f1 = mocked_open('a-name')
lines = [line for line in f1]
self.assertEqual(lines[0], 'Remarkable\n')
self.assertEqual(lines[1], 'Norwegian Blue')
self.assertEqual(list(f1), [])
def test_mock_open_write(self):
3
Source : testmock.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_alter_readline(self):
mopen = mock.mock_open(read_data='foo\nbarn')
mopen.return_value.readline.side_effect = lambda *args:'abc'
first = mopen().readline()
second = mopen().readline()
self.assertEqual('abc', first)
self.assertEqual('abc', second)
def test_mock_open_after_eof(self):
3
Source : testmock.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_after_eof(self):
# read, readline and readlines should work after end of file.
_open = mock.mock_open(read_data='foo')
h = _open('bar')
h.read()
self.assertEqual('', h.read())
self.assertEqual('', h.read())
self.assertEqual('', h.readline())
self.assertEqual('', h.readline())
self.assertEqual([], h.readlines())
self.assertEqual([], h.readlines())
def test_mock_parents(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open(self):
mock = mock_open()
with patch('%s.open' % __name__, mock, create=True) as patched:
self.assertIs(patched, mock)
open('foo')
mock.assert_called_once_with('foo')
def test_mock_open_context_manager(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_context_manager(self):
mock = mock_open()
handle = mock.return_value
with patch('%s.open' % __name__, mock, create=True):
with open('foo') as f:
f.read()
expected_calls = [call('foo'), call().__enter__(), call().read(),
call().__exit__(None, None, None)]
self.assertEqual(mock.mock_calls, expected_calls)
self.assertIs(f, handle)
def test_mock_open_context_manager_multiple_times(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_context_manager_multiple_times(self):
mock = mock_open()
with patch('%s.open' % __name__, mock, create=True):
with open('foo') as f:
f.read()
with open('bar') as f:
f.read()
expected_calls = [
call('foo'), call().__enter__(), call().read(),
call().__exit__(None, None, None),
call('bar'), call().__enter__(), call().read(),
call().__exit__(None, None, None)]
self.assertEqual(mock.mock_calls, expected_calls)
def test_explicit_mock(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_explicit_mock(self):
mock = MagicMock()
mock_open(mock)
with patch('%s.open' % __name__, mock, create=True) as patched:
self.assertIs(patched, mock)
open('foo')
mock.assert_called_once_with('foo')
def test_read_data(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_read_data(self):
mock = mock_open(read_data='foo')
with patch('%s.open' % __name__, mock, create=True):
h = open('bar')
result = h.read()
self.assertEqual(result, 'foo')
def test_readline_data(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_dunder_iter_data(self):
# Check that dunder_iter 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')
lines = [l for l in h]
self.assertEqual(lines[0], 'foo\n')
self.assertEqual(lines[1], 'bar\n')
self.assertEqual(lines[2], 'baz\n')
self.assertEqual(h.readline(), '')
def test_readlines_data(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
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'])
def test_read_bytes(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_read_bytes(self):
mock = mock_open(read_data=b'\xc6')
with patch('%s.open' % __name__, mock, create=True):
with open('abc', 'rb') as f:
result = f.read()
self.assertEqual(result, b'\xc6')
def test_readline_bytes(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_readline_bytes(self):
m = mock_open(read_data=b'abc\ndef\nghi\n')
with patch('%s.open' % __name__, m, create=True):
with open('abc', 'rb') as f:
line1 = f.readline()
line2 = f.readline()
line3 = f.readline()
self.assertEqual(line1, b'abc\n')
self.assertEqual(line2, b'def\n')
self.assertEqual(line3, b'ghi\n')
def test_readlines_bytes(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_readlines_bytes(self):
m = mock_open(read_data=b'abc\ndef\nghi\n')
with patch('%s.open' % __name__, m, create=True):
with open('abc', 'rb') as f:
result = f.readlines()
self.assertEqual(result, [b'abc\n', b'def\n', b'ghi\n'])
def test_mock_open_read_with_argument(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_mock_open_read_with_argument(self):
# At one point calling read with an argument was broken
# for mocks returned by mock_open
some_data = 'foo\nbar\nbaz'
mock = mock_open(read_data=some_data)
self.assertEqual(mock().read(10), some_data)
def test_interleaved_reads(self):
3
Source : testwith.py
with MIT License
from CedricGuillemet
with MIT License
from CedricGuillemet
def test_overriding_return_values(self):
mock = mock_open(read_data='foo')
handle = mock()
handle.read.return_value = 'bar'
handle.readline.return_value = 'bar'
handle.readlines.return_value = ['bar']
self.assertEqual(handle.read(), 'bar')
self.assertEqual(handle.readline(), 'bar')
self.assertEqual(handle.readlines(), ['bar'])
# call repeatedly to check that a StopIteration is not propagated
self.assertEqual(handle.readline(), 'bar')
self.assertEqual(handle.readline(), 'bar')
if __name__ == '__main__':
3
Source : cbn_cli_test.py
with Apache License 2.0
from chronicle
with Apache License 2.0
from chronicle
def test_download_parser_config_id(self):
cmd_line_args = 'download -i={}'.format(self.config_id)
url = '{}/tools/cbnParsers/{}'.format(cbn_cli.CHRONICLE_API_V1_URL,
self.config_id)
self.mock_make_request.return_value = self.parser
args = cbn_cli.arg_parser().parse_args(cmd_line_args.split())
with mock.patch('builtins.open', mock.mock_open()) as mock_file:
cbn_cli.download_parser(args)
mock_file.assert_called_once_with(mock.ANY, 'a')
self.mock_make_request.assert_called_once_with(args, url)
def test_download_parser_log_type(self):
3
Source : cbn_cli_test.py
with Apache License 2.0
from chronicle
with Apache License 2.0
from chronicle
def test_download_parser_log_type(self):
cmd_line_args = 'download -l={}'.format(self.log_type)
url = '{}/tools/cbnParsers'.format(cbn_cli.CHRONICLE_API_V1_URL)
self.mock_make_request.return_value = self.parsers
args = cbn_cli.arg_parser().parse_args(cmd_line_args.split())
with mock.patch('builtins.open', mock.mock_open()) as mock_file:
cbn_cli.download_parser(args)
mock_file.assert_called_once_with(mock.ANY, 'a')
self.mock_make_request.assert_called_once_with(args, url)
def test_parser_errors(self):
3
Source : test_get_token.py
with BSD 3-Clause "New" or "Revised" License
from Cloud-CV
with BSD 3-Clause "New" or "Revised" License
from Cloud-CV
def test_get_token(self):
expected_token = "test"
expected_json = """{"token": "%s"}""" % expected_token
expected = "Current token is {}".format(expected_token)
mock_file = mock_open(read_data=expected_json)
with patch("evalai.get_token.open", mock_file):
runner = CliRunner()
result = runner.invoke(get_token)
response = result.output.rstrip()
assert response == expected
@patch("evalai.get_token.os.path.exists", return_value=False)
3
Source : test_util.py
with MIT License
from cn-uofbasel
with MIT License
from cn-uofbasel
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():
3
Source : test_system.py
with MIT License
from codrsquad
with MIT License
from codrsquad
def test_docker_detection(monkeypatch):
monkeypatch.setenv("container", "foo")
info = SystemInfo()
assert info.is_running_in_docker is True
monkeypatch.setenv("container", "")
with patch("runez.system.open", side_effect=OSError):
info = SystemInfo()
assert info.is_running_in_docker is False
if sys.version_info[:2] >= (3, 7): # unittest.mock doesn't work correctly before 3.7
with patch("runez.system.open", mock_open(read_data="1: /docker/foo")):
info = SystemInfo()
assert info.is_running_in_docker is True
def test_find_parent_folder(monkeypatch):
3
Source : test_collator.py
with Apache License 2.0
from ComplianceAsCode
with Apache License 2.0
from ComplianceAsCode
def test_write_functionality(self):
"""Ensures that write is called appropriately."""
m = mock_open()
with patch('builtins.open', m):
collator = Collator(*self.args)
collator.write('raw/foo/foo.json', self.commits)
handle = m()
self.assertEqual(handle.write.call_count, 3)
self.assertIn(call('./20191106_foo.json', 'w+'), m.mock_calls)
self.assertIn(call('./20191105_foo.json', 'w+'), m.mock_calls)
self.assertIn(call('./20191101_foo.json', 'w+'), m.mock_calls)
@patch('harvest.collator.git.Repo.clone_from')
3
Source : test_nexus.py
with GNU General Public License v3.0
from containerbuildsystem
with GNU General Public License v3.0
from containerbuildsystem
def test_upload_asset_only_component(mock_post, use_hoster):
mock_open = mock.mock_open(read_data=b"some tgz file")
mock_post.return_value.ok = True
with mock.patch("cachito.workers.nexus.open", mock_open):
nexus.upload_asset_only_component(
"cachito-js-hosted", "npm", "/path/to/rxjs-6.5.5.tgz", use_hoster
)
expected_asset = {"npm.asset": ("rxjs-6.5.5.tgz", b"some tgz file")}
assert mock_post.call_args[1]["files"] == expected_asset
assert mock_post.call_args[1]["params"] == {"repository": "cachito-js-hosted"}
assert mock_post.call_args[1]["auth"].username == "cachito"
assert mock_post.call_args[1]["auth"].password == "cachito"
@mock.patch.object(nexus.nexus_requests_session, "post")
See More Examples