def test_game_session_admin_session_download_layout_description_no_spoiler( mock_layout_description: PropertyMock, clean_database, mock_emit_session_update, flask_app): user1 = database.User.create(id=1234, name="The Name") session = database.GameSession.create( id=1, name="Debug", state=GameSessionState.SETUP, creator=user1, layout_description_json="layout_description_json") database.GameSessionMembership.create(user=user1, session=session, row=None, admin=False) sio = MagicMock() sio.get_current_user.return_value = user1 mock_layout_description.return_value.permalink.spoiler = False # Run with pytest.raises(InvalidAction), flask_app.test_request_context(): game_session.game_session_admin_session( sio, 1, SessionAdminGlobalAction.DOWNLOAD_LAYOUT_DESCRIPTION.value, None) # Assert mock_emit_session_update.assert_not_called() mock_layout_description.assert_called_once()
def test_set_yarn_spark_resource_config_fallback( patched_virtual_memory, patched_cpu_count, patched_yarn_config, patched_spark_config, default_bootstrapper: Bootstrapper, ) -> None: mocked_virtual_memory_total = PropertyMock(return_value=123 * 1024 * 1024) type(patched_virtual_memory.return_value ).total = mocked_virtual_memory_total patched_cpu_count.return_value = 456 default_bootstrapper.load_processing_job_config = MagicMock( return_value=None) default_bootstrapper.load_instance_type_info = MagicMock(return_value=None) default_bootstrapper.get_yarn_spark_resource_config = MagicMock( return_value=(patched_yarn_config, patched_spark_config)) default_bootstrapper.set_yarn_spark_resource_config() patched_virtual_memory.assert_called_once() mocked_virtual_memory_total.assert_called_once() patched_cpu_count.assert_called_once() default_bootstrapper.load_processing_job_config.assert_called_once() default_bootstrapper.load_instance_type_info.assert_called_once() default_bootstrapper.get_yarn_spark_resource_config.assert_called_once_with( 1, 123, 456) patched_yarn_config.write_config.assert_called_once() patched_spark_config.write_config.assert_called_once()
def test_getTextContent_no_childNodes(self): """Tests getTextContent when it has no childNodes""" _node = MagicMock() _childNodes = PropertyMock(return_value=iter([])) type(_node).childNodes = _childNodes _element = Element(_node) _result = _element.getTextContent() self.assertIsNone(_result) _childNodes.assert_called_once()
def test_compare_sentiments__when_GET_method(self, mock_request, mock_redirect): mock_request_method = PropertyMock(return_value='GET') type(mock_request).method = mock_request_method sentiment.compare_sentiments() mock_request_method.assert_called_once() mock_redirect.assert_called_once_with('/')
def test_getTextContent_has_childNodes_but_without_expected_nodeType(self): """Tests getTextContent whith childNodes""" _node = MagicMock() _childNodes = PropertyMock(return_value=iter( [InnerNode(0, '0'), InnerNode(1, '1')])) type(_node).childNodes = _childNodes _element = Element(_node) _result = _element.getTextContent() self.assertIsNone(_result) _childNodes.assert_called_once()
def test_getTextContent_returns_text(self): """Tests getTextContent when it has proper data""" _node = MagicMock() _childNodes = PropertyMock(return_value=iter([InnerNode(0, '0'), InnerNode( 3, '3'), InnerNode(3, '16'), InnerNode(1, '1')])) type(_node).childNodes = _childNodes _element = Element(_node) _result = _element.getTextContent() self.assertEqual(_result, '3\n16') _childNodes.assert_called_once()
def test_get_image_dimensions(self, mock_open): mock_enter = mock_open.return_value.__enter__ p = PropertyMock() type(mock_enter.return_value).size = p self.operation.get_image_dimensions('somefile') mock_open.assert_called_once_with('somefile') p.assert_called_once()
def test_compare_sentiments__when_POST_method_and_error_occurs( self, mock_request, mock_tweets_sentiment, mock_render_template): mock_request_method = PropertyMock(return_value='POST') type(mock_request).method = mock_request_method mock_request.form.__getitem__.return_value = 'keyword1 ,keyword2, keyword3 ' mock_tweets_sentiment.side_effect = TweepError('test reason') sentiment.compare_sentiments() mock_request_method.assert_called_once() mock_request.form.__getitem__.assert_called_once_with('keywords') mock_tweets_sentiment.assert_called_once() mock_render_template.assert_called_once()
def test_singletonness(self, mock_AwsSecret): value_mock = PropertyMock(return_value='{"secret2": "foo"}') type(mock_AwsSecret()).value = value_mock config1 = BogoComponentConfig(deployment=self.deployment_env, source='aws') self.assertEqual('foo', config1.secret2) config2 = BogoComponentConfig(deployment=self.deployment_env, source='aws') self.assertEqual('foo', config2.secret2) value_mock.assert_called_once()
def test_getIndex_has_parent_node_with_childNodes(self): """Tests getIndex when it has parent with childNodes""" _node = MagicMock() _parent = MagicMock() _childNodes = PropertyMock(return_value=iter([1, 2, 3, _node, 5, 6])) type(_parent).childNodes = _childNodes _getParentIndex = self._init_patch_with_name( '_getParentIndex', 'xmind.core.Element.getParentNode', return_value=_parent, autospec=True) _element = Element(_node) _result = _element.getIndex() self.assertEqual(_result, 3) _getParentIndex.assert_called_once() _childNodes.assert_called_once()
def test_compare_sentiments__when_POST_method_and_more_than_eight_keywords( self, mock_request, mock_render_template): mock_request_method = PropertyMock(return_value='POST') type(mock_request).method = mock_request_method mock_request.form.__getitem__.return_value = 'k1,k2,k3,k4,k5,k6,k7,k8,k9' sentiment.compare_sentiments() mock_request_method.assert_called_once() mock_request.form.__getitem__.assert_called_once_with('keywords') mock_render_template.assert_called_once_with( 'index.html', error=True, message="The maximum amount of keywords is 7")
def test_setTextContent_no_childNodes(self): """Tests setTextContent when it has childNodes""" _node = MagicMock(childNodes=[]) _childNodes = PropertyMock(return_value=iter([])) type(_node).childNodes = _childNodes _text_object = MagicMock() _dom_text = self._init_patch_with_name( '_dom_text', 'xmind.core.DOM.Text', return_value=_text_object, autospec=True) _element = Element(_node) _element.setTextContent('data2') _node.appendChild.assert_called_once_with(_text_object) _dom_text.assert_called_once() _node.removeChild.assert_not_called() _text_object.data = 'data2' _childNodes.assert_called_once()
def test_sync_dhcp(input_manager_dhcp, mocker): # Arrange mock = MagicMock() m_property = PropertyMock(return_value=input_manager_dhcp) type(mock).manage_dhcp = m_property mocker.patch.object(CobblerAPI, "settings", return_value=mock) stub = create_autospec(spec=cobbler.modules.managers.isc._IscManager) mocker.patch("cobbler.modules.managers.isc.get_manager", return_value=stub) test_api = CobblerAPI() # Act test_api.sync_dhcp() # Assert m_property.assert_called_once() assert stub.sync.called == input_manager_dhcp
def test_find_end_point_endpoint_tag_name_is_not_topic(self): _wb_mock = MagicMock() _end_point = MagicMock() _tag_name = PropertyMock(return_value='bla-bla') type(_end_point).tagName = _tag_name _wb_mock.getElementById.return_value = _end_point _relationship_element = RelationshipElement(12) with patch.object(_relationship_element, 'getOwnerWorkbook') as _g_wb: _g_wb.return_value = _wb_mock self.assertIsNone(_relationship_element._find_end_point('1')) self._wb_mixin_element_init.assert_called_once_with( _relationship_element, 12, None) self._add_attribute.assert_called_once_with( _relationship_element, ATTR_ID) _wb_mock.getElementById.assert_called_once_with('1') _tag_name.assert_called_once()
def test_get_ophys_stimulus_timestamps(monkeypatch, sync_path, expected_timestamps): mock_ophys_time_aligner = create_autospec(OphysTimeAligner) mock_aligner_instance = mock_ophys_time_aligner.return_value property_mock = PropertyMock(return_value=(expected_timestamps, "ignored_return_val")) type(mock_aligner_instance).clipped_stim_timestamps = property_mock with monkeypatch.context() as m: m.setattr( "allensdk.brain_observatory.behavior.data_objects" ".timestamps.stimulus_timestamps.timestamps_processing" ".OphysTimeAligner", mock_ophys_time_aligner) obt = get_ophys_stimulus_timestamps(sync_path) mock_ophys_time_aligner.assert_called_with(sync_file=sync_path) property_mock.assert_called_once() assert np.allclose(obt, expected_timestamps)
def test_filtered_state(self): """`filtered_state` calls thru to SessionState, unless disconnected.""" for disconnected in (False, True): with self.subTest(f"disconnected={disconnected}"): safe_state, mock_state = _create_state_spy({}, disconnected) filtered_state_mock = PropertyMock(return_value={ "foo": 10, "bar": 20 }) type(mock_state).filtered_state = filtered_state_mock result = safe_state.filtered_state if disconnected: filtered_state_mock.assert_not_called() self.assertEqual({}, result) else: filtered_state_mock.assert_called_once() self.assertEqual({"foo": 10, "bar": 20}, result)
def test_sync_dns(input_manage_dns, mocker): # Arrange mock = MagicMock() m_property = PropertyMock(return_value=input_manage_dns) type(mock).manage_dns = m_property mocker.patch.object(CobblerAPI, "settings", return_value=mock) # mock get_manager() and ensure mock object has the same api as the object it is replacing. # see https://docs.python.org/3/library/unittest.mock.html#unittest.mock.create_autospec stub = create_autospec(spec=cobbler.modules.managers.bind._BindManager) mocker.patch("cobbler.modules.managers.bind.get_manager", return_value=stub) test_api = CobblerAPI() # Act test_api.sync_dns() # Assert m_property.assert_called_once() assert stub.sync.called == input_manage_dns
def test_compare_sentiments__when_POST_method_and_no_errors( self, mock_request, mock_tweets_sentiment, mock_pool, mock_make_plot, mock_base64, mock_render_template): mock_request_method = PropertyMock(return_value='POST') type(mock_request).method = mock_request_method mock_request.form.__getitem__.return_value = 'keyword1 ,keyword2, keyword3 ' mock_image = MagicMock() mock_make_plot.return_value = (mock_image, 1, 2) sentiment.compare_sentiments() mock_request_method.assert_called_once() mock_request.form.__getitem__.assert_called_once_with('keywords') mock_tweets_sentiment.assert_called_once() mock_pool.assert_called_once() mock_make_plot.assert_called_once() mock_image.getvalue.assert_called_once() mock_base64.b64encode.assert_called_once() mock_base64.b64encode.return_value.decode.assert_called_once() mock_render_template.assert_called_once()
async def test_audio_input_sensor(hass, async_autosetup_sonos, soco, tv_event, no_media_event): """Test audio input sensor.""" entity_registry = ent_reg.async_get(hass) subscription = soco.avTransport.subscribe.return_value sub_callback = subscription.callback sub_callback(tv_event) await hass.async_block_till_done() audio_input_sensor = entity_registry.entities[ "sensor.zone_a_audio_input_format"] audio_input_state = hass.states.get(audio_input_sensor.entity_id) assert audio_input_state.state == "Dolby 5.1" # Set mocked input format to new value and ensure poll success no_input_mock = PropertyMock(return_value="No input") type(soco).soundbar_audio_input_format = no_input_mock async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL) await hass.async_block_till_done() no_input_mock.assert_called_once() audio_input_state = hass.states.get(audio_input_sensor.entity_id) assert audio_input_state.state == "No input" # Ensure state is not polled when source is not TV and state is already "No input" sub_callback(no_media_event) await hass.async_block_till_done() unpolled_mock = PropertyMock(return_value="Will not be polled") type(soco).soundbar_audio_input_format = unpolled_mock async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL) await hass.async_block_till_done() unpolled_mock.assert_not_called() audio_input_state = hass.states.get(audio_input_sensor.entity_id) assert audio_input_state.state == "No input"
def test_max_line_length(): media_info = PropertyMock() metadata_font = PropertyMock() metadata_font.getsize.return_value = (40, 40) header_margin = 100 width = 1000 text = "A long line of text" assert_equals(19, max_line_length(media_info, metadata_font, header_margin, width, text)) text = "A long line of text with a few more words" assert_equals(41, max_line_length(media_info, metadata_font, header_margin, width, text)) text = "A really long line of text with a lots more words" * 100 assert_equals(4900, max_line_length(media_info, metadata_font, header_margin, width, text)) text = None filename = PropertyMock() type(media_info).filename = filename # media_info.filename = filename assert_equals(0, max_line_length(media_info, metadata_font, header_margin, width, text)) filename.assert_called_once()
def test_setTextContent_has_childNodes(self): """Tests setTextContent when it has childNodes""" _childNodesValues = [ InnerNode(0, '0'), InnerNode(3, '3'), InnerNode(3, '16'), InnerNode(1, '1') ] _node = MagicMock() _childNodes = PropertyMock(return_value=iter(_childNodesValues)) type(_node).childNodes = _childNodes _text_object = MagicMock() _dom_text = self._init_patch_with_name( '_dom_text', 'xmind.core.DOM.Text', return_value=_text_object, autospec=True) _element = Element(_node) _element.setTextContent('data2') _node.appendChild.assert_called_once_with(_text_object) self.assertEqual(_node.removeChild.call_count, 2) self.assertListEqual(_node.removeChild.call_args_list, [ call(_childNodesValues[1]), call(_childNodesValues[2])]) _dom_text.assert_called_once() _text_object.data = 'data2' _childNodes.assert_called_once()
def test_find_end_point_endpoint_tag_name_is_topic(self): _wb_mock = MagicMock() _end_point = MagicMock() _tag_name = PropertyMock(return_value=TAG_TOPIC) type(_end_point).tagName = _tag_name _wb_mock.getElementById.return_value = _end_point _relationship_element = RelationshipElement(12) _new_topic_element_mock = self._init_patch_with_name( '_topic', 'xmind.core.relationship.TopicElement', return_value='super', autospec=True) with patch.object(_relationship_element, 'getOwnerWorkbook') as _g_wb: _g_wb.return_value = _wb_mock self.assertEqual( 'super', _relationship_element._find_end_point('1')) self._wb_mixin_element_init.assert_called_once_with( _relationship_element, 12, None) self._add_attribute.assert_called_once_with( _relationship_element, ATTR_ID) _wb_mock.getElementById.assert_called_once_with('1') _tag_name.assert_called_once() _new_topic_element_mock.assert_called_once_with(_end_point, _wb_mock)