def test_get_web_page_with_user_agent_in_headers(self): """ Test that adding a user agent in the header when calling get_web_page() adds that user agent to the request """ with patch('openlp.core.common.httputils.urllib.request.Request') as MockRequest, \ patch('openlp.core.common.httputils.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.common.httputils.get_user_agent') as mock_get_user_agent: # GIVEN: Mocked out objects, a fake URL and a fake header mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object fake_url = 'this://is.a.fake/url' user_agent_header = ('User-Agent', 'OpenLP/2.2.0') # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url, header=user_agent_header) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with(user_agent_header[0], user_agent_header[1]) self.assertEqual(1, mocked_request_object.add_header.call_count, 'There should only be 1 call to add_header') self.assertEqual(0, mock_get_user_agent.call_count, 'get_user_agent should not have been called') mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def test_get_upgrade_op(self): """ Test that the ``get_upgrade_op`` function creates a MigrationContext and an Operations object """ # GIVEN: Mocked out alembic classes and a mocked out SQLAlchemy session object with patch('openlp.core.lib.db.MigrationContext') as MockedMigrationContext, \ patch('openlp.core.lib.db.Operations') as MockedOperations: mocked_context = MagicMock() mocked_op = MagicMock() mocked_connection = MagicMock() MockedMigrationContext.configure.return_value = mocked_context MockedOperations.return_value = mocked_op mocked_session = MagicMock() mocked_session.bind.connect.return_value = mocked_connection # WHEN: get_upgrade_op is executed with the mocked session object op = get_upgrade_op(mocked_session) # THEN: The op object should be mocked_op, and the correction function calls should have been made self.assertIs(op, mocked_op, 'The return value should be the mocked object') mocked_session.bind.connect.assert_called_with() MockedMigrationContext.configure.assert_called_with( mocked_connection) MockedOperations.assert_called_with(mocked_context)
def test_get_html_tags_with_user_tags(self): """ FormattingTags class - test the get_html_tags(), add_html_tags() and remove_html_tag() methods. """ with patch('openlp.core.lib.translate') as mocked_translate, \ patch('openlp.core.common.settings') as mocked_settings, \ patch('openlp.core.lib.formattingtags.json') as mocked_json: # GIVEN: Our mocked modules and functions. mocked_translate.side_effect = lambda module, string_to_translate: string_to_translate mocked_settings.value.return_value = '' mocked_json.loads.side_effect = [[], [TAG]] # WHEN: Get the display tags. FormattingTags.load_tags() old_tags_list = copy.deepcopy(FormattingTags.get_html_tags()) # WHEN: Add our tag and get the tags again. FormattingTags.load_tags() FormattingTags.add_html_tags([TAG]) new_tags_list = copy.deepcopy(FormattingTags.get_html_tags()) # THEN: Lists should not be identical. assert old_tags_list != new_tags_list, 'The lists should be different.' # THEN: Added tag and last tag should be the same. new_tag = new_tags_list.pop() assert TAG == new_tag, 'Tags should be identical.' # WHEN: Remove the new tag. FormattingTags.remove_html_tag(len(new_tags_list)) # THEN: The lists should now be identical. assert old_tags_list == FormattingTags.get_html_tags(), 'The lists should be identical.'
def test_select_image_file_dialog_cancelled(self): """ Test the select image file dialog when the user presses cancel """ # GIVEN: An instance of Theme Form and mocked QFileDialog which returns an empty string (similating a user # pressing cancel) with patch('openlp.core.ui.ThemeForm._setup'),\ patch('openlp.core.ui.themeform.get_images_filter', **{'return_value': 'Image Files (*.bmp; *.gif)(*.bmp *.gif)'}),\ patch('openlp.core.ui.themeform.QtWidgets.QFileDialog.getOpenFileName', **{'return_value': ('', '')}) as mocked_get_open_file_name,\ patch('openlp.core.ui.themeform.translate', **{'return_value': 'Translated String'}),\ patch('openlp.core.ui.ThemeForm.set_background_page_values') as mocked_set_background_page_values: instance = ThemeForm(None) mocked_image_file_edit = MagicMock() mocked_image_file_edit.text.return_value = '/original_path/file.ext' instance.image_file_edit = mocked_image_file_edit # WHEN: on_image_browse_button is clicked instance.on_image_browse_button_clicked() # THEN: The QFileDialog getOpenFileName and set_background_page_values moethods should have been called # with known arguments mocked_get_open_file_name.assert_called_once_with(instance, 'Translated String', '/original_path/file.ext', 'Image Files (*.bmp; *.gif)(*.bmp *.gif);;' 'All Files (*.*)') mocked_set_background_page_values.assert_called_once_with()
def test_get_titles_and_notes(self): """ Test PresentationDocument.get_titles_and_notes method """ # GIVEN: A mocked open, get_thumbnail_folder and exists with patch('builtins.open', mock_open(read_data='uno\ndos\n')) as mocked_open, \ patch(FOLDER_TO_PATCH) as mocked_get_thumbnail_folder, \ patch('openlp.plugins.presentations.lib.presentationcontroller.os.path.exists') as mocked_exists: mocked_get_thumbnail_folder.return_value = 'test' mocked_exists.return_value = True # WHEN: calling get_titles_and_notes result_titles, result_notes = self.document.get_titles_and_notes() # THEN: it should return two items for the titles and two empty strings for the notes self.assertIs(type(result_titles), list, 'result_titles should be of type list') self.assertEqual(len(result_titles), 2, 'There should be two items in the titles') self.assertIs(type(result_notes), list, 'result_notes should be of type list') self.assertEqual(len(result_notes), 2, 'There should be two items in the notes') self.assertEqual(mocked_open.call_count, 3, 'Three files should be opened') mocked_open.assert_any_call(os.path.join('test', 'titles.txt'), encoding='utf-8') mocked_open.assert_any_call(os.path.join('test', 'slideNotes1.txt'), encoding='utf-8') mocked_open.assert_any_call(os.path.join('test', 'slideNotes2.txt'), encoding='utf-8') self.assertEqual(mocked_exists.call_count, 3, 'Three files should have been checked')
def get_titles_and_notes_test(self): """ Test PresentationDocument.get_titles_and_notes method """ # GIVEN: A mocked open, get_thumbnail_folder and exists with patch('builtins.open', mock_open(read_data='uno\ndos\n')) as mocked_open, \ patch(FOLDER_TO_PATCH) as mocked_get_thumbnail_folder, \ patch('openlp.plugins.presentations.lib.presentationcontroller.os.path.exists') as mocked_exists: mocked_get_thumbnail_folder.return_value = 'test' mocked_exists.return_value = True # WHEN: calling get_titles_and_notes result_titles, result_notes = self.document.get_titles_and_notes() # THEN: it should return two items for the titles and two empty strings for the notes self.assertIs(type(result_titles), list, 'result_titles should be of type list') self.assertEqual(len(result_titles), 2, 'There should be two items in the titles') self.assertIs(type(result_notes), list, 'result_notes should be of type list') self.assertEqual(len(result_notes), 2, 'There should be two items in the notes') self.assertEqual(mocked_open.call_count, 3, 'Three files should be opened') mocked_open.assert_any_call(os.path.join('test', 'titles.txt'), encoding='utf-8') mocked_open.assert_any_call(os.path.join('test', 'slideNotes1.txt'), encoding='utf-8') mocked_open.assert_any_call(os.path.join('test', 'slideNotes2.txt'), encoding='utf-8') self.assertEqual(mocked_exists.call_count, 3, 'Three files should have been checked')
def test_get_web_page_with_user_agent_in_headers(self): """ Test that adding a user agent in the header when calling get_web_page() adds that user agent to the request """ with patch('openlp.core.lib.webpagereader.urllib.request.Request') as MockRequest, \ patch('openlp.core.lib.webpagereader.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.lib.webpagereader._get_user_agent') as mock_get_user_agent: # GIVEN: Mocked out objects, a fake URL and a fake header mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object fake_url = 'this://is.a.fake/url' user_agent_header = ('User-Agent', 'OpenLP/2.2.0') # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url, header=user_agent_header) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with( user_agent_header[0], user_agent_header[1]) self.assertEqual(1, mocked_request_object.add_header.call_count, 'There should only be 1 call to add_header') self.assertEqual(0, mock_get_user_agent.call_count, '_get_user_agent should not have been called') mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def test_get_web_page_update_openlp(self): """ Test that passing "update_openlp" as true to get_web_page calls Registry().get('app').process_events() """ with patch('openlp.core.lib.webpagereader.urllib.request.Request') as MockRequest, \ patch('openlp.core.lib.webpagereader.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.lib.webpagereader._get_user_agent') as mock_get_user_agent, \ patch('openlp.core.lib.webpagereader.Registry') as MockRegistry: # GIVEN: Mocked out objects, a fake URL mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object mock_get_user_agent.return_value = 'user_agent' mocked_registry_object = MagicMock() mocked_application_object = MagicMock() mocked_registry_object.get.return_value = mocked_application_object MockRegistry.return_value = mocked_registry_object fake_url = 'this://is.a.fake/url' # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url, update_openlp=True) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with( 'User-Agent', 'user_agent') self.assertEqual(1, mocked_request_object.add_header.call_count, 'There should only be 1 call to add_header') mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() mocked_registry_object.get.assert_called_with('application') mocked_application_object.process_events.assert_called_with() self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def set_basic_urls_test(self): """ Test the set_urls function with standard defaults """ # GIVEN: A mocked location with patch('openlp.core.common.Settings') as mocked_class, \ patch('openlp.core.utils.AppLocation.get_directory') as mocked_get_directory, \ patch('openlp.core.common.check_directory_exists') as mocked_check_directory_exists, \ patch('openlp.core.common.applocation.os') as mocked_os: # GIVEN: A mocked out Settings class and a mocked out AppLocation.get_directory() mocked_settings = mocked_class.return_value mocked_settings.contains.return_value = False mocked_get_directory.return_value = 'test/dir' mocked_check_directory_exists.return_value = True mocked_os.path.normpath.return_value = 'test/dir' # WHEN: when the set_urls is called having reloaded the form. self.form.load() self.form.set_urls() # THEN: the following screen values should be set self.assertEqual(self.form.address_edit.text(), ZERO_URL, 'The default URL should be set on the screen') self.assertEqual(self.form.https_settings_group_box.isEnabled(), False, 'The Https box should not be enabled') self.assertEqual(self.form.https_settings_group_box.isChecked(), False, 'The Https checked box should note be Checked') self.assertEqual(self.form.user_login_group_box.isChecked(), False, 'The authentication box should not be enabled')
def setUp(self): self.test_file = BytesIO( b'<?xml version="1.0" encoding="UTF-8" ?>\n' b'<root>\n' b' <data><div>Test<p>data</p><a>to</a>keep</div></data>\n' b' <data><unsupported>Test<x>data</x><y>to</y>discard</unsupported></data>\n' b'</root>') self.open_patcher = patch('builtins.open') self.addCleanup(self.open_patcher.stop) self.mocked_open = self.open_patcher.start() self.critical_error_message_box_patcher = \ patch('openlp.plugins.bibles.lib.bibleimport.critical_error_message_box') self.addCleanup(self.critical_error_message_box_patcher.stop) self.mocked_critical_error_message_box = self.critical_error_message_box_patcher.start( ) self.setup_patcher = patch( 'openlp.plugins.bibles.lib.db.BibleDB._setup') self.addCleanup(self.setup_patcher.stop) self.setup_patcher.start() self.translate_patcher = patch( 'openlp.plugins.bibles.lib.bibleimport.translate', side_effect=lambda module, string_to_translate, *args: string_to_translate) self.addCleanup(self.translate_patcher.stop) self.mocked_translate = self.translate_patcher.start() self.registry_patcher = patch( 'openlp.plugins.bibles.lib.bibleimport.Registry') self.addCleanup(self.registry_patcher.stop) self.registry_patcher.start()
def test_display_results_cclinumber(self): """ Test displaying song search results sorted by CCLI number with basic song """ # GIVEN: Search results sorted by CCLI number, plus a mocked QtListWidgetItem with patch('openlp.core.lib.QtWidgets.QListWidgetItem') as MockedQListWidgetItem, \ patch('openlp.core.lib.QtCore.Qt.UserRole') as MockedUserRole: mock_search_results = [] mock_song = MagicMock() mock_song_temp = MagicMock() mock_song.id = 1 mock_song.title = 'My Song' mock_song.sort_key = 'My Song' mock_song.ccli_number = '12345' mock_song.temporary = False mock_song_temp.id = 2 mock_song_temp.title = 'My Temporary' mock_song_temp.sort_key = 'My Temporary' mock_song_temp.ccli_number = '12346' mock_song_temp.temporary = True mock_search_results.append(mock_song) mock_search_results.append(mock_song_temp) mock_qlist_widget = MagicMock() MockedQListWidgetItem.return_value = mock_qlist_widget # WHEN: I display song search results sorted by CCLI number self.media_item.display_results_cclinumber(mock_search_results) # THEN: The current list view is cleared, the widget is created, and the relevant attributes set self.media_item.list_view.clear.assert_called_with() MockedQListWidgetItem.assert_called_once_with('12345 (My Song)') mock_qlist_widget.setData.assert_called_once_with(MockedUserRole, mock_song.id) self.media_item.list_view.addItem.assert_called_once_with(mock_qlist_widget)
def process_chapters_verse_in_chapter_verse_milestone_test(self): """ Test process_chapters when supplied with an etree element with a verse element nested, when the verse system is based on milestones """ with patch('openlp.plugins.bibles.lib.importers.osis.verse_in_chapter', return_value=True), \ patch('openlp.plugins.bibles.lib.importers.osis.text_in_verse', return_value=False), \ patch.object(OSISBible, 'set_current_chapter') as mocked_set_current_chapter, \ patch.object(OSISBible, 'process_verse') as mocked_process_verse: # GIVEN: Some test data and an instance of OSISBible test_book = MagicMock() test_verse = MagicMock() test_verse.tail = '\n ' # Whitespace test_verse.text = 'Verse Text' test_chapter = MagicMock() test_chapter.__iter__.return_value = [test_verse] test_chapter.get.side_effect = lambda x: { 'osisID': '1.2.4', 'sID': '999' }.get(x) importer = OSISBible(MagicMock(), path='.', name='.', filename='') # WHEN: Calling process_chapters importer.process_chapters(test_book, [test_chapter]) # THEN: set_current_chapter and process_verse should have been called with the test data mocked_set_current_chapter.assert_called_once_with( test_book.name, 2) mocked_process_verse.assert_called_once_with(test_book, 2, test_verse, use_milestones=True)
def test_init_db_calls_correct_functions(self): """ Test that the init_db function makes the correct function calls """ # GIVEN: Mocked out SQLAlchemy calls and return objects, and an in-memory SQLite database URL with patch('openlp.core.lib.db.create_engine') as mocked_create_engine, \ patch('openlp.core.lib.db.MetaData') as MockedMetaData, \ patch('openlp.core.lib.db.sessionmaker') as mocked_sessionmaker, \ patch('openlp.core.lib.db.scoped_session') as mocked_scoped_session: mocked_engine = MagicMock() mocked_metadata = MagicMock() mocked_sessionmaker_object = MagicMock() mocked_scoped_session_object = MagicMock() mocked_create_engine.return_value = mocked_engine MockedMetaData.return_value = mocked_metadata mocked_sessionmaker.return_value = mocked_sessionmaker_object mocked_scoped_session.return_value = mocked_scoped_session_object db_url = 'sqlite://' # WHEN: We try to initialise the db session, metadata = init_db(db_url) # THEN: We should see the correct function calls mocked_create_engine.assert_called_with(db_url, poolclass=NullPool) MockedMetaData.assert_called_with(bind=mocked_engine) mocked_sessionmaker.assert_called_with(autoflush=True, autocommit=False, bind=mocked_engine) mocked_scoped_session.assert_called_with( mocked_sessionmaker_object) self.assertIs(session, mocked_scoped_session_object, 'The ``session`` object should be the mock') self.assertIs(metadata, mocked_metadata, 'The ``metadata`` object should be the mock')
def test_backup_on_upgrade(self): """ Test that we try to backup on a new install """ # GIVEN: Mocked data version and OpenLP version which are different old_install = True MOCKED_VERSION = { 'full': '2.2.0-bzr000', 'version': '2.2.0', 'build': 'bzr000' } Settings().setValue('core/application version', '2.0.5') self.openlp.splash = MagicMock() self.openlp.splash.isVisible.return_value = True with patch('openlp.core.get_application_version') as mocked_get_application_version,\ patch('openlp.core.QtWidgets.QMessageBox.question') as mocked_question: mocked_get_application_version.return_value = MOCKED_VERSION mocked_question.return_value = QtWidgets.QMessageBox.No # WHEN: We check if a backup should be created self.openlp.backup_on_upgrade(old_install, True) # THEN: It should ask if we want to create a backup self.assertEqual(Settings().value('core/application version'), '2.2.0', 'Version should be upgraded!') self.assertEqual(mocked_question.call_count, 1, 'A question should have been asked!') self.openlp.splash.hide.assert_called_once_with() self.openlp.splash.show.assert_called_once_with()
def paint_event_text_doesnt_fit_test(self): """ Test the paintEvent method when text fits the label """ font = QtGui.QFont() metrics = QtGui.QFontMetrics(font) with patch('openlp.core.ui.slidecontroller.QtGui.QLabel'), \ patch('openlp.core.ui.slidecontroller.QtGui.QPainter') as mocked_qpainter: # GIVEN: An instance of InfoLabel, with mocked text return, width and rect methods info_label = InfoLabel() test_string = 'Label Text' mocked_rect = MagicMock() mocked_text = MagicMock() mocked_width = MagicMock() mocked_text.return_value = test_string info_label.rect = mocked_rect info_label.text = mocked_text info_label.width = mocked_width # WHEN: The instance is narrower than its text, and the paintEvent method is called label_width = metrics.boundingRect(test_string).width() - 10 info_label.width.return_value = label_width info_label.paintEvent(MagicMock()) # THEN: The text should be drawn aligned left with an elided test_string elided_test_string = metrics.elidedText(test_string, QtCore.Qt.ElideRight, label_width) mocked_qpainter().drawText.assert_called_once_with(mocked_rect(), QtCore.Qt.AlignLeft, elided_test_string)
def paint_event_text_fits_test(self): """ Test the paintEvent method when text fits the label """ font = QtGui.QFont() metrics = QtGui.QFontMetrics(font) with patch('openlp.core.ui.slidecontroller.QtGui.QLabel'), \ patch('openlp.core.ui.slidecontroller.QtGui.QPainter') as mocked_qpainter: # GIVEN: An instance of InfoLabel, with mocked text return, width and rect methods info_label = InfoLabel() test_string = 'Label Text' mocked_rect = MagicMock() mocked_text = MagicMock() mocked_width = MagicMock() mocked_text.return_value = test_string info_label.rect = mocked_rect info_label.text = mocked_text info_label.width = mocked_width # WHEN: The instance is wider than its text, and the paintEvent method is called info_label.width.return_value = metrics.boundingRect(test_string).width() + 10 info_label.paintEvent(MagicMock()) # THEN: The text should be drawn centered with the complete test_string mocked_qpainter().drawText.assert_called_once_with(mocked_rect(), QtCore.Qt.AlignCenter, test_string)
def setUp(self): self.test_file = BytesIO( b'<?xml version="1.0" encoding="UTF-8" ?>\n' b'<root>\n' b' <data><div>Test<p>data</p><a>to</a>keep</div></data>\n' b' <data><unsupported>Test<x>data</x><y>to</y>discard</unsupported></data>\n' b'</root>' ) self.open_patcher = patch('builtins.open') self.addCleanup(self.open_patcher.stop) self.mocked_open = self.open_patcher.start() self.critical_error_message_box_patcher = \ patch('openlp.plugins.bibles.lib.bibleimport.critical_error_message_box') self.addCleanup(self.critical_error_message_box_patcher.stop) self.mocked_critical_error_message_box = self.critical_error_message_box_patcher.start() self.setup_patcher = patch('openlp.plugins.bibles.lib.db.BibleDB._setup') self.addCleanup(self.setup_patcher.stop) self.setup_patcher.start() self.translate_patcher = patch('openlp.plugins.bibles.lib.bibleimport.translate', side_effect=lambda module, string_to_translate, *args: string_to_translate) self.addCleanup(self.translate_patcher.stop) self.mocked_translate = self.translate_patcher.start() self.registry_patcher = patch('openlp.plugins.bibles.lib.bibleimport.Registry') self.addCleanup(self.registry_patcher.stop) self.registry_patcher.start()
def parse_csv_file_test(self): """ Test the parse_csv_file() with sample data """ # GIVEN: A mocked csv.reader which returns an iterator with test data test_data = [['1', 'Line 1', 'Data 1'], ['2', 'Line 2', 'Data 2'], ['3', 'Line 3', 'Data 3']] TestTuple = namedtuple('TestTuple', 'line_no line_description line_data') with patch('openlp.plugins.bibles.lib.importers.csvbible.get_file_encoding', return_value={'encoding': 'utf-8', 'confidence': 0.99}),\ patch('openlp.plugins.bibles.lib.importers.csvbible.open', create=True) as mocked_open,\ patch('openlp.plugins.bibles.lib.importers.csvbible.csv.reader', return_value=iter(test_data)) as mocked_reader: # WHEN: Calling the CSVBible parse_csv_file method with a file name and TestTuple result = CSVBible.parse_csv_file('file.csv', TestTuple) # THEN: A list of TestTuple instances with the parsed data should be returned self.assertEqual(result, [ TestTuple('1', 'Line 1', 'Data 1'), TestTuple('2', 'Line 2', 'Data 2'), TestTuple('3', 'Line 3', 'Data 3') ]) mocked_open.assert_called_once_with('file.csv', 'r', encoding='utf-8', newline='') mocked_reader.assert_called_once_with(ANY, delimiter=',', quotechar='"')
def test_get_data_path(self): """ Test the AppLocation.get_data_path() method """ with patch('openlp.core.common.applocation.Settings') as mocked_class, \ patch('openlp.core.common.AppLocation.get_directory') as mocked_get_directory, \ patch('openlp.core.common.applocation.check_directory_exists') as mocked_check_directory_exists, \ patch('openlp.core.common.applocation.os') as mocked_os: # GIVEN: A mocked out Settings class and a mocked out AppLocation.get_directory() mocked_settings = mocked_class.return_value mocked_settings.contains.return_value = False mocked_get_directory.return_value = os.path.join('test', 'dir') mocked_check_directory_exists.return_value = True mocked_os.path.normpath.return_value = os.path.join('test', 'dir') # WHEN: we call AppLocation.get_data_path() data_path = AppLocation.get_data_path() # THEN: check that all the correct methods were called, and the result is correct mocked_settings.contains.assert_called_with('advanced/data path') mocked_get_directory.assert_called_with(AppLocation.DataDir) mocked_check_directory_exists.assert_called_with( os.path.join('test', 'dir')) self.assertEqual(os.path.join('test', 'dir'), data_path, 'Result should be "test/dir"')
def process_books_test(self): """ Test process books when it completes successfully """ # GIVEN: An instance of CSVBible with the stop_import_flag set to False, and some sample data mocked_manager = MagicMock() with patch('openlp.plugins.bibles.lib.db.BibleDB._setup'),\ patch('openlp.plugins.bibles.lib.importers.csvbible.translate'): importer = CSVBible(mocked_manager, path='.', name='.', booksfile='books.csv', versefile='verse.csv') importer.find_and_create_book = MagicMock() importer.language_id = 10 importer.stop_import_flag = False importer.wizard = MagicMock() books = [ Book('1', '1', '1. Mosebog', '1Mos'), Book('2', '1', '2. Mosebog', '2Mos') ] # WHEN: Calling process_books result = importer.process_books(books) # THEN: translate and find_and_create_book should have been called with both book names. # The returned data should be a dictionary with both song's id and names. self.assertEqual( importer.find_and_create_book.mock_calls, [call('1. Mosebog', 2, 10), call('2. Mosebog', 2, 10)]) self.assertDictEqual(result, {1: '1. Mosebog', 2: '2. Mosebog'})
def setUp(self): """ Mock out stuff for all the tests """ # Mock self.parent().width() self.parent_patcher = patch('openlp.core.ui.lib.listpreviewwidget.ListPreviewWidget.parent') self.mocked_parent = self.parent_patcher.start() self.mocked_parent.width.return_value = 100 self.addCleanup(self.parent_patcher.stop) # Mock Settings().value() self.Settings_patcher = patch('openlp.core.ui.lib.listpreviewwidget.Settings') self.mocked_Settings = self.Settings_patcher.start() self.mocked_Settings_obj = MagicMock() self.mocked_Settings_obj.value.return_value = None self.mocked_Settings.return_value = self.mocked_Settings_obj self.addCleanup(self.Settings_patcher.stop) # Mock self.viewport().width() self.viewport_patcher = patch('openlp.core.ui.lib.listpreviewwidget.ListPreviewWidget.viewport') self.mocked_viewport = self.viewport_patcher.start() self.mocked_viewport_obj = MagicMock() self.mocked_viewport_obj.width.return_value = 200 self.mocked_viewport.return_value = self.mocked_viewport_obj self.addCleanup(self.viewport_patcher.stop)
def select_image_file_dialog_new_file_test(self): """ Test the select image file dialog when the user presses ok """ # GIVEN: An instance of Theme Form and mocked QFileDialog which returns a file path with patch('openlp.core.ui.ThemeForm._setup'),\ patch('openlp.core.ui.themeform.get_images_filter', **{'return_value': 'Image Files (*.bmp; *.gif)(*.bmp *.gif)'}),\ patch('openlp.core.ui.themeform.QtGui.QFileDialog.getOpenFileName', **{'return_value': '/new_path/file.ext'}) as mocked_get_open_file_name,\ patch('openlp.core.ui.themeform.translate', **{'return_value': 'Translated String'}),\ patch('openlp.core.ui.ThemeForm.set_background_page_values') as mocked_background_page_values: instance = ThemeForm(None) mocked_image_file_edit = MagicMock() mocked_image_file_edit.text.return_value = '/original_path/file.ext' instance.image_file_edit = mocked_image_file_edit instance.theme = MagicMock() # WHEN: on_image_browse_button is clicked instance.on_image_browse_button_clicked() # THEN: The QFileDialog getOpenFileName and set_background_page_values moethods should have been called # with known arguments and theme.background_filename should be set mocked_get_open_file_name.assert_called_once_with(instance, 'Translated String', '/original_path/file.ext', 'Image Files (*.bmp; *.gif)(*.bmp *.gif);;' 'All Files (*.*)') self.assertEqual(instance.theme.background_filename, '/new_path/file.ext', 'theme.background_filename should be set to the path that the file dialog returns') mocked_background_page_values.assert_called_once_with()
def build_html_test(self): """ Test the build_html() function """ # GIVEN: Mocked arguments and function. with patch('openlp.core.lib.htmlbuilder.build_background_css') as mocked_build_background_css, \ patch('openlp.core.lib.htmlbuilder.build_footer_css') as mocked_build_footer_css, \ patch('openlp.core.lib.htmlbuilder.build_lyrics_css') as mocked_build_lyrics_css: # Mocked function. mocked_build_background_css.return_value = '' mocked_build_footer_css.return_value = 'dummy: dummy;' mocked_build_lyrics_css.return_value = '' # Mocked arguments. item = MagicMock() item.bg_image_bytes = None screen = MagicMock() is_live = False background = None plugin = MagicMock() plugin.get_display_css.return_value = 'plugin CSS' plugin.get_display_javascript.return_value = 'plugin JS' plugin.get_display_html.return_value = 'plugin HTML' plugins = [plugin] # WHEN: Create the html. html = build_html(item, screen, is_live, background, plugins=plugins) # THEN: The returned html should match. self.assertEqual(html, HTML, 'The returned html should match')
def setUp(self): self.registry_patcher = patch('openlp.plugins.bibles.lib.bibleimport.Registry') self.addCleanup(self.registry_patcher.stop) self.registry_patcher.start() self.manager_patcher = patch('openlp.plugins.bibles.lib.db.Manager') self.addCleanup(self.manager_patcher.stop) self.manager_patcher.start()
def do_import_memo_validty_test(self): """ Test the :mod:`do_import` module handles invalid memo files correctly """ # GIVEN: A mocked out SongImport class, a mocked out "manager" with patch('openlp.plugins.songs.lib.importers.easyworship.SongImport'), \ patch('openlp.plugins.songs.lib.importers.easyworship.os.path') as mocked_os_path, \ patch('builtins.open') as mocked_open, \ patch('openlp.plugins.songs.lib.importers.easyworship.struct') as mocked_struct: mocked_manager = MagicMock() importer = EasyWorshipSongImport(mocked_manager, filenames=[]) mocked_os_path.isfile.return_value = True mocked_os_path.getsize.return_value = 0x800 importer.import_source = 'Songs.DB' # WHEN: Unpacking first 35 bytes of Memo file struct_unpack_return_values = [(0, 0x700, 2, 0, 0), (0, 0x800, 0, 0, 0), (0, 0x800, 5, 0, 0)] mocked_struct.unpack.side_effect = struct_unpack_return_values # THEN: do_import should return None having called closed the open files db and memo files. for effect in struct_unpack_return_values: self.assertIsNone(importer.do_import(), 'do_import should return None when db_size is less than 0x800') self.assertEqual(mocked_open().close.call_count, 2, 'The open db and memo files should have been closed') mocked_open().close.reset_mock() self.assertIs(mocked_open().seek.called, False, 'db_file.seek should not have been called.')
def test_get_web_page_with_header(self): """ Test that adding a header to the call to get_web_page() adds the header to the request """ with patch('openlp.core.common.httputils.urllib.request.Request') as MockRequest, \ patch('openlp.core.common.httputils.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.common.httputils.get_user_agent') as mock_get_user_agent: # GIVEN: Mocked out objects, a fake URL and a fake header mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object mock_get_user_agent.return_value = 'user_agent' fake_url = 'this://is.a.fake/url' fake_header = ('Fake-Header', 'fake value') # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url, header=fake_header) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with(fake_header[0], fake_header[1]) self.assertEqual(2, mocked_request_object.add_header.call_count, 'There should only be 2 calls to add_header') mock_get_user_agent.assert_called_with() mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def code_page_to_encoding_test(self): """ Test the :mod:`do_import` converts the code page to the encoding correctly """ # GIVEN: A mocked out SongImport class, a mocked out "manager" with patch('openlp.plugins.songs.lib.importers.easyworship.SongImport'), \ patch('openlp.plugins.songs.lib.importers.easyworship.os.path') as mocked_os_path, \ patch('builtins.open'), patch('openlp.plugins.songs.lib.importers.easyworship.struct') as mocked_struct, \ patch('openlp.plugins.songs.lib.importers.easyworship.retrieve_windows_encoding') as \ mocked_retrieve_windows_encoding: mocked_manager = MagicMock() importer = EasyWorshipSongImport(mocked_manager, filenames=[]) mocked_os_path.isfile.return_value = True mocked_os_path.getsize.return_value = 0x800 importer.import_source = 'Songs.DB' # WHEN: Unpacking the code page for code_page, encoding in CODE_PAGE_MAPPINGS: struct_unpack_return_values = [(0, 0x800, 2, 0, 0), (code_page, )] mocked_struct.unpack.side_effect = struct_unpack_return_values mocked_retrieve_windows_encoding.return_value = False # THEN: do_import should return None having called retrieve_windows_encoding with the correct encoding. self.assertIsNone(importer.do_import(), 'do_import should return None when db_size is less than 0x800') mocked_retrieve_windows_encoding.assert_call(encoding)
def write_theme_same_image_test(self): """ Test that we don't try to overwrite a theme background image with itself """ # GIVEN: A new theme manager instance, with mocked builtins.open, shutil.copyfile, # theme, check_directory_exists and thememanager-attributes. with patch('builtins.open') as mocked_open, \ patch('openlp.core.ui.thememanager.shutil.copyfile') as mocked_copyfile, \ patch('openlp.core.ui.thememanager.check_directory_exists') as mocked_check_directory_exists: mocked_open.return_value = MagicMock() theme_manager = ThemeManager(None) theme_manager.old_background_image = None theme_manager.generate_and_save_image = MagicMock() theme_manager.path = '' mocked_theme = MagicMock() mocked_theme.theme_name = 'themename' mocked_theme.extract_formatted_xml = MagicMock() mocked_theme.extract_formatted_xml.return_value = 'fake_theme_xml'.encode( ) # WHEN: Calling _write_theme with path to the same image, but the path written slightly different file_name1 = os.path.join(TEST_RESOURCES_PATH, 'church.jpg') # Do replacement from end of string to avoid problems with path start file_name2 = file_name1[::-1].replace(os.sep, os.sep + os.sep, 2)[::-1] theme_manager._write_theme(mocked_theme, file_name1, file_name2) # THEN: The mocked_copyfile should not have been called self.assertFalse(mocked_copyfile.called, 'shutil.copyfile should not be called')
def test_backup_on_upgrade_first_install(self): """ Test that we don't try to backup on a new install """ # GIVEN: Mocked data version and OpenLP version which are the same old_install = False MOCKED_VERSION = { 'full': '2.2.0-bzr000', 'version': '2.2.0', 'build': 'bzr000' } Settings().setValue('core/application version', '2.2.0') with patch('openlp.core.get_application_version') as mocked_get_application_version,\ patch('openlp.core.QtWidgets.QMessageBox.question') as mocked_question: mocked_get_application_version.return_value = MOCKED_VERSION mocked_question.return_value = QtWidgets.QMessageBox.No # WHEN: We check if a backup should be created self.openlp.backup_on_upgrade(old_install) # THEN: It should not ask if we want to create a backup self.assertEqual(Settings().value('core/application version'), '2.2.0', 'Version should be the same!') self.assertEqual(mocked_question.call_count, 0, 'No question should have been asked!')
def test_do_import_memo_validty(self): """ Test the :mod:`do_import` module handles invalid memo files correctly """ # GIVEN: A mocked out SongImport class, a mocked out "manager" with patch('openlp.plugins.songs.lib.importers.easyworship.SongImport'), \ patch('openlp.plugins.songs.lib.importers.easyworship.os.path') as mocked_os_path, \ patch('builtins.open') as mocked_open, \ patch('openlp.plugins.songs.lib.importers.easyworship.struct') as mocked_struct: mocked_manager = MagicMock() importer = EasyWorshipSongImport(mocked_manager, filenames=[]) mocked_os_path.isfile.return_value = True mocked_os_path.getsize.return_value = 0x800 importer.import_source = 'Songs.DB' # WHEN: Unpacking first 35 bytes of Memo file struct_unpack_return_values = [(0, 0x700, 2, 0, 0), (0, 0x800, 0, 0, 0), (0, 0x800, 5, 0, 0)] mocked_struct.unpack.side_effect = struct_unpack_return_values # THEN: do_import should return None having called closed the open files db and memo files. for effect in struct_unpack_return_values: self.assertIsNone(importer.do_import(), 'do_import should return None when db_size is less than 0x800') self.assertEqual(mocked_open().close.call_count, 2, 'The open db and memo files should have been closed') mocked_open().close.reset_mock() self.assertIs(mocked_open().seek.called, False, 'db_file.seek should not have been called.')
def test_check_file_type_no_players(self): """ Test that we don't try to play media when no players available """ # GIVEN: A mocked UiStrings, get_used_players, controller, display and service_item with patch('openlp.core.ui.media.mediacontroller.MediaController._get_used_players') as \ mocked_get_used_players,\ patch('openlp.core.ui.media.mediacontroller.UiStrings') as mocked_uistrings: mocked_get_used_players.return_value = ([]) mocked_ret_uistrings = MagicMock() mocked_ret_uistrings.Automatic = 1 mocked_uistrings.return_value = mocked_ret_uistrings media_controller = MediaController() mocked_controller = MagicMock() mocked_display = MagicMock() mocked_service_item = MagicMock() mocked_service_item.processor = 1 # WHEN: calling _check_file_type when no players exists ret = media_controller._check_file_type(mocked_controller, mocked_display, mocked_service_item) # THEN: it should return False self.assertFalse( ret, '_check_file_type should return False when no mediaplayers are available.' )
def test_code_page_to_encoding(self): """ Test the :mod:`do_import` converts the code page to the encoding correctly """ # GIVEN: A mocked out SongImport class, a mocked out "manager" with patch('openlp.plugins.songs.lib.importers.easyworship.SongImport'), \ patch('openlp.plugins.songs.lib.importers.easyworship.os.path') as mocked_os_path, \ patch('builtins.open'), patch('openlp.plugins.songs.lib.importers.easyworship.struct') as mocked_struct, \ patch('openlp.plugins.songs.lib.importers.easyworship.retrieve_windows_encoding') as \ mocked_retrieve_windows_encoding: mocked_manager = MagicMock() importer = EasyWorshipSongImport(mocked_manager, filenames=[]) mocked_os_path.isfile.return_value = True mocked_os_path.getsize.return_value = 0x800 importer.import_source = 'Songs.DB' # WHEN: Unpacking the code page for code_page, encoding in CODE_PAGE_MAPPINGS: struct_unpack_return_values = [(0, 0x800, 2, 0, 0), (code_page, )] mocked_struct.unpack.side_effect = struct_unpack_return_values mocked_retrieve_windows_encoding.return_value = False # THEN: do_import should return None having called retrieve_windows_encoding with the correct encoding. self.assertIsNone(importer.do_import(), 'do_import should return None when db_size is less than 0x800') mocked_retrieve_windows_encoding.assert_any_call(encoding)
def setUp(self): """ Patch and set up the mocks required. """ Registry.create() self.add_copyright_patcher = patch( 'openlp.plugins.songs.lib.importers.%s.%s.add_copyright' % (self.importer_module_name, self.importer_class_name)) self.add_verse_patcher = patch( 'openlp.plugins.songs.lib.importers.%s.%s.add_verse' % (self.importer_module_name, self.importer_class_name)) self.finish_patcher = patch( 'openlp.plugins.songs.lib.importers.%s.%s.finish' % (self.importer_module_name, self.importer_class_name)) self.add_author_patcher = patch( 'openlp.plugins.songs.lib.importers.%s.%s.add_author' % (self.importer_module_name, self.importer_class_name)) self.song_import_patcher = patch( 'openlp.plugins.songs.lib.importers.%s.SongImport' % self.importer_module_name) self.mocked_add_copyright = self.add_copyright_patcher.start() self.mocked_add_verse = self.add_verse_patcher.start() self.mocked_finish = self.finish_patcher.start() self.mocked_add_author = self.add_author_patcher.start() self.mocked_song_importer = self.song_import_patcher.start() self.mocked_manager = MagicMock() self.mocked_import_wizard = MagicMock() self.mocked_finish.return_value = True
def setUp(self): """ Set up the patches and mocks need for all tests. """ self.setup_application() self.build_settings() self.mock_plugin = MagicMock() self.temp_folder = mkdtemp() self.mock_plugin.settings_section = self.temp_folder self.powerpoint_document_stop_presentation_patcher = patch( 'openlp.plugins.presentations.lib.powerpointcontroller.PowerpointDocument.stop_presentation' ) self.presentation_document_get_temp_folder_patcher = patch( 'openlp.plugins.presentations.lib.powerpointcontroller.PresentationDocument.get_temp_folder' ) self.presentation_document_setup_patcher = patch( 'openlp.plugins.presentations.lib.powerpointcontroller.PresentationDocument._setup' ) self.mock_powerpoint_document_stop_presentation = self.powerpoint_document_stop_presentation_patcher.start( ) self.mock_presentation_document_get_temp_folder = self.presentation_document_get_temp_folder_patcher.start( ) self.mock_presentation_document_setup = self.presentation_document_setup_patcher.start( ) self.mock_controller = MagicMock() self.mock_presentation = MagicMock() self.mock_presentation_document_get_temp_folder.return_value = 'temp folder' self.file_name = os.path.join(TEST_RESOURCES_PATH, 'presentations', 'test.pptx') self.real_controller = PowerpointController(self.mock_plugin) Settings().extend_default_settings(__default_settings__)
def write_theme_diff_images_test(self): """ Test that we do overwrite a theme background image when a new is submitted """ # GIVEN: A new theme manager instance, with mocked builtins.open, shutil.copyfile, # theme, check_directory_exists and thememanager-attributes. with patch('builtins.open') as mocked_open, \ patch('openlp.core.ui.thememanager.shutil.copyfile') as mocked_copyfile, \ patch('openlp.core.ui.thememanager.check_directory_exists') as mocked_check_directory_exists: mocked_open.return_value = MagicMock() theme_manager = ThemeManager(None) theme_manager.old_background_image = None theme_manager.generate_and_save_image = MagicMock() theme_manager.path = '' mocked_theme = MagicMock() mocked_theme.theme_name = 'themename' mocked_theme.extract_formatted_xml = MagicMock() mocked_theme.extract_formatted_xml.return_value = 'fake_theme_xml'.encode( ) # WHEN: Calling _write_theme with path to different images file_name1 = os.path.join(TEST_RESOURCES_PATH, 'church.jpg') file_name2 = os.path.join(TEST_RESOURCES_PATH, 'church2.jpg') theme_manager._write_theme(mocked_theme, file_name1, file_name2) # THEN: The mocked_copyfile should not have been called self.assertTrue(mocked_copyfile.called, 'shutil.copyfile should be called')
def pyodbc_exception_test(self): """ Test that exceptions raised by pyodbc are handled """ # GIVEN: A mocked out SongImport class, a mocked out pyodbc module, a mocked out translate method, # a mocked "manager" and a mocked out log_error method. with patch('openlp.plugins.songs.lib.importers.worshipcenterpro.SongImport'), \ patch('openlp.plugins.songs.lib.importers.worshipcenterpro.pyodbc.connect') as mocked_pyodbc_connect, \ patch('openlp.plugins.songs.lib.importers.worshipcenterpro.translate') as mocked_translate: mocked_manager = MagicMock() mocked_log_error = MagicMock() mocked_translate.return_value = 'Translated Text' importer = WorshipCenterProImport(mocked_manager, filenames=[]) importer.log_error = mocked_log_error importer.import_source = 'import_source' pyodbc_errors = [pyodbc.DatabaseError, pyodbc.IntegrityError, pyodbc.InternalError, pyodbc.OperationalError] mocked_pyodbc_connect.side_effect = pyodbc_errors # WHEN: Calling the do_import method for effect in pyodbc_errors: return_value = importer.do_import() # THEN: do_import should return None, and pyodbc, translate & log_error are called with known calls self.assertIsNone(return_value, 'do_import should return None when pyodbc raises an exception.') mocked_pyodbc_connect.assert_called_with('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=import_source') mocked_translate.assert_called_with('SongsPlugin.WorshipCenterProImport', 'Unable to connect the WorshipCenter Pro database.') mocked_log_error.assert_called_with('import_source', 'Translated Text')
def init_db_calls_correct_functions_test(self): """ Test that the init_db function makes the correct function calls """ # GIVEN: Mocked out SQLAlchemy calls and return objects, and an in-memory SQLite database URL with patch('openlp.core.lib.db.create_engine') as mocked_create_engine, \ patch('openlp.core.lib.db.MetaData') as MockedMetaData, \ patch('openlp.core.lib.db.sessionmaker') as mocked_sessionmaker, \ patch('openlp.core.lib.db.scoped_session') as mocked_scoped_session: mocked_engine = MagicMock() mocked_metadata = MagicMock() mocked_sessionmaker_object = MagicMock() mocked_scoped_session_object = MagicMock() mocked_create_engine.return_value = mocked_engine MockedMetaData.return_value = mocked_metadata mocked_sessionmaker.return_value = mocked_sessionmaker_object mocked_scoped_session.return_value = mocked_scoped_session_object db_url = 'sqlite://' # WHEN: We try to initialise the db session, metadata = init_db(db_url) # THEN: We should see the correct function calls mocked_create_engine.assert_called_with(db_url, poolclass=NullPool) MockedMetaData.assert_called_with(bind=mocked_engine) mocked_sessionmaker.assert_called_with(autoflush=True, autocommit=False, bind=mocked_engine) mocked_scoped_session.assert_called_with(mocked_sessionmaker_object) self.assertIs(session, mocked_scoped_session_object, 'The ``session`` object should be the mock') self.assertIs(metadata, mocked_metadata, 'The ``metadata`` object should be the mock')
def set_certificate_urls_test(self): """ Test the set_urls function with certificate available """ # GIVEN: A mocked location with patch('openlp.core.common.Settings') as mocked_class, \ patch('openlp.core.utils.AppLocation.get_directory') as mocked_get_directory, \ patch('openlp.core.common.check_directory_exists') as mocked_check_directory_exists, \ patch('openlp.core.common.applocation.os') as mocked_os: # GIVEN: A mocked out Settings class and a mocked out AppLocation.get_directory() mocked_settings = mocked_class.return_value mocked_settings.contains.return_value = False mocked_get_directory.return_value = TEST_PATH mocked_check_directory_exists.return_value = True mocked_os.path.normpath.return_value = TEST_PATH # WHEN: when the set_urls is called having reloaded the form. self.form.load() self.form.set_urls() # THEN: the following screen values should be set self.assertEqual(self.form.http_settings_group_box.isEnabled(), True, 'The Http group box should be enabled') self.assertEqual(self.form.https_settings_group_box.isChecked(), False, 'The Https checked box should be Checked') self.assertEqual(self.form.https_settings_group_box.isEnabled(), True, 'The Https box should be enabled')
def test_get_web_page(self): """ Test that the get_web_page method works correctly """ with patch('openlp.core.common.httputils.urllib.request.Request') as MockRequest, \ patch('openlp.core.common.httputils.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.common.httputils.get_user_agent') as mock_get_user_agent, \ patch('openlp.core.common.Registry') as MockRegistry: # GIVEN: Mocked out objects and a fake URL mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object mock_get_user_agent.return_value = 'user_agent' fake_url = 'this://is.a.fake/url' # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with('User-Agent', 'user_agent') self.assertEqual(1, mocked_request_object.add_header.call_count, 'There should only be 1 call to add_header') mock_get_user_agent.assert_called_with() mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() self.assertEqual(0, MockRegistry.call_count, 'The Registry() object should have never been called') self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def test_get_web_page_with_header(self): """ Test that adding a header to the call to get_web_page() adds the header to the request """ with patch('openlp.core.lib.webpagereader.urllib.request.Request') as MockRequest, \ patch('openlp.core.lib.webpagereader.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.lib.webpagereader._get_user_agent') as mock_get_user_agent: # GIVEN: Mocked out objects, a fake URL and a fake header mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object mock_get_user_agent.return_value = 'user_agent' fake_url = 'this://is.a.fake/url' fake_header = ('Fake-Header', 'fake value') # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url, header=fake_header) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with( fake_header[0], fake_header[1]) self.assertEqual(2, mocked_request_object.add_header.call_count, 'There should only be 2 calls to add_header') mock_get_user_agent.assert_called_with() mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def test_get_web_page(self): """ Test that the get_web_page method works correctly """ with patch('openlp.core.lib.webpagereader.urllib.request.Request') as MockRequest, \ patch('openlp.core.lib.webpagereader.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.lib.webpagereader._get_user_agent') as mock_get_user_agent, \ patch('openlp.core.common.Registry') as MockRegistry: # GIVEN: Mocked out objects and a fake URL mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object mock_get_user_agent.return_value = 'user_agent' fake_url = 'this://is.a.fake/url' # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with( 'User-Agent', 'user_agent') self.assertEqual(1, mocked_request_object.add_header.call_count, 'There should only be 1 call to add_header') mock_get_user_agent.assert_called_with() mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() self.assertEqual( 0, MockRegistry.call_count, 'The Registry() object should have never been called') self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def test_get_web_page_update_openlp(self): """ Test that passing "update_openlp" as true to get_web_page calls Registry().get('app').process_events() """ with patch('openlp.core.common.httputils.urllib.request.Request') as MockRequest, \ patch('openlp.core.common.httputils.urllib.request.urlopen') as mock_urlopen, \ patch('openlp.core.common.httputils.get_user_agent') as mock_get_user_agent, \ patch('openlp.core.common.httputils.Registry') as MockRegistry: # GIVEN: Mocked out objects, a fake URL mocked_request_object = MagicMock() MockRequest.return_value = mocked_request_object mocked_page_object = MagicMock() mock_urlopen.return_value = mocked_page_object mock_get_user_agent.return_value = 'user_agent' mocked_registry_object = MagicMock() mocked_application_object = MagicMock() mocked_registry_object.get.return_value = mocked_application_object MockRegistry.return_value = mocked_registry_object fake_url = 'this://is.a.fake/url' # WHEN: The get_web_page() method is called returned_page = get_web_page(fake_url, update_openlp=True) # THEN: The correct methods are called with the correct arguments and a web page is returned MockRequest.assert_called_with(fake_url) mocked_request_object.add_header.assert_called_with('User-Agent', 'user_agent') self.assertEqual(1, mocked_request_object.add_header.call_count, 'There should only be 1 call to add_header') mock_urlopen.assert_called_with(mocked_request_object, timeout=30) mocked_page_object.geturl.assert_called_with() mocked_registry_object.get.assert_called_with('application') mocked_application_object.process_events.assert_called_with() self.assertEqual(mocked_page_object, returned_page, 'The returned page should be the mock object')
def test_write_theme_same_image(self): """ Test that we don't try to overwrite a theme background image with itself """ # GIVEN: A new theme manager instance, with mocked builtins.open, shutil.copyfile, # theme, check_directory_exists and thememanager-attributes. with patch('builtins.open') as mocked_open, \ patch('openlp.core.ui.thememanager.shutil.copyfile') as mocked_copyfile, \ patch('openlp.core.ui.thememanager.check_directory_exists') as mocked_check_directory_exists: mocked_open.return_value = MagicMock() theme_manager = ThemeManager(None) theme_manager.old_background_image = None theme_manager.generate_and_save_image = MagicMock() theme_manager.path = '' mocked_theme = MagicMock() mocked_theme.theme_name = 'themename' mocked_theme.extract_formatted_xml = MagicMock() mocked_theme.extract_formatted_xml.return_value = 'fake_theme_xml'.encode() # WHEN: Calling _write_theme with path to the same image, but the path written slightly different file_name1 = os.path.join(TEST_RESOURCES_PATH, 'church.jpg') # Do replacement from end of string to avoid problems with path start file_name2 = file_name1[::-1].replace(os.sep, os.sep + os.sep, 2)[::-1] theme_manager._write_theme(mocked_theme, file_name1, file_name2) # THEN: The mocked_copyfile should not have been called self.assertFalse(mocked_copyfile.called, 'shutil.copyfile should not be called')
def test_write_theme_diff_images(self): """ Test that we do overwrite a theme background image when a new is submitted """ # GIVEN: A new theme manager instance, with mocked builtins.open, shutil.copyfile, # theme, check_directory_exists and thememanager-attributes. with patch('builtins.open') as mocked_open, \ patch('openlp.core.ui.thememanager.shutil.copyfile') as mocked_copyfile, \ patch('openlp.core.ui.thememanager.check_directory_exists') as mocked_check_directory_exists: mocked_open.return_value = MagicMock() theme_manager = ThemeManager(None) theme_manager.old_background_image = None theme_manager.generate_and_save_image = MagicMock() theme_manager.path = '' mocked_theme = MagicMock() mocked_theme.theme_name = 'themename' mocked_theme.extract_formatted_xml = MagicMock() mocked_theme.extract_formatted_xml.return_value = 'fake_theme_xml'.encode() # WHEN: Calling _write_theme with path to different images file_name1 = os.path.join(TEST_RESOURCES_PATH, 'church.jpg') file_name2 = os.path.join(TEST_RESOURCES_PATH, 'church2.jpg') theme_manager._write_theme(mocked_theme, file_name1, file_name2) # THEN: The mocked_copyfile should not have been called self.assertTrue(mocked_copyfile.called, 'shutil.copyfile should be called')
def test_set_basic_urls(self): """ Test the set_urls function with standard defaults """ # GIVEN: A mocked location with patch('openlp.core.common.Settings') as mocked_class, \ patch('openlp.core.common.applocation.AppLocation.get_directory') as mocked_get_directory, \ patch('openlp.core.common.check_directory_exists') as mocked_check_directory_exists, \ patch('openlp.core.common.applocation.os') as mocked_os: # GIVEN: A mocked out Settings class and a mocked out AppLocation.get_directory() mocked_settings = mocked_class.return_value mocked_settings.contains.return_value = False mocked_get_directory.return_value = 'test/dir' mocked_check_directory_exists.return_value = True mocked_os.path.normpath.return_value = 'test/dir' # WHEN: when the set_urls is called having reloaded the form. self.form.load() self.form.set_urls() # THEN: the following screen values should be set self.assertEqual(self.form.address_edit.text(), ZERO_URL, 'The default URL should be set on the screen') self.assertEqual(self.form.https_settings_group_box.isEnabled(), False, 'The Https box should not be enabled') self.assertEqual(self.form.https_settings_group_box.isChecked(), False, 'The Https checked box should note be Checked') self.assertEqual(self.form.user_login_group_box.isChecked(), False, 'The authentication box should not be enabled')
def test_set_certificate_urls(self): """ Test the set_urls function with certificate available """ # GIVEN: A mocked location with patch('openlp.core.common.Settings') as mocked_class, \ patch('openlp.core.common.applocation.AppLocation.get_directory') as mocked_get_directory, \ patch('openlp.core.common.check_directory_exists') as mocked_check_directory_exists, \ patch('openlp.core.common.applocation.os') as mocked_os: # GIVEN: A mocked out Settings class and a mocked out AppLocation.get_directory() mocked_settings = mocked_class.return_value mocked_settings.contains.return_value = False mocked_get_directory.return_value = TEST_PATH mocked_check_directory_exists.return_value = True mocked_os.path.normpath.return_value = TEST_PATH # WHEN: when the set_urls is called having reloaded the form. self.form.load() self.form.set_urls() # THEN: the following screen values should be set self.assertEqual(self.form.http_settings_group_box.isEnabled(), True, 'The Http group box should be enabled') self.assertEqual(self.form.https_settings_group_box.isChecked(), False, 'The Https checked box should be Checked') self.assertEqual(self.form.https_settings_group_box.isEnabled(), True, 'The Https box should be enabled')
def setUp(self): self.os_patcher = patch('openlp.core.lib.filedialog.os') self.qt_gui_patcher = patch('openlp.core.lib.filedialog.QtWidgets') self.ui_strings_patcher = patch('openlp.core.lib.filedialog.UiStrings') self.mocked_os = self.os_patcher.start() self.mocked_qt_gui = self.qt_gui_patcher.start() self.mocked_ui_strings = self.ui_strings_patcher.start() self.mocked_parent = MagicMock()
def setUp(self): """ Set up the components need for all tests. """ with patch('openlp.plugins.bibles.lib.mediaitem.MediaManagerItem._setup'),\ patch('openlp.plugins.bibles.lib.mediaitem.BibleMediaItem.setup_item'): self.media_item = BibleMediaItem(None, MagicMock()) self.setup_application()
def setUp(self): """ Set up the components need for all tests. """ Registry.create() Registry().register('service_manager', MagicMock()) Registry().register('main_window', MagicMock()) with patch('openlp.plugins.presentations.lib.mediaitem.MediaManagerItem._setup'), \ patch('openlp.plugins.presentations.lib.mediaitem.PresentationMediaItem.setup_item'): self.media_item = PresentationMediaItem(None, MagicMock, MagicMock())
def setUp(self): Registry.create() self.registry = Registry() self.setup_application() # Mock cursor busy/normal methods. self.app.set_busy_cursor = MagicMock() self.app.set_normal_cursor = MagicMock() self.app.args = [] Registry().register('application', self.app) # Mock classes and methods used by mainwindow. with patch('openlp.core.ui.mainwindow.SettingsForm') as mocked_settings_form, \ patch('openlp.core.ui.mainwindow.ImageManager') as mocked_image_manager, \ patch('openlp.core.ui.mainwindow.LiveController') as mocked_live_controller, \ patch('openlp.core.ui.mainwindow.PreviewController') as mocked_preview_controller, \ patch('openlp.core.ui.mainwindow.OpenLPDockWidget') as mocked_dock_widget, \ patch('openlp.core.ui.mainwindow.QtWidgets.QToolBox') as mocked_q_tool_box_class, \ patch('openlp.core.ui.mainwindow.QtWidgets.QMainWindow.addDockWidget') as mocked_add_dock_method, \ patch('openlp.core.ui.mainwindow.ThemeManager') as mocked_theme_manager, \ patch('openlp.core.ui.mainwindow.Renderer') as mocked_renderer: self.mocked_settings_form = mocked_settings_form self.mocked_image_manager = mocked_image_manager self.mocked_live_controller = mocked_live_controller self.mocked_preview_controller = mocked_preview_controller self.mocked_dock_widget = mocked_dock_widget self.mocked_q_tool_box_class = mocked_q_tool_box_class self.mocked_add_dock_method = mocked_add_dock_method self.mocked_theme_manager = mocked_theme_manager self.mocked_renderer = mocked_renderer self.main_window = MainWindow()
def db_file_import_test(self): """ Test the actual import of real song database files and check that the imported data is correct. """ # GIVEN: Test files with a mocked out SongImport class, a mocked out "manager", a mocked out "import_wizard", # and mocked out "author", "add_copyright", "add_verse", "finish" methods. with patch('openlp.plugins.songs.lib.importers.easyworship.SongImport'), \ patch('openlp.plugins.songs.lib.importers.easyworship.retrieve_windows_encoding') as \ mocked_retrieve_windows_encoding: mocked_retrieve_windows_encoding.return_value = 'cp1252' mocked_manager = MagicMock() mocked_import_wizard = MagicMock() mocked_add_author = MagicMock() mocked_add_verse = MagicMock() mocked_finish = MagicMock() mocked_title = MagicMock() mocked_finish.return_value = True importer = EasyWorshipSongImportLogger(mocked_manager) importer.import_wizard = mocked_import_wizard importer.stop_import_flag = False importer.add_author = mocked_add_author importer.add_verse = mocked_add_verse importer.title = mocked_title importer.finish = mocked_finish importer.topics = [] # WHEN: Importing each file importer.import_source = os.path.join(TEST_PATH, 'Songs.DB') import_result = importer.do_import() # THEN: do_import should return none, the song data should be as expected, and finish should have been # called. self.assertIsNone(import_result, 'do_import should return None when it has completed') for song_data in SONG_TEST_DATA: title = song_data['title'] author_calls = song_data['authors'] song_copyright = song_data['copyright'] ccli_number = song_data['ccli_number'] add_verse_calls = song_data['verses'] verse_order_list = song_data['verse_order_list'] self.assertIn(title, importer._title_assignment_list, 'title for %s should be "%s"' % (title, title)) for author in author_calls: mocked_add_author.assert_any_call(author) if song_copyright: self.assertEqual(importer.copyright, song_copyright) if ccli_number: self.assertEqual(importer.ccli_number, ccli_number, 'ccli_number for %s should be %s' % (title, ccli_number)) for verse_text, verse_tag in add_verse_calls: mocked_add_verse.assert_any_call(verse_text, verse_tag) if verse_order_list: self.assertEqual(importer.verse_order_list, verse_order_list, 'verse_order_list for %s should be %s' % (title, verse_order_list)) mocked_finish.assert_called_with()
def setUp(self): """ Set up the components need for all tests. """ with patch('openlp.plugins.media.lib.mediaitem.MediaManagerItem.__init__'),\ patch('openlp.plugins.media.lib.mediaitem.MediaMediaItem.setup'): self.media_item = MediaMediaItem(None, MagicMock()) self.media_item.settings_section = 'media' self.setup_application() self.build_settings() Settings().extend_default_settings(__default_settings__)
def setUp(self): self.mocked_main_window = MagicMock() Registry.create() Registry().register('application', MagicMock()) Registry().register('service_list', MagicMock()) Registry().register('main_window', self.mocked_main_window) Registry().register('live_controller', MagicMock()) mocked_plugin = MagicMock() with patch('openlp.plugins.images.lib.mediaitem.MediaManagerItem._setup'), \ patch('openlp.plugins.images.lib.mediaitem.ImageMediaItem.setup_item'): self.media_item = ImageMediaItem(None, mocked_plugin) self.media_item.settings_section = 'images'