当前位置: 首页>>代码示例>>Python>>正文


Python functional.patch函数代码示例

本文整理汇总了Python中tests.functional.patch函数的典型用法代码示例。如果您正苦于以下问题:Python patch函数的具体用法?Python patch怎么用?Python patch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了patch函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_titles_and_notes_test

    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')
开发者ID:crossroadchurch,项目名称:paul,代码行数:25,代码来源:test_presentationcontroller.py

示例2: test_write_theme_same_image

    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')
开发者ID:imkernel,项目名称:openlp,代码行数:27,代码来源:test_thememanager.py

示例3: test_select_image_file_dialog_cancelled

    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()
开发者ID:imkernel,项目名称:openlp,代码行数:27,代码来源:test_themeform.py

示例4: test_display_results_cclinumber

    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)
开发者ID:imkernel,项目名称:openlp,代码行数:33,代码来源:test_mediaitem.py

示例5: init_db_calls_correct_functions_test

    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')
开发者ID:crossroadchurch,项目名称:paul,代码行数:29,代码来源:test_db.py

示例6: build_html_test

    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')
开发者ID:crossroadchurch,项目名称:paul,代码行数:29,代码来源:test_htmlbuilder.py

示例7: setUp

 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()
开发者ID:imkernel,项目名称:openlp,代码行数:25,代码来源:test_bibleimport.py

示例8: pyodbc_exception_test

    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')
开发者ID:crossroadchurch,项目名称:paul,代码行数:28,代码来源:test_worshipcenterproimport.py

示例9: setUp

 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()
开发者ID:imkernel,项目名称:openlp,代码行数:7,代码来源:test_zefaniaimport.py

示例10: test_get_web_page_update_openlp

    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')
开发者ID:imkernel,项目名称:openlp,代码行数:33,代码来源:test_httputils.py

示例11: test_write_theme_diff_images

    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')
开发者ID:imkernel,项目名称:openlp,代码行数:26,代码来源:test_thememanager.py

示例12: select_image_file_dialog_new_file_test

    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()
开发者ID:crossroadchurch,项目名称:paul,代码行数:29,代码来源:test_themeform.py

示例13: test_backup_on_upgrade

    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()
开发者ID:imkernel,项目名称:openlp,代码行数:27,代码来源:test_init.py

示例14: paint_event_text_doesnt_fit_test

    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)
开发者ID:crossroadchurch,项目名称:paul,代码行数:29,代码来源:test_slidecontroller.py

示例15: paint_event_text_fits_test

    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)
开发者ID:crossroadchurch,项目名称:paul,代码行数:27,代码来源:test_slidecontroller.py


注:本文中的tests.functional.patch函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。