Here are the examples of the python api unittest.mock.call taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3011 Examples
5
Source : test_db.py
with MIT License
from Kostiantyn-Salnykov
with MIT License
from Kostiantyn-Salnykov
def test_description_changed(self, patch_logging, event):
event.new_description.has_writable_server.return_value = False
event.new_description.has_readable_server.return_value = False
self.logger.description_changed(event=event)
patch_logging.assert_has_calls(
calls=[
unittest.mock.call(f"Topology description updated for topology id {event.topology_id}"),
unittest.mock.call(
f"Topology {event.topology_id} changed type from {event.previous_description.topology_type_name} "
f"to {event.new_description.topology_type_name}"
),
unittest.mock.call("No writable servers available."),
unittest.mock.call("No readable servers available."),
]
)
def test_description_changed_not_changed(self, patch_logging, event):
5
Source : test_models.py
with MIT License
from Kostiantyn-Salnykov
with MIT License
from Kostiantyn-Salnykov
def test_properties(self, faker, repository, patcher):
logger = patcher.patch_obj(target="fastapi_mongodb.simple_logger")
oid = bson.ObjectId()
active_record = fastapi_mongodb.models.BaseActiveRecord(document=faker.pydict(), repository=repository)
self._check_empty_active_record(active_record=active_record)
logger.warning.assert_has_calls(
calls=[
unittest.mock.call(msg=self.WARNING_MSG),
unittest.mock.call(msg=self.WARNING_MSG),
unittest.mock.call(msg=self.WARNING_MSG),
]
)
active_record._document["_id"] = oid
self._check_filled_active_record(active_record=active_record, oid=oid)
def test_get_collection(self, repository):
5
Source : test_models.py
with MIT License
from Kostiantyn-Salnykov
with MIT License
from Kostiantyn-Salnykov
async def test_read_empty(self, faker, repository, mongodb_session, patcher):
logger = patcher.patch_obj(target="fastapi_mongodb.simple_logger")
fake_oid = bson.ObjectId()
empty_active_record = await fastapi_mongodb.models.BaseActiveRecord.read(
query={"_id": fake_oid}, repository=repository, session=mongodb_session
)
self._check_empty_active_record(active_record=empty_active_record)
logger.warning.assert_has_calls(
calls=[
unittest.mock.call(msg=self.WARNING_MSG),
unittest.mock.call(msg=self.WARNING_MSG),
unittest.mock.call(msg=self.WARNING_MSG),
]
)
async def test_read_filled(self, faker, repository, mongodb_session):
5
Source : test_models.py
with MIT License
from Kostiantyn-Salnykov
with MIT License
from Kostiantyn-Salnykov
async def test_reload_refresh_empty(self, faker, repository, mongodb_session, patcher):
logger = patcher.patch_obj(target="fastapi_mongodb.simple_logger")
empty_active_record = fastapi_mongodb.models.BaseActiveRecord(document={}, repository=repository)
self._check_empty_active_record(active_record=empty_active_record)
assert logger.warning.call_count == 3 # 3 logs from _check method
logger.warning.assert_has_calls(
calls=[
unittest.mock.call(msg=self.WARNING_MSG),
unittest.mock.call(msg=self.WARNING_MSG),
unittest.mock.call(msg=self.WARNING_MSG),
]
)
new_empty_active_record = await empty_active_record.reload(session=mongodb_session)
self._check_empty_active_record(active_record=new_empty_active_record)
assert logger.warning.call_count == 7 # 3 earlier + 1 from reload and another 3 from _check method
3
Source : test_install.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_setup_admin_again(self, mock_get_pod):
mock_pod = Mock()
mock_pod.execute.side_effect = [
("an-admin.card", None) # composer card list admin
]
mock_get_pod.side_effect = [mock_pod]
setup_admin(self.OPTS, verbose=True)
mock_get_pod.assert_called_once_with(
"peer-namespace", "hlc", "hl-composer", verbose=True
)
mock_pod.execute.assert_has_calls(
[call("composer card list --card PeerAdmin@hlfv1")]
)
class TestInstallNetwork:
3
Source : test_crypto.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_register_id(self, mock_check_id, mock_get_pod, mock_sleep):
mock_executor = Mock()
mock_check_id.side_effect = [False]
mock_get_pod.side_effect = [mock_executor]
mock_executor.execute.side_effect = [("Register", None)] # Register identities
register_id("a-namespace", "a-ca", "an-ord", "a-password", "orderer")
mock_get_pod.assert_called_once_with(
namespace="a-namespace", release="a-ca", app="hlf-ca", verbose=False
)
mock_executor.execute.assert_has_calls(
[
call(
"fabric-ca-client register --id.name an-ord --id.secret a-password --id.type orderer"
)
]
)
mock_sleep.assert_not_called()
@patch("nephos.fabric.crypto.sleep")
3
Source : test_crypto.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_setup_nodes(self, mock_setup_id):
setup_nodes(self.OPTS, "peer")
mock_setup_id.assert_has_calls(
[
call(self.OPTS, "peer_MSP", "peer0", "peer", verbose=False),
call(self.OPTS, "peer_MSP", "peer1", "peer", verbose=False),
]
)
@patch("nephos.fabric.crypto.setup_id")
3
Source : test_crypto.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_setup_nodes_ord(self, mock_setup_id):
setup_nodes(self.OPTS, "orderer", verbose=True)
mock_setup_id.assert_has_calls(
[call(self.OPTS, "ord_MSP", "ord0", "orderer", verbose=True)]
)
class TestGenesisBlock:
3
Source : test_crypto.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_again(
self, mock_chdir, mock_execute, mock_exists, mock_print, mock_secret_from_file
):
mock_exists.side_effect = [True, True]
genesis_block(self.OPTS, True)
mock_chdir.assert_has_calls([call("./config"), call(PWD)])
mock_exists.assert_called_once_with("./crypto/genesis.block")
mock_execute.assert_not_called()
mock_print.assert_called_once_with("./crypto/genesis.block already exists")
mock_secret_from_file.assert_called_once_with(
secret="a-genesis-secret",
namespace="ord-ns",
key="genesis.block",
filename="./crypto/genesis.block",
verbose=True,
)
class TestChannelTx:
3
Source : test_crypto.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_again(
self, mock_chdir, mock_execute, mock_exists, mock_print, mock_secret_from_file
):
mock_exists.side_effect = [True, True]
channel_tx(self.OPTS, True)
mock_chdir.assert_has_calls([call("./config"), call(PWD)])
mock_exists.assert_called_once_with("./crypto/a-channel.tx")
mock_execute.assert_not_called()
mock_print.assert_called_once_with("./crypto/a-channel.tx already exists")
mock_secret_from_file.assert_called_once_with(
secret="a-channel-secret",
namespace="peer-ns",
key="a-channel.tx",
filename="./crypto/a-channel.tx",
verbose=True,
)
3
Source : test_peer.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_get_channel_block_again(self):
mock_pod_ex = Mock()
mock_pod_ex.execute.side_effect = [
("/var/hyperledger/a-channel.block", None) # Get channel file
]
result = get_channel_block(
mock_pod_ex, "ord42", "ord-namespace", "a-channel", "some-suffix"
)
mock_pod_ex.execute.assert_has_calls(
[call("ls /var/hyperledger/a-channel.block")]
)
assert result is True
def test_get_channel_block_error(self):
3
Source : test_k8s.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_helm_check(self, mock_execute, mock_print, mock_sleep):
mock_execute.side_effect = [
("Pending", None), # Get states
("Running", None),
]
pod_check("a-namespace", "an-identifier", sleep_interval=15)
assert mock_execute.call_count == 2
mock_print.assert_has_calls(
[
call("Ensuring that all pods are running "),
call(".", end="", flush=True),
call("All pods are running"),
]
)
mock_sleep.assert_called_once_with(15)
@patch("nephos.helpers.k8s.sleep")
3
Source : test_k8s.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_pod_check_podnum(self, mock_execute, mock_print, mock_sleep):
mock_execute.side_effect = [
("Pending Running", None), # Get states
("Running Running", None),
]
pod_check("a-namespace", "an_identifier", pod_num=2)
assert mock_execute.call_count == 2
mock_print.assert_has_calls(
[
call("Ensuring that all pods are running "),
call(".", end="", flush=True),
call("All pods are running"),
]
)
mock_sleep.assert_called_once_with(10)
class TestCmCreate:
3
Source : test_misc.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_execute_verbose(self, mock_print, mock_check_output):
# Add some side effects
mock_check_output.side_effect = ["output".encode("ascii")]
execute("ls", verbose=True)
# First check_output
mock_check_output.assert_called_once()
mock_check_output.assert_called_with("ls", shell=True, stderr=-2)
# Then print
mock_print.assert_has_calls([call("ls"), call("output")])
@patch("nephos.helpers.misc.check_output")
3
Source : test_misc.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_input_files_multiple(
self, mock_print, mock_get_response, mock_isfile, mock_open
):
mock_isfile.side_effect = [True, True]
mock_get_response.side_effect = self.files
data = input_files(("hello", "goodbye"))
mock_print.assert_not_called()
mock_get_response.assert_has_calls([call("Input hello"), call("Input goodbye")])
mock_isfile.assert_has_calls([call(self.files[0]), call(self.files[1])])
mock_open.assert_any_call(self.files[0], "rb")
mock_open.assert_any_call(self.files[1], "rb")
assert data.keys() == {"hello", "goodbye"}
@patch("nephos.helpers.misc.open")
3
Source : test_misc.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_input_files_mistake(
self, mock_print, mock_get_response, mock_isfile, mock_open
):
mock_isfile.side_effect = [False, True]
mock_get_response.side_effect = [self.files[0] + "OOPS", self.files[0]]
data = input_files(("hello",))
mock_print.assert_called_once_with(
"{} is not a file".format(self.files[0] + "OOPS")
)
mock_get_response.assert_has_calls([call("Input hello"), call("Input hello")])
mock_isfile.assert_has_calls(
[call(self.files[0] + "OOPS"), call(self.files[0])]
)
mock_open.assert_called_with(self.files[0], "rb")
assert data.keys() == {"hello"}
@patch("nephos.helpers.misc.open")
3
Source : test_misc.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_get_response_options(self, mock_print, mock_input):
mock_input.side_effect = ["mistake", "y"]
get_response("A question", ("y", "n"))
mock_input.assert_has_calls([call()] * 2)
mock_print.assert_has_calls(
[
call("A question"),
call("Permitted responses: ('y', 'n')"),
call("Invalid response, try again!"),
]
)
class TestPrettyPrint:
3
Source : test_deploy.py
with Apache License 2.0
from aidtechnology
with Apache License 2.0
from aidtechnology
def test_settings_verbose(self, mock_load_config, mock_print):
mock_load_config.side_effect = [{"key": "value"}]
result = RUNNER.invoke(
cli, ["-v", "--settings_file", "nephos_config.yaml", "settings"]
)
mock_load_config.assert_called_once_with("nephos_config.yaml")
mock_print.assert_has_calls(
[
call("Settings successfully loaded...\n"),
call('{\n "key": "value"\n}'),
]
)
assert result.exit_code == 0
3
Source : test_configdocs_api.py
with Apache License 2.0
from airshipit
with Apache License 2.0
from airshipit
def test_on_post(self, mock_acquire, mock_release, api_client):
queries = ["", "force=true", "dryrun=true"]
with patch.object(
CommitConfigDocsResource, 'commit_configdocs', return_value={}
) as mock_method:
for q in queries:
result = api_client.simulate_post(
"/api/v1.0/commitconfigdocs", query_string=q,
headers=common.AUTH_HEADERS)
assert result.status_code == 200
mock_method.assert_has_calls([
mock.call(ANY, False, False),
mock.call(ANY, True, False),
mock.call(ANY, False, True)
])
def test_commit_configdocs(self):
3
Source : test_commit_commands.py
with Apache License 2.0
from airshipit
with Apache License 2.0
from airshipit
def test_commit_configdocs_options(*args):
"""test commit configdocs command with options"""
runner = CliRunner()
options = ['--force', '--dryrun']
with patch.object(CommitConfigdocs, '__init__') as mock_method:
for opt in options:
results = runner.invoke(shipyard, [auth_vars, 'commit',
'configdocs', opt])
mock_method.assert_has_calls([
mock.call(ANY, True, False),
mock.call(ANY, False, True)
])
def test_commit_configdocs_negative_invalid_arg():
3
Source : test_core.py
with MIT License
from albumentations-team
with MIT License
from albumentations-team
def test_dual_transform(image, mask):
image_call = call(image, interpolation=cv2.INTER_LINEAR, cols=image.shape[1], rows=image.shape[0])
mask_call = call(mask, interpolation=cv2.INTER_NEAREST, cols=mask.shape[1], rows=mask.shape[0])
with mock.patch.object(DualTransform, "apply") as mocked_apply:
with mock.patch.object(DualTransform, "get_params", return_value={"interpolation": cv2.INTER_LINEAR}):
aug = DualTransform(p=1)
aug(image=image, mask=mask)
mocked_apply.assert_has_calls([image_call, mask_call], any_order=True)
def test_additional_targets(image, mask):
3
Source : test_core.py
with MIT License
from albumentations-team
with MIT License
from albumentations-team
def test_additional_targets(image, mask):
image_call = call(image, interpolation=cv2.INTER_LINEAR, cols=image.shape[1], rows=image.shape[0])
image2_call = call(mask, interpolation=cv2.INTER_LINEAR, cols=mask.shape[1], rows=mask.shape[0])
with mock.patch.object(DualTransform, "apply") as mocked_apply:
with mock.patch.object(DualTransform, "get_params", return_value={"interpolation": cv2.INTER_LINEAR}):
aug = DualTransform(p=1)
aug.add_targets({"image2": "image"})
aug(image=image, image2=mask)
mocked_apply.assert_has_calls([image_call, image2_call], any_order=True)
def test_check_bboxes_with_correct_values():
3
Source : test_connection.py
with MIT License
from alengwenus
with MIT License
from alengwenus
async def test_lcn_connected(pchk_server, pypck_client):
"""Test lcn disconnected event."""
pypck_client.event_handler = AsyncMock()
await pypck_client.async_connect()
await pchk_server.send_message("$io:#LCN:connected")
await pypck_client.received("$io:#LCN:connected")
pypck_client.event_handler.assert_has_awaits(
[call("lcn-connection-status-changed"), call("lcn-connected")]
)
@pytest.mark.asyncio
3
Source : test_connection.py
with MIT License
from alengwenus
with MIT License
from alengwenus
async def test_lcn_disconnected(pchk_server, pypck_client):
"""Test lcn disconnected event."""
pypck_client.event_handler = AsyncMock()
await pypck_client.async_connect()
await pchk_server.send_message("$io:#LCN:disconnected")
await pypck_client.received("$io:#LCN:disconnected")
pypck_client.event_handler.assert_has_awaits(
[call("lcn-connection-status-changed"), call("lcn-disconnected")]
)
@pytest.mark.asyncio
3
Source : test_connection.py
with MIT License
from alengwenus
with MIT License
from alengwenus
async def test_connection_lost(pchk_server, pypck_client):
"""Test pchk server connection close."""
pypck_client.event_handler = AsyncMock()
await pypck_client.async_connect()
await pchk_server.stop()
# ensure that pypck_client is about to be closed
await pypck_client.wait_closed()
pypck_client.event_handler.assert_has_awaits([call("connection-lost")])
@pytest.mark.asyncio
3
Source : test_connection.py
with MIT License
from alengwenus
with MIT License
from alengwenus
async def test_multiple_connections(
pchk_server, pypck_client, pchk_server_2, pypck_client_2
):
"""Test that two independent connections can coexists."""
await pypck_client_2.async_connect()
pypck_client.event_handler = AsyncMock()
await pypck_client.async_connect()
await pchk_server.stop()
await pypck_client.wait_closed()
pypck_client.event_handler.assert_has_awaits([call("connection-lost")])
assert len(pypck_client.task_registry.tasks) == 0
assert len(pypck_client_2.task_registry.tasks) > 0
@pytest.mark.asyncio
3
Source : test_decorator.py
with MIT License
from alhazmy13
with MIT License
from alhazmy13
def test_api_response_with_status_only(self, mock_http_response):
# given
mock_method = MagicMock(return_value=HTTPStatus.BAD_REQUEST)
# when
decorator = api_response()
decorated = decorator(mock_method)
decorated("dummy")
# then
self.assertEqual(mock_http_response.to_json_response.call_args,
call(HTTPStatus.BAD_REQUEST))
self.assertEqual(mock_method.call_args, call("dummy"))
@patch('src.common.decorator.HTTPResponse')
3
Source : test_decorator.py
with MIT License
from alhazmy13
with MIT License
from alhazmy13
def test_api_response_without_status(self, mock_http_response):
# given
mock_method = MagicMock(return_value="response")
# when
decorator = api_response()
decorated = decorator(mock_method)
decorated("dummy")
# then
self.assertEqual(mock_http_response.to_ok_json.call_args,
call(body="response", encoder=PynamoDbEncoder))
self.assertEqual(mock_method.call_args, call("dummy"))
@patch('src.common.decorator.HTTPResponse')
3
Source : test_decorator.py
with MIT License
from alhazmy13
with MIT License
from alhazmy13
def test_api_response_with_both_response_and_status(self, mock_http_response):
# given
mock_method = MagicMock(return_value=(HTTPStatus.BAD_REQUEST, "response"))
# when
decorator = api_response()
decorated = decorator(mock_method)
decorated("dummy")
# then
self.assertEqual(mock_http_response.to_json_response.call_args,
call(HTTPStatus.BAD_REQUEST, "response"))
self.assertEqual(mock_method.call_args, call("dummy"))
3
Source : test_piat_server.py
with MIT License
from Ali-aqrabawi
with MIT License
from Ali-aqrabawi
def test__setup(self, mock_syslog_server, mock_snmp_trap_server, mock_process):
s = PiatServer([], [])
mock_syslog_server.assert_called_with([], 514)
mock_snmp_trap_server.assert_called_with([], 'public', 162, '')
calls = [mock.call(target=mock_syslog_server().start),
mock.call(target=mock_snmp_trap_server().start)]
mock_process.assert_has_calls(calls)
self.assertEqual(len(s._processes), 2)
self.assertIsInstance(s._processes, list)
@mock.patch('piat.servers.piat_server.Process')
3
Source : test_syslog_server.py
with MIT License
from Ali-aqrabawi
with MIT License
from Ali-aqrabawi
def test_handel(self, mock_BaseRequestHandler, mock_SyslogMsg, mock_ThreadsManager):
_SyslogHandler.callbacks = ['cb1', 'cb2']
handler = _SyslogHandler([b"raw byte packet", ], ('1.1.1.1', 8000), None)
mock_SyslogMsg.create_msg.assert_called_with('1.1.1.1', "raw byte packet")
mock_ThreadsManager.assert_called_with()
expected_calls = []
for callback in handler.callbacks:
call = mock.call(callback, args=[mock_SyslogMsg.create_msg()])
expected_calls.append(call)
mock_ThreadsManager().add.assert_has_calls(expected_calls)
class TestSyslogServer(TestCase):
3
Source : test_pickup.py
with BSD 3-Clause "New" or "Revised" License
from alphatwirl
with BSD 3-Clause "New" or "Revised" License
from alphatwirl
def test_no_report(self, pickup, mock_queue, presentation):
mock_queue.empty.side_effect = [False, True]
mock_queue.get.side_effect = [None]
pickup._run_until_the_end_order_arrives()
assert [] == presentation.mock_calls
assert [mock.call(), mock.call()] == mock_queue.empty.mock_calls
assert 0 == pickup._short_sleep.call_count
def test_one_report(self, pickup, mock_queue, presentation):
3
Source : test_stream.py
with BSD 3-Clause "New" or "Revised" License
from alphatwirl
with BSD 3-Clause "New" or "Revised" License
from alphatwirl
def test_print_bytes(obj, mock_queue, monkeypatch):
monkeypatch.setattr(sys, 'stdout', obj)
print(b'abc')
assert [call(("b'abc'\n", FD.STDOUT))] == mock_queue.put.call_args_list
##__________________________________________________________________||
def test_stdout(obj, mock_queue, monkeypatch):
3
Source : test_local_tcp_protocol.py
with MIT License
from Amaindex
with MIT License
from Amaindex
def test_negotiate_with_invalid_socks_version(mock_transport):
config = Config()
local_tcp = LocalTCP(config)
local_tcp.connection_made(mock_transport)
# Invalid version
# VER, NMETHODS = b"\x06\x02"
local_tcp.data_received(b"\x06\x02")
with pytest.raises(asyncio.exceptions.CancelledError):
asyncio.get_event_loop().run_until_complete(local_tcp.negotiate_task)
# NoVersionAllowed
calls = [call(b"\x05\xff")]
local_tcp.transport.write.assert_has_calls(calls)
def test_negotiate_with_invalid_auth_method(mock_transport):
3
Source : test_etheroll_ui.py
with MIT License
from AndreMiras
with MIT License
from AndreMiras
def load_roll_screen(screen_manager):
"""Loads back the default screen."""
with patch_fetch_update_balance() as m_fetch_update_balance:
# loads back the default screen
screen_manager.current = 'roll_screen'
assert m_fetch_update_balance.call_args_list == [mock.call()]
advance_frames_for_screen()
class UITestCase(unittest.TestCase):
3
Source : test_utils_slack_api.py
with Apache License 2.0
from app-sre
with Apache License 2.0
from app-sre
def test_update_usergroup_users(slack_api):
slack_api.client.update_usergroup_users('ABCD', ['USERA', 'USERB'])
assert slack_api.mock_slack_client.return_value\
.usergroups_users_update.call_args == \
call(usergroup='ABCD', users=['USERA', 'USERB'])
@patch.object(SlackApi, 'get_random_deleted_user', autospec=True)
3
Source : test_utils_slack_api.py
with Apache License 2.0
from app-sre
with Apache License 2.0
from app-sre
def test_update_usergroup_users_empty_list(mock_get_deleted, slack_api):
"""Passing in an empty list supports removing all users from a group."""
mock_get_deleted.return_value = 'a-deleted-user'
slack_api.client.update_usergroup_users('ABCD', [])
assert slack_api.mock_slack_client.return_value\
.usergroups_users_update.call_args == \
call(usergroup='ABCD', users=['a-deleted-user'])
def test_get_user_id_by_name_user_not_found(slack_api):
3
Source : test_config.py
with GNU General Public License v3.0
from archlinux
with GNU General Public License v3.0
from archlinux
def test_read_toml_configuration_settings(
toml_load_mock: Mock,
empty_toml_file: Path,
empty_toml_files_in_dir: Path,
) -> None:
with patch("repo_management.defaults.SETTINGS_LOCATION", empty_toml_file):
config.read_toml_configuration_settings(Mock())
with patch("repo_management.defaults.SETTINGS_OVERRIDE_LOCATION", empty_toml_files_in_dir):
config.read_toml_configuration_settings(Mock())
toml_load_mock.has_calls(call([empty_toml_file] + sorted(empty_toml_files_in_dir.glob("*.toml"))))
@fixture(
3
Source : test_fhirstore.py
with Apache License 2.0
from arkhn
with Apache License 2.0
from arkhn
def test_save_many(_):
fhirstore.save_many(
[
{"name": "instance1", "value": 1},
{"name": "instance2", "value": 2},
{"name": "instance3", "value": 3},
]
)
store = fhirstore.get_fhirstore()
assert store.create.call_count == 3
store.create.assert_has_calls(
[
mock.call({"name": "instance1", "value": 1}, bypass_document_validation=False),
mock.call({"name": "instance2", "value": 2}, bypass_document_validation=False),
mock.call({"name": "instance3", "value": 3}, bypass_document_validation=False),
]
)
3
Source : test_dataset_downloader.py
with MIT License
from ArtemKushnerov
with MIT License
from ArtemKushnerov
def test_downloads_apks(self, get_mock, open_mock, os_mock):
self.dataset_downloader.download()
self.assertTrue(mock.call(self.apk) in self.constructor_mock.construct.call_args_list)
self.assertTrue(mock.call(self.apk2) in self.constructor_mock.construct.call_args_list)
self.constructor_mock.reset_mock()
self.assertEqual(get_mock.call_count, 2)
self.assertTrue(mock.call(r'out/apk1.apk', 'wb') in open_mock.call_args_list)
self.assertTrue(mock.call(r'out/apk2.apk', 'wb') in open_mock.call_args_list)
if __name__ == '__main__':
3
Source : test_lsankidb.py
with The Unlicense
from AurelienLourot
with The Unlicense
from AurelienLourot
def test_main_finds_db_and_prints_it(self, mock_parse_args, mock_find_db_path, mock_db,
mock_print):
mock_parse_args.return_value.PATH = None
mock_find_db_path.return_value = '/path/to/db.anki2'
mock_db.side_effect = ['hello']
lsankidb.main()
mock_db.assert_called_once_with(mock_find_db_path.return_value)
mock_print.assert_has_calls([mock.call('hello')])
@mock.patch('src.lsankidb.print')
3
Source : test_lsankidb.py
with The Unlicense
from AurelienLourot
with The Unlicense
from AurelienLourot
def test_main_prints_passed_db(self, mock_parse_args, mock_db, mock_print):
mock_parse_args.return_value.PATH = '/path/to/db.anki2'
mock_db.side_effect = ['hello']
lsankidb.main()
mock_db.assert_called_once_with(mock_parse_args.return_value.PATH)
mock_print.assert_has_calls([mock.call('hello')])
@mock.patch('src.lsankidb._find_db_path')
3
Source : test_plugin_base.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_language_plugin_setup_jinja_env_no_spec(plugin):
with patch(
"rpdk.core.plugin_base.importlib.util.find_spec", return_value=None
) as mock_spec, patch("rpdk.core.plugin_base.PackageLoader") as mock_loader:
env = plugin._setup_jinja_env()
mock_spec.assert_called_once_with(plugin._module_name)
mock_loader.assert_has_calls([call(plugin._module_name), call(plugin_base_name)])
assert env.loader
assert env.autoescape
for name in FILTER_REGISTRY:
assert name in env.filters
3
Source : test_project.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_write_configuration_schema():
mock_path = MagicMock(spec=Path)
project = Project(root=mock_path)
project.type_info = ("test", "validTypeConfiguration")
project.write_configuration_schema(mock_path)
mock_path.open.assert_called_once_with("w", encoding="utf-8")
mock_f = mock_path.open.return_value.__enter__.return_value
mock_f.write.assert_has_calls([call("null"), call("\n")])
def test_configuration_schema_filename(project):
3
Source : test_resource_helper.py
with Apache License 2.0
from aws-cloudformation
with Apache License 2.0
from aws-cloudformation
def test_init_failure_call(self, mock_send):
c = crhelper.resource_helper.CfnResource()
c.init_failure(Exception('TestException'))
event = test_events["Create"]
c.__call__(event, MockContext)
self.assertEqual([call('FAILED', 'TestException')], mock_send.call_args_list)
@patch('crhelper.log_helper.setup', Mock())
3
Source : asset_helpers_unit_test.py
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
def test_read_from_site_packages(mocked_open):
# setup
from servicecatalog_puppet import asset_helpers as sut
expected_param = os.path.sep.join(
[os.path.dirname(os.path.abspath(__file__)), "foo"]
)
# exercise
sut.read_from_site_packages("foo")
# verify
assert mocked_open.call_count == 1
assert mocked_open.call_args == call(expected_param, "r")
3
Source : test_fetcher_dispatcher_service.py
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
def test_fetcher_event_handler_nothing_to_do(
fetcher_callback: FetcherEventHandler, benchmark_event_without_datasets_or_models, kafka_service: KafkaService
):
fetcher_callback.handle_event(benchmark_event_without_datasets_or_models, kafka_service)
assert kafka_service.send_status_message_event.call_args_list == [call(ANY, Status.SUCCEEDED, "Nothing to fetch")]
args, _ = kafka_service.send_event.call_args_list[0]
fetcher_event, topic = args
assert isinstance(fetcher_event, FetcherBenchmarkEvent)
assert topic == PRODUCER_TOPIC
assert fetcher_event.payload.datasets == []
def validate_populated_dst(benchmark_event):
3
Source : test_http_estimator.py
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
def test_http_estimator(mock_curl):
size_info = http_estimate_size(SOME_DATASET_SRC)
mock_curl.setopt.assert_has_calls(
[call(pycurl.URL, SOME_DATASET_SRC), call(pycurl.NOBODY, 1), call(pycurl.HEADER, 1)], any_order=True
)
mock_curl.getinfo.assert_called_with(pycurl.CONTENT_LENGTH_DOWNLOAD)
assert size_info == ContentSizeInfo(DATA_SIZE, 1, DATA_SIZE)
3
Source : test_s3_utils.py
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
def test_upload_to_s3_pass_through(mock_file, mock_s3_client):
upload_to_s3(mock_file, S3OBJECT)
assert mock_file.seek.call_args_list == [call(0, SEEK_END), call(0)]
mock_s3_client.upload_fileobj.assert_called_once_with(mock_file, S3OBJECT.bucket, S3OBJECT.key, Callback=ANY)
def test_upload_to_s3_wrap_exception(mock_file, mock_client_error_s3_client):
3
Source : test_execution_callback.py
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
def test_handle_event(
executor_handler: ExecutorEventHandler,
fetcher_event: FetcherBenchmarkEvent,
kafka_service: KafkaService,
expected_executor_event: ExecutorBenchmarkEvent,
expected_pending_call,
):
executor_handler.handle_event(fetcher_event, kafka_service)
kafka_service.send_status_message_event.assert_has_calls(
[expected_pending_call, call(expected_executor_event, Status.SUCCEEDED, ANY)]
)
kafka_service.send_event.assert_called_once_with(expected_executor_event, PRODUCER_TOPIC)
def test_handle_event_processes_single_run_benchmark(
See More Examples