Exemplo n.º 1
0
    def test_do_import_success(self):
        """
        Test do_import when the import succeeds
        """
        # GIVEN: An instance of CSVBible
        mocked_manager = MagicMock()
        with patch('openlp.plugins.bibles.lib.db.BibleDB._setup'):
            importer = CSVBible(mocked_manager, path='.', name='.', books_path=Path('books.csv'),
                                verse_path=Path('verses.csv'))
            importer.get_language = MagicMock(return_value=10)
            importer.parse_csv_file = MagicMock(side_effect=[['Book 1'], ['Verse 1']])
            importer.process_books = MagicMock(return_value=['Book 1'])
            importer.process_verses = MagicMock(return_value=['Verse 1'])
            importer.session = MagicMock()
            importer.stop_import_flag = False
            importer.wizard = MagicMock()

            # WHEN: Calling do_import
            result = importer.do_import('Bible Name')

            # THEN: parse_csv_file should be called twice,
            # and True should be returned.
            assert importer.parse_csv_file.mock_calls == \
                [call(Path('books.csv'), Book), call(Path('verses.csv'), Verse)]
            importer.process_books.assert_called_once_with(['Book 1'])
            importer.process_verses.assert_called_once_with(['Verse 1'], ['Book 1'])
            assert result is True
Exemplo n.º 2
0
    def test_process_books(self, mocked_read_text):
        """
        Test the process_books() method
        """
        # GIVEN: A WordProject importer and a bunch of mocked things
        importer = WordProjectBible(MagicMock(),
                                    path='.',
                                    name='.',
                                    file_path=Path('kj.zip'))
        importer.base_path = Path()
        importer.stop_import_flag = False
        importer.language_id = 'en'
        mocked_read_text.return_value = INDEX_PAGE

        # WHEN: process_books() is called
        with patch.object(importer, 'find_and_create_book') as mocked_find_and_create_book, \
                patch.object(importer, 'process_chapters') as mocked_process_chapters, \
                patch.object(importer, 'session') as mocked_session:
            importer.process_books()

        # THEN: The right methods should have been called
        mocked_read_text.assert_called_once_with(encoding='utf-8',
                                                 errors='ignore')
        assert mocked_find_and_create_book.call_count == 66, 'There should be 66 books'
        assert mocked_process_chapters.call_count == 66, 'There should be 66 books'
        assert mocked_session.commit.call_count == 66, 'There should be 66 books'
Exemplo n.º 3
0
    def test_process_books(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='.', books_path=Path('books.csv'),
                                verse_path=Path('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.
            assert importer.find_and_create_book.mock_calls == \
                [call('1. Mosebog', 2, 10), call('2. Mosebog', 2, 10)]
            assert result == {1: '1. Mosebog', 2: '2. Mosebog'}
Exemplo n.º 4
0
    def test_process_verses_successful(self):
        """
        Test process_verses when the import is successful
        """
        # GIVEN: An instance of CSVBible with the application and wizard attributes mocked out, and some test 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='.', books_path=Path('books.csv'),
                                verse_path=Path('verse.csv'))
            importer.create_verse = MagicMock()
            importer.get_book = MagicMock(return_value=Book('1', '1', '1. Mosebog', '1Mos'))
            importer.get_book_name = MagicMock(return_value='1. Mosebog')
            importer.session = MagicMock()
            importer.stop_import_flag = False
            importer.wizard = MagicMock()
            verses = [Verse(1, 1, 1, 'I Begyndelsen skabte Gud Himmelen og Jorden.'),
                      Verse(1, 1, 2, 'Og Jorden var øde og tom, og der var Mørke over Verdensdybet. '
                                     'Men Guds Ånd svævede over Vandene.')]
            books = {1: '1. Mosebog'}

            # WHEN: Calling process_verses
            importer.process_verses(verses, books)

            # THEN: create_verse is called with the test data
            assert importer.get_book_name.mock_calls == [call(1, books), call(1, books)]
            importer.get_book.assert_called_once_with('1. Mosebog')
            assert importer.session.commit.call_count == 2
            assert importer.create_verse.mock_calls == \
                [call('1', 1, 1, 'I Begyndelsen skabte Gud Himmelen og Jorden.'),
                 call('1', 1, 2, 'Og Jorden var øde og tom, og der var Mørke over Verdensdybet. '
                                 'Men Guds Ånd svævede over Vandene.')]
Exemplo n.º 5
0
    def test_process_chapters(self, mocked_read_text):
        """
        Test the process_chapters() method
        """
        # GIVEN: A WordProject importer and a bunch of mocked things
        importer = WordProjectBible(MagicMock(),
                                    path='.',
                                    name='.',
                                    file_path=Path('kj.zip'))
        importer.base_path = Path()
        importer.stop_import_flag = False
        importer.language_id = 'en'
        mocked_read_text.return_value = CHAPTER_PAGE
        mocked_db_book = MagicMock()
        mocked_db_book.name = 'Genesis'
        book_id = 1
        book_link = '01/1.htm'

        # WHEN: process_chapters() is called
        with patch.object(importer, 'set_current_chapter') as mocked_set_current_chapter, \
                patch.object(importer, 'process_verses') as mocked_process_verses:
            importer.process_chapters(mocked_db_book, book_id, book_link)

        # THEN: The right methods should have been called
        expected_set_current_chapter_calls = [
            call('Genesis', ch) for ch in range(1, 51)
        ]
        expected_process_verses_calls = [
            call(mocked_db_book, 1, ch) for ch in range(1, 51)
        ]
        mocked_read_text.assert_called_once_with(encoding='utf-8',
                                                 errors='ignore')
        assert mocked_set_current_chapter.call_args_list == expected_set_current_chapter_calls
        assert mocked_process_verses.call_args_list == expected_process_verses_calls
Exemplo n.º 6
0
    def test_download_and_check(self, mocked_deploy_zipfile,
                                mocked_get_data_path, mocked_download_file,
                                mocked_get_url_file_size,
                                mocked_download_sha256, MockRegistry):
        # GIVEN: A bunch of mocks
        mocked_get_data_path.return_value = Path('/tmp/remotes')
        mocked_download_file.return_value = True
        mocked_get_url_file_size.return_value = 5
        mocked_download_sha256.return_value = ('asdfgh', '0.1')
        MockRegistry.return_value.get.return_value.applicationVersion.return_value = '1.0'
        mocked_callback = MagicMock()

        # WHEN: download_and_check() is called
        download_and_check(mocked_callback)

        # THEN: The correct things should have been done
        mocked_download_sha256.assert_called_once_with()
        mocked_get_url_file_size.assert_called_once_with(
            'https://get.openlp.org/webclient/site.zip')
        mocked_callback.setRange.assert_called_once_with(0, 5)
        mocked_download_file.assert_called_once_with(
            mocked_callback,
            'https://get.openlp.org/webclient/site.zip',
            Path('/tmp/remotes/site.zip'),
            sha256='asdfgh')
        mocked_deploy_zipfile.assert_called_once_with(Path('/tmp/remotes'),
                                                      'site.zip')
Exemplo n.º 7
0
    def test_process_verses(self, mocked_read_text):
        """
        Test the process_verses() method
        """
        # GIVEN: A WordProject importer and a bunch of mocked things
        importer = WordProjectBible(MagicMock(),
                                    path='.',
                                    name='.',
                                    file_path=Path('kj.zip'))
        importer.base_path = Path()
        importer.stop_import_flag = False
        importer.language_id = 'en'
        mocked_read_text.return_value = CHAPTER_PAGE
        mocked_db_book = MagicMock()
        mocked_db_book.name = 'Genesis'
        book_number = 1
        chapter_number = 1

        # WHEN: process_verses() is called
        with patch.object(importer, 'process_verse') as mocked_process_verse:
            importer.process_verses(mocked_db_book, book_number,
                                    chapter_number)

        # THEN: All the right methods should have been called
        mocked_read_text.assert_called_once_with(encoding='utf-8',
                                                 errors='ignore')
        assert mocked_process_verse.call_count == 31
Exemplo n.º 8
0
    def test_copytree_optional_params(self):
        """
        Test :func:`openlp.core.common.path.copytree` when optional parameters are passed
        """
        # GIVEN: A mocked :func:`shutil.copytree`
        with patch('openlp.core.common.path.shutil.copytree',
                   return_value='') as mocked_shutil_copytree:
            mocked_ignore = MagicMock()
            mocked_copy_function = MagicMock()

            # WHEN: Calling :func:`openlp.core.common.path.copytree` with the optional parameters set
            copytree(Path('source', 'test', 'path'),
                     Path('destination', 'test', 'path'),
                     symlinks=True,
                     ignore=mocked_ignore,
                     copy_function=mocked_copy_function,
                     ignore_dangling_symlinks=True)

            # THEN: :func:`shutil.copytree` should have been called with the optional parameters, with out any of the
            #       values being modified
            mocked_shutil_copytree.assert_called_once_with(
                ANY,
                ANY,
                symlinks=True,
                ignore=mocked_ignore,
                copy_function=mocked_copy_function,
                ignore_dangling_symlinks=True)
Exemplo n.º 9
0
    def test_clean_up_thumbnails(self):
        """
        Test that the clean_up_thumbnails method works as expected when files exists.
        """
        # GIVEN: A mocked controller, and mocked os.path.getmtime
        mocked_controller = MagicMock()
        mocked_doc = MagicMock(**{'get_thumbnail_path.return_value': Path()})
        mocked_controller.add_document.return_value = mocked_doc
        mocked_controller.supports = ['tmp']
        self.media_item.controllers = {
            'Mocked': mocked_controller
        }

        thmub_path = MagicMock(st_mtime=100)
        file_path = MagicMock(st_mtime=400)
        with patch.object(Path, 'stat', side_effect=[thmub_path, file_path]), \
                patch.object(Path, 'exists', return_value=True):
            presentation_file = Path('file.tmp')

            # WHEN: calling clean_up_thumbnails
            self.media_item.clean_up_thumbnails(presentation_file, True)

        # THEN: doc.presentation_deleted should have been called since the thumbnails mtime will be greater than
        #       the presentation_file's mtime.
        mocked_doc.assert_has_calls([call.get_thumbnail_path(1, True), call.presentation_deleted()], True)
Exemplo n.º 10
0
    def test_image_filenames_table(self):
        """
        Test that the ImageFilenames table is correctly upgraded to the latest version
        """
        # GIVEN: An unversioned image database
        temp_db_name = os.path.join(self.tmp_folder, 'image-v0.sqlite')
        shutil.copyfile(
            os.path.join(TEST_RESOURCES_PATH, 'images', 'image-v0.sqlite'),
            temp_db_name)

        with patch.object(AppLocation,
                          'get_data_path',
                          return_value=Path('/', 'test', 'dir')):
            # WHEN: Initalising the database manager
            manager = Manager('images',
                              init_schema,
                              db_file_path=temp_db_name,
                              upgrade_mod=upgrade)

            # THEN: The database should have been upgraded and image_filenames.file_path should return Path objects
            upgraded_results = manager.get_all_objects(ImageFilenames)

            expected_result_data = {
                1: Path('/', 'test', 'image1.jpg'),
                2: Path('/', 'test', 'dir', 'image2.jpg'),
                3: Path('/', 'test', 'dir', 'subdir', 'image3.jpg')
            }

            assert len(upgraded_results) == 3
            for result in upgraded_results:
                assert expected_result_data[result.id] == result.file_path
Exemplo n.º 11
0
class TestPluginManager(TestCase, TestMixin):
    """
    Test the PluginManager class
    """
    def setUp(self):
        """
        Some pre-test setup required.
        """
        self.setup_application()
        self.build_settings()
        self.temp_dir_path = Path(mkdtemp('openlp'))
        Settings().setValue('advanced/data path', self.temp_dir_path)
        Registry.create()
        Registry().register('service_list', MagicMock())
        self.main_window = QtWidgets.QMainWindow()
        Registry().register('main_window', self.main_window)

    def tearDown(self):
        Settings().remove('advanced/data path')
        self.destroy_settings()
        del self.main_window
        # On windows we need to manually garbage collect to close sqlalchemy files
        # to avoid errors when temporary files are deleted.
        gc.collect()
        self.temp_dir_path.rmtree()

    @patch('openlp.plugins.songusage.lib.db.init_schema')
    @patch('openlp.plugins.songs.lib.db.init_schema')
    @patch('openlp.plugins.images.lib.db.init_schema')
    @patch('openlp.plugins.custom.lib.db.init_schema')
    @patch('openlp.plugins.alerts.lib.db.init_schema')
    @patch('openlp.plugins.bibles.lib.db.init_schema')
    def test_find_plugins(self, mocked_is1, mocked_is2, mocked_is3, mocked_is4,
                          mocked_is5, mocked_is6):
        """
        Test the find_plugins() method to ensure it imports the correct plugins
        """
        # GIVEN: A plugin manager
        plugin_manager = PluginManager()

        # WHEN: We mock out sys.platform to make it return "darwin" and then find the plugins
        old_platform = sys.platform
        sys.platform = 'darwin'
        plugin_manager.find_plugins()
        sys.platform = old_platform

        # THEN: We should find the "Songs", "Bibles", etc in the plugins list
        plugin_names = [plugin.name for plugin in plugin_manager.plugins]
        assert 'songs' in plugin_names, 'There should be a "songs" plugin'
        assert 'bibles' in plugin_names, 'There should be a "bibles" plugin'
        assert 'presentations' in plugin_names, 'There should be a "presentations" plugin'
        assert 'images' in plugin_names, 'There should be a "images" plugin'
        assert 'media' in plugin_names, 'There should be a "media" plugin'
        assert 'custom' in plugin_names, 'There should be a "custom" plugin'
        assert 'songusage' in plugin_names, 'There should be a "songusage" plugin'
        assert 'alerts' in plugin_names, 'There should be a "alerts" plugin'
Exemplo n.º 12
0
    def test_path_getter(self):
        """
        Test the `path` property getter.
        """
        # GIVEN: An instance of PathEdit with the `_path` instance variable set
        self.widget._path = Path('getter', 'test', 'pat.h')

        # WHEN: Reading the `path` property
        # THEN: The value that we set should be returned
        assert self.widget.path == Path('getter', 'test', 'pat.h')
Exemplo n.º 13
0
    def check_thumbnails(self):
        """
        Check that the last thumbnail image exists and is valid and are more recent than the powerpoint file.

        :return: If the thumbnail is valid
        :rtype: bool
        """
        last_image_path = self.get_thumbnail_path(self.get_slide_count(), True)
        if not (last_image_path and last_image_path.is_file()):
            return False
        return validate_thumb(Path(self.file_path), Path(last_image_path))
Exemplo n.º 14
0
 def test_search_not_found(self):
     """
     Media Remote Search not find
     """
     # GIVEN: The Mediaitem set up a list of media
     Settings().setValue(
         self.media_item.settings_section + '/media files',
         [Path('test.mp3'), Path('test.mp4')])
     # WHEN: Retrieving the test file
     result = self.media_item.search('test.mpx', False)
     # THEN: a file should be found
     assert result == [], 'The result file should be empty'
Exemplo n.º 15
0
 def do_import(self):
     """
     Determines the type of file to import and calls the appropiate method
     """
     self.import_source = Path(self.import_source)
     ext = self.import_source.suffix.lower()
     if ext == '.ews':
         self.import_ews()
     elif ext == '.db':
         self.import_db()
     else:
         self.import_sqlite_db()
Exemplo n.º 16
0
def test_get_directory_for_app_dir(mocked_get_frozen_path):
    """
    Test the AppLocation.get_directory() method for AppLocation.AppDir
    """
    # GIVEN: A mocked out _get_frozen_path function
    mocked_get_frozen_path.return_value = Path('app', 'dir')

    # WHEN: We call AppLocation.get_directory
    directory = AppLocation.get_directory(AppLocation.AppDir)

    # THEN: check that the correct directory is returned
    assert directory == Path('app', 'dir'), 'Directory should be "app/dir"'
Exemplo n.º 17
0
 def setUp(self):
     """
     Some pre-test setup required.
     """
     self.setup_application()
     self.build_settings()
     self.temp_dir_path = Path(mkdtemp('openlp'))
     Settings().setValue('advanced/data path', self.temp_dir_path)
     Registry.create()
     Registry().register('service_list', MagicMock())
     self.main_window = QtWidgets.QMainWindow()
     Registry().register('main_window', self.main_window)
Exemplo n.º 18
0
    def test_json_decode(self):
        """
        Test the OpenLPJsonDecoder when decoding a JSON string
        """
        # GIVEN: A JSON encoded string
        json_string = '[{"__Path__": ["test", "path1"]}, {"__Path__": ["test", "path2"]}]'

        # WHEN: Decoding the string using the OpenLPJsonDecoder class
        obj = json.loads(json_string, cls=OpenLPJsonDecoder)

        # THEN: The object returned should be a python version of the JSON string
        assert obj == [Path('test', 'path1'), Path('test', 'path2')]
Exemplo n.º 19
0
    def test_json_encode(self):
        """
        Test the OpenLPJsonDEncoder when encoding an object conatining Path objects
        """
        # GIVEN: A list of Path objects
        obj = [Path('test', 'path1'), Path('test', 'path2')]

        # WHEN: Encoding the object using the OpenLPJsonEncoder class
        json_string = json.dumps(obj, cls=OpenLPJsonEncoder)

        # THEN: The JSON string return should be a representation of the object encoded
        assert json_string == '[{"__Path__": ["test", "path1"]}, {"__Path__": ["test", "path2"]}]'
Exemplo n.º 20
0
    def test_path_json_object(self):
        """
        Test that `Path.json_object` creates a JSON decode-able object from a Path object
        """
        # GIVEN: A Path object from openlp.core.common.path
        path = Path('/base', 'path', 'to', 'fi.le')

        # WHEN: Calling json_object
        obj = path.json_object(extra=1, args=2)

        # THEN: A JSON decodable object should have been returned.
        assert obj == {'__Path__': ('/', 'base', 'path', 'to', 'fi.le')}
Exemplo n.º 21
0
    def test_path_encode_json_base_path(self):
        """
        Test that `Path.encode_json` returns a Path object from a dictionary representation of a Path object decoded
        from JSON when the base_path arg is supplied.
        """
        # GIVEN: A Path object from openlp.core.common.path
        # WHEN: Calling encode_json, with a dictionary representation
        path = Path.encode_json({'__Path__': ['path', 'to', 'fi.le']},
                                base_path=Path('/base'))

        # THEN: A Path object should have been returned with an absolute path
        assert path == Path('/', 'base', 'path', 'to', 'fi.le')
Exemplo n.º 22
0
 def test_search_found(self):
     """
     Media Remote Search Successful find
     """
     # GIVEN: The Mediaitem set up a list of media
     Settings().setValue(
         self.media_item.settings_section + '/media files',
         [Path('test.mp3'), Path('test.mp4')])
     # WHEN: Retrieving the test file
     result = self.media_item.search('test.mp4', False)
     # THEN: a file should be found
     assert result == [['test.mp4', 'test.mp4']
                       ], 'The result file contain the file name'
Exemplo n.º 23
0
    def test_path_encode_json(self):
        """
        Test that `Path.encode_json` returns a Path object from a dictionary representation of a Path object decoded
        from JSON
        """
        # GIVEN: A Path object from openlp.core.common.path
        # WHEN: Calling encode_json, with a dictionary representation
        path = Path.encode_json({'__Path__': ['path', 'to', 'fi.le']},
                                extra=1,
                                args=2)

        # THEN: A Path object should have been returned
        assert path == Path('path', 'to', 'fi.le')
Exemplo n.º 24
0
    def test_path_json_object_base_path(self):
        """
        Test that `Path.json_object` creates a JSON decode-able object from a Path object, that is relative to the
        base_path
        """
        # GIVEN: A Path object from openlp.core.common.path
        path = Path('/base', 'path', 'to', 'fi.le')

        # WHEN: Calling json_object with a base_path
        obj = path.json_object(base_path=Path('/', 'base'))

        # THEN: A JSON decodable object should have been returned.
        assert obj == {'__Path__': ('path', 'to', 'fi.le')}
Exemplo n.º 25
0
 def _start_server(self):
     """
     Start a LibreOfficeServer
     """
     libreoffice_python = Path(
         '/Applications/LibreOffice.app/Contents/Resources/python')
     libreoffice_server = AppLocation.get_directory(
         AppLocation.PluginsDir).joinpath('presentations', 'lib',
                                          'libreofficeserver.py')
     if libreoffice_python.exists():
         self.server_process = Popen(
             [str(libreoffice_python),
              str(libreoffice_server)])
Exemplo n.º 26
0
    def test_save_new_images_list_other_objects_in_list(self, mocked_load_full_list):
        """
        Test that the save_new_images_list() ignores everything in the provided list except strings
        """
        # GIVEN: A list with images and objects
        image_list = [Path('test_image_1.jpg'), None, True, ImageFilenames(), Path('test_image_2.jpg')]
        self.media_item.manager = MagicMock()

        # WHEN: We run save_new_images_list with the list of images and objects
        self.media_item.save_new_images_list(image_list, reload_list=False)

        # THEN: load_full_list() should not have been called
        assert self.media_item.manager.save_object.call_count == 2, 'load_full_list() should have been called only once'
Exemplo n.º 27
0
    def test_save_new_images_list_multiple_images(self, mocked_load_full_list):
        """
        Test that the save_new_images_list() saves all images in the list
        """
        # GIVEN: A list with 3 images
        image_list = [Path('test_image_1.jpg'), Path('test_image_2.jpg'), Path('test_image_3.jpg')]
        self.media_item.manager = MagicMock()

        # WHEN: We run save_new_images_list with the list of 3 images
        self.media_item.save_new_images_list(image_list, reload_list=False)

        # THEN: load_full_list() should not have been called
        assert self.media_item.manager.save_object.call_count == 3, \
            'load_full_list() should have been called three times'
Exemplo n.º 28
0
    def test_validate_and_load_group(self, mocked_settings, mocked_load_list):
        """
        Test that the validate_and_load_test() method when called with a group
        """
        # GIVEN: A list of files
        file_list = [Path('path1', 'image1.jpg'), Path('path2', 'image2.jpg')]

        # WHEN: Calling validate_and_load with the list of files and a group
        self.media_item.validate_and_load(file_list, 'group')

        # THEN: load_list should have been called with the file list and the group name,
        #       the directory should have been saved to the settings
        mocked_load_list.assert_called_once_with(file_list, 'group')
        mocked_settings().setValue.assert_called_once_with(ANY, Path('path1'))
Exemplo n.º 29
0
    def test_on_revert_button_clicked(self):
        """
        Test that the default path is set as the path when the `revert_button.clicked` handler is called.
        """
        # GIVEN: An instance of PathEdit with a mocked `on_new_path`, and the `default_path` set.
        with patch.object(self.widget, 'on_new_path') as mocked_on_new_path:
            self.widget.default_path = Path('default', 'pat.h')

            # WHEN: Calling `on_revert_button_clicked`
            self.widget.on_revert_button_clicked()

            # THEN: on_new_path should have been called with the default path
            mocked_on_new_path.assert_called_once_with(Path(
                'default', 'pat.h'))
Exemplo n.º 30
0
    def test_files_to_paths(self):
        """
        Test the files_to_paths() method
        """
        # GIVEN: A list of string filenames
        test_files = ['/tmp/openlp/file1.txt', '/tmp/openlp/file2.txt']

        # WHEN: files_to_paths is called
        result = files_to_paths(test_files)

        # THEN: The result should be a list of Paths
        assert result == [
            Path('/tmp/openlp/file1.txt'),
            Path('/tmp/openlp/file2.txt')
        ]