async def test_play_sound_file_sets_volume_and_plays_with_end_at( self, example_sound_manager, monkeypatch): """ Test that the `_play_sound_file()` method sets the volume on the `pygame.mixer.Sound` instance with the configured volume, that it starts to play the sound and waits for it to finish. This test assumes the `end_at` attribute on the sound to be set, so make sure to set it. Make sure the `play()` method is called appropriately and the method should sleep for the correct amount of time. """ sound_instance_mock = MagicMock() sleep_mock = CoroutineMock() monkeypatch.setattr("src.sound.sound_manager.pygame.mixer.Sound", MagicMock(return_value=sound_instance_mock)) monkeypatch.setattr("src.sound.sound_manager.asyncio.sleep", sleep_mock) example_sound_manager.volume = 0.5 group = example_sound_manager.groups[0] sound = group.sounds[0] sound.volume = 0.5 assert len( sound.files ) == 1 # make sure it is only one since they are chosen at random sound_file = sound.files[0] sound_file.end_at = 4000 await example_sound_manager._play_sound_file(0, 0) sound_instance_mock.set_volume.assert_called_once_with( example_sound_manager.volume * sound.volume) sound_instance_mock.play.assert_called_once_with( maxtime=sound_file.end_at) sleep_mock.assert_called_once_with(sound_file.end_at / 1000) # in seconds
async def test_play_sound_file_sets_volume_and_plays( self, example_sound_manager, monkeypatch): """ Test that the `_play_sound_file()` method sets the volume on the `pygame.mixer.Sound` instance with the configured volume, that it starts to play the sound and waits for it to finish. This test assumes no `end_at` attribute on the sound, so make sure to remove it. """ sound_instance_mock = MagicMock() sound_instance_mock.get_length.return_value = 42 sleep_mock = CoroutineMock() monkeypatch.setattr("src.sound.sound_manager.pygame.mixer.Sound", MagicMock(return_value=sound_instance_mock)) monkeypatch.setattr("src.sound.sound_manager.asyncio.sleep", sleep_mock) example_sound_manager.volume = 0.5 group = example_sound_manager.groups[0] sound = group.sounds[0] sound.volume = 0.5 assert len( sound.files ) == 1 # make sure it is only one since they are chosen at random sound_file = sound.files[0] sound_file.end_at = None # Test without end_at await example_sound_manager._play_sound_file(0, 0) sound_instance_mock.set_volume.assert_called_once_with( example_sound_manager.volume * sound.volume) sound_instance_mock.play.assert_called_once_with() sound_instance_mock.get_length.assert_called_once() sleep_mock.assert_called_once_with( 42) # same as sound_instance.get_length()
async def test_007_on_direct_message(self): cb = CoroutineMock() self.bus.direct_subscribe(cb) msg = self.bus.client.Message() msg['type'] = 'message' msg['from'] = JID('other@localhost') msg['body'] = '{"key": "value"}' await self.bus._on_direct_message(msg) cb.assert_called_once_with('other', {'key': 'value'})
async def test_007_on_direct_message(self): cb = CoroutineMock() self.bus.direct_subscribe(cb) msg = self.bus.client.Message() msg['type'] = 'message' msg['from'] = JID('other@localhost') msg['body'] = '{"key": "value"}' await self.bus._on_direct_message(msg) cb.assert_called_once_with('other', {'key': 'value'})
async def test_error_handler_coroutine(dummy_provider): error_handler = CoroutineMock(return_value=True) route = Route(dummy_provider, mock.Mock(), error_handler=error_handler) exc = TypeError() exc_info = (type(exc), exc, 'traceback') result = await route.error_handler(exc_info, 'whatever') assert result is True assert error_handler.called error_handler.assert_called_once_with(exc_info, 'whatever')
async def test_deliver_with_message_translator(dummy_provider): mock_handler = CoroutineMock(return_value=True) route = Route(dummy_provider, mock_handler) route.apply_message_translator = mock.Mock(return_value={'content': 'whatever', 'metadata': {}}) result = await route.deliver('test') assert result is True assert route.apply_message_translator.called assert mock_handler.called mock_handler.assert_called_once_with('whatever', {})
async def test_get_select_root_field_graphql(self, monkeypatch): mock = CoroutineMock() monkeypatch.setattr( "prefect_server.database.hasura.HasuraClient.execute", mock) graphql = await self.TestModel().where().get() mock.assert_called_once_with( query={"query": { "select: abc(where: {})": "id" }}, as_box=False)
async def test_error_handler_coroutine(dummy_provider): error_handler = AsyncMock(return_value=True) route = Route(dummy_provider, mock.Mock(), error_handler=error_handler) exc = TypeError() exc_info = (type(exc), exc, "traceback") result = await route.error_handler(exc_info, "whatever") assert result is True assert error_handler.called error_handler.assert_called_once_with(exc_info, "whatever")
async def test_error_handler_ok(self, mocker): app = mocker.Mock() handler = CoroutineMock() request = mocker.Mock() factory = error_handler() handle_func = await factory(app, handler) await handle_func(request) handler.assert_called_once_with(request)
async def test_ok(self, mocker): fake_app = mocker.Mock() fake_handler = CoroutineMock() fake_request = mocker.Mock() mocked_params_dict = mocker.patch('aiohttp_baseapi.middleware.params_handler.ParamsDict') handle_func = await factory(fake_app, fake_handler) await handle_func(fake_request) fake_handler.assert_called_once_with(fake_request) mocked_params_dict.assert_called_once_with(fake_request.query)
async def test_resolve_request_with_single_matcher(self): handler = CoroutineMock(return_value=sentinel.response) matcher = CoroutineMock(return_value=True) self.resolver.register_matcher(matcher, handler) request = Mock() response = await self.resolver.resolve(request, self.default_app) self.assertEqual(response, handler) matcher.assert_called_once_with(request) handler.assert_not_called()
async def test_deliver_with_message_translator(dummy_provider): mock_handler = CoroutineMock(return_value=True) route = Route(dummy_provider, mock_handler) route.apply_message_translator = mock.Mock(return_value={ 'content': 'whatever', 'metadata': {} }) result = await route.deliver('test') assert result is True assert route.apply_message_translator.called assert mock_handler.called mock_handler.assert_called_once_with('whatever', {})
async def test_002_on_event(self): cb = CoroutineMock() with patch.object(self.bus._mucs, 'joinMUC') as join_mock: self.bus._connected.set() await self.bus.subscribe('other', cb) join_mock.assert_called_once_with('*****@*****.**', 'login') msg = self.bus.client.Message() msg['type'] = 'groupchat' msg['from'] = JID('other@localhost') msg['body'] = '{"key": "value"}' await self.bus._on_event(msg) cb.assert_called_once_with({'key': 'value'})
async def test_deliver_with_message_translator(dummy_provider): mock_handler = AsyncMock(return_value=True) route = Route(dummy_provider, mock_handler) route.apply_message_translator = mock.Mock(return_value={ "content": "whatever", "metadata": {} }) result = await route.deliver("test") assert result is True assert route.apply_message_translator.called assert mock_handler.called mock_handler.assert_called_once_with("whatever", {})
async def test_002_on_event(self): self.bus._connected.set() cb = CoroutineMock() with patch.object(self.bus._mucs, 'join_muc') as join_mock: await self.bus.subscribe('someone', cb) join_mock.assert_called_once_with('*****@*****.**', 'test') msg = self.bus.client.Message() msg['type'] = 'groupchat' msg['to'] = JID('test@localhost') msg['from'] = JID('someone@localhost') msg['body'] = '{"key": "value"}' await self.bus._on_event(msg) cb.assert_called_once_with('someone', {'key': 'value'})
async def test_resolve_request_with_first_falsy_matcher(self): handler = CoroutineMock(return_value=sentinel.response) matcher1 = CoroutineMock(return_value=False) matcher2 = CoroutineMock(return_value=True) self.resolver.register_matcher(matcher1, handler) self.resolver.register_matcher(matcher2, handler) request = Mock() response = await self.resolver.resolve(request, self.default_app) self.assertEqual(response, self.default_handler) matcher1.assert_called_once_with(request) matcher2.assert_not_called() handler.assert_not_called()
async def test_handle_function_called_with_args(): mock_callback = CoroutineMock() args = (1, 2, 3) kwargs = {"a": 1} timeout = 0 name = 'timer_name' timer = Timer(timeout, mock_callback, name, *args, **kwargs) await timer.run() mock_callback.assert_called_once_with(*args, **kwargs) # Cleanup timer.cancel()
async def test_resolve_request_priority(self): matcher = CoroutineMock(side_effect=(True, True)) handler1 = CoroutineMock(return_value=sentinel.response1) handler2 = CoroutineMock(return_value=sentinel.response2) self.resolver.register_matcher(matcher, handler1) self.resolver.register_matcher(matcher, handler2) request = Mock() response = await self.resolver.resolve(request, self.default_app) self.assertEqual(response, handler1) handler1.assert_not_called() handler2.assert_not_called() matcher.assert_called_once_with(request)
async def test_update_device_config(hass, hass_client): """Test updating device config.""" with patch.object(config, "SECTIONS", ["group"]): await async_setup_component(hass, "config", {}) client = await hass_client() orig_data = { "hello.beer": { "ignored": True }, "other.entity": { "polling_intensity": 2 }, } def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) mock_call = CoroutineMock() with patch("homeassistant.components.config._read", mock_read), patch( "homeassistant.components.config._write", mock_write), patch.object(hass.services, "async_call", mock_call): resp = await client.post( "/api/config/group/config/hello_beer", data=json.dumps({ "name": "Beer", "entities": ["light.top", "light.bottom"] }), ) await hass.async_block_till_done() assert resp.status == 200 result = await resp.json() assert result == {"result": "ok"} orig_data["hello_beer"]["name"] = "Beer" orig_data["hello_beer"]["entities"] = ["light.top", "light.bottom"] assert written[0] == orig_data mock_call.assert_called_once_with("group", "reload")
async def test_get_custom_select_aggregate_root_field_graphql( self, monkeypatch): mock = CoroutineMock() monkeypatch.setattr( "prefect_server.database.hasura.HasuraClient.execute", mock) graphql = await self.TestCustomModel().where().count() mock.assert_called_once_with( { "query": { "count: custom_select_aggregate_xyz(where: {})": { "aggregate": "count" } } }, as_box=False, )
async def test_query_get_result_pandas(monkeypatch, format, function): get_result_mock = CoroutineMock(return_value="DUMMY_RESULT") monkeypatch.setattr(f"flowclient.async_api_query.{function}", get_result_mock) connection_mock = AMock() connection_mock.post_json = CoroutineMock(return_value=Mock( status_code=202, headers={"Location": "DUMMY_LOCATION/DUMMY_ID"})) query = ASyncAPIQuery(connection=connection_mock, parameters={"query_kind": "dummy_query"}) await query.run() assert "DUMMY_RESULT" == await query.get_result(format=format, poll_interval=2) get_result_mock.assert_called_once_with( connection=connection_mock, disable_progress=None, query_id="DUMMY_ID", poll_interval=2, )
async def test_ok(self, mocker): fake_base_method = CoroutineMock() mocked_http_status = mocker.patch('http.HTTPStatus') mocked_json_response = mocker.patch('aiohttp_baseapi.decorators.JSONResponse') class FakeClass: fake_method = jsonify_response(fake_base_method) fake_obj = FakeClass() compared_response = await fake_obj.fake_method() expected_response = mocked_json_response.return_value assert compared_response == expected_response fake_base_method.assert_called_once_with(fake_obj) mocked_json_response.assert_called_once_with( fake_base_method.return_value, status=mocked_http_status.OK )
async def test_ok(self, mocker: MockFixture, fake_data_provider: BaseDataProvider): fake_get_many = CoroutineMock() fake_data_provider.test_attribute_name = 'test_attribute_value' fake_include_settings_data_provider = mocker.Mock( __name__='foo', return_value=mocker.Mock(get_many=fake_get_many)) fake_item = mocker.Mock() fake_include_settings = { 'relations': [{ 'included_entity_field_name': 'foo', 'root_entity_field_name': 'bar', }], 'data_provider_init_params': [{ 'param_name': 'test_param_name', 'attribute_name': 'test_attribute_name', }], 'data_provider_class': fake_include_settings_data_provider } fake_include_params = { 'page': mocker.Mock(), 'sort': mocker.Mock(), 'available_includes': mocker.Mock(), 'include': mocker.Mock(), } result = await fake_data_provider.get_item_include_data( fake_item, fake_include_settings, fake_include_params) fake_item.get.assert_called_once_with('bar') fake_include_settings_data_provider.assert_called_once_with( filters={'foo': fake_item.get.return_value}, page=fake_include_params.get('page'), sort=fake_include_params.get('sort'), include=fake_include_params.get('include'), available_includes=fake_include_params.get('available_includes'), test_param_name='test_attribute_value') fake_get_many.assert_called_once_with() assert result == fake_get_many.return_value
class Pick(CommandTestCase): def setup(self, state="A", inv=0): mock_command = Mock(spec=PickCommand, invocation="A") mock_message = Mock(spec=Message) mock_candy_value = Mock(spec=CandyValue, candy=Mock(spec=Candy), value=10) self.mock_candy_drop = Mock(spec=CandyDrop, candy_value=mock_candy_value, command=mock_command, message=mock_message) self.mock_state = {state: self.mock_candy_drop} self.patch("candybot.engine.STATE", self.mock_state) mock_get_inv = Mock(spec=database.get_inv, return_value={ "A": Mock(spec=CandyCollection, __getitem__=Mock(return_value=inv)) }) self.mock_database = Mock(spec=database, get_inv=mock_get_inv) self.patch("candybot.commands.pick.database", self.mock_database) self.mock_send = CoroutineMock() self.patch("candybot.commands.Command.send", self.mock_send) def assert_action(self, expected_candy): self.assertFalse(self.mock_state) self.mock_candy_drop.message.delete.assert_called_once_with() self.mock_database.set_inv.assert_called_once_with( "A", "A", self.mock_candy_drop.candy_value, update=True) self.mock_send.assert_called_once_with(self.mock_candy_drop.pick_str) self.assertEqual(self.mock_candy_drop.candy_value.value, expected_candy) def assert_no_action(self): self.assertTrue(self.mock_state) self.mock_candy_drop.message.delete.assert_not_called() self.mock_database.set_inv.assert_not_called() self.mock_send.assert_not_called() def test_invocation_default(self): command = PickCommand(None) self.assertEqual(command.invocation, "pick") def test_invocation_set(self): command = PickCommand(None, invocation="A") self.assertEqual(command.invocation, "A") async def test_ignore_if_no_state(self): self.setup(state="B") command = PickCommand(None, invocation="A") await command._run() self.assert_no_action() async def test_ignore_if_invocations_differ(self): self.setup() command = PickCommand(None, invocation="B") await command._run() self.assert_no_action() async def test_ignore_if_at_cap(self): self.setup(inv=20) command = PickCommand(Mock(spec=Settings, cap=20), invocation="A") await command._run() self.assert_no_action() async def test_successful_full_pick(self): self.setup() command = PickCommand(Mock(spec=Settings, cap=20), invocation="A") await command._run() self.assert_action(10) async def test_successful_partial_pick(self): self.setup(inv=15) command = PickCommand(Mock(spec=Settings, cap=20), invocation="A") await command._run() self.assert_action(5)