Best Python code snippet using molotov_python
po_pot.py
Source:po_pot.py  
1# -*- coding: utf-8 -*-2"""3Test PO/POT Handler invocations.4There are two kinds:5  - get/read6  - put/create7"""8from __future__ import with_statement9import os10from mock import patch11from django.core.urlresolvers import reverse12from django.conf import settings13from django.utils import simplejson14from django.test import TestCase15from django.test.client import Client, RequestFactory16from transifex.txcommon.tests.base import BaseTestCase17from transifex.languages.models import Language18from transifex.resources.formats.registry import registry19from transifex.resources.views import update_translation20from transifex.resources.templatetags.upload_manager_tags import \21        upload_create_resource_form22from transifex.resources.backends import FormatsBackend23from transifex.resources.api import Translation24from transifex.resources.formats.pofile import POHandler, POTHandler25class TestApiInvocations(BaseTestCase):26    """Test PO/POT Handler invokations in the API.27    We need to test POST for resources and GET and PUT for translations and28    source content.29    """30    def setUp(self):31        super(TestApiInvocations, self).setUp()32        self.resource.i18n_type = 'PO'33        self.resource.save()34        self.source_url = reverse(35            'apiv2_source_content', kwargs={36                'project_slug': self.resource.project.slug,37                'resource_slug': self.resource.slug,38            }39        )40        self.translation_url = reverse(41            'apiv2_translation', kwargs={42                'project_slug': self.resource.project.slug,43                'resource_slug': self.resource.slug,44                'lang_code': 'el'45            }46        )47    @patch.object(POHandler, 'compile')48    def test_get(self, mock_po):49        """Test GET method for API.50        Test for both source content and translations, json and file51        responses.52        """53        for url in (self.source_url, self.translation_url):54            self.client['maintainer'].get(url)55            self.assertTrue(mock_po.called)56            res = self.client['maintainer'].get(url, data={'file' : ''})57            self.assertTrue(mock_po.called)58            attachment = res.items()[1][1]59            filename = attachment[30:-1]60            self.assertTrue(filename.endswith('po'))61    @patch.object(Translation, '_parse_translation')62    @patch.object(POHandler, 'is_content_valid')63    def test_put(self, _mock, mock):64        """Test PUT method for the API.65        Test filenames used.66        """67        # JSON APi68        mock.return_value = {69            'strings_added': 0,70            'strings_updated': 0,71            'redirect': reverse(72                'resource_detail',73                args=[self.resource.project.slug, self.resource.slug]74            )75        }76        self.client['maintainer'].put(77            self.translation_url,78            data=simplejson.dumps({'content': '', }),79            content_type='application/json'80        )81        self.assertTrue(mock.called)82        used_handler = mock.call_args[0][0]83        self.assertIsInstance(used_handler, type(registry.handler_for('PO')))84        res = self.client['maintainer'].put(85            self.source_url,86            data=simplejson.dumps({'content': '', }),87            content_type='application/json'88        )89        self.assertTrue(mock.called)90        self.assertIsInstance(used_handler, type(registry.handler_for('PO')))91        # filename API92        pofile_path = os.path.join(93            settings.TX_ROOT, 'resources/tests/lib/pofile'94        )95        po_filename = os.path.join(pofile_path, "pt_BR.po")96        pot_filename = os.path.join(pofile_path, "general/test.pot")97        po_class = type(registry.handler_for('PO'))98        pot_class = type(registry.handler_for('POT'))99        for url in (self.source_url, self.translation_url):100            with open(po_filename) as f:101                self.client['maintainer'].put(102                    url, data={103                        'name': 'name.po',104                        'attachment': f105                    },106                )107                self.assertTrue(mock.called)108                used_handler = mock.call_args[0][0]109                self.assertIsInstance(used_handler, po_class)110            with open(pot_filename) as f:111                self.client['maintainer'].put(112                    url, data={113                        'name': 'name.po',114                        'attachment': f115                    },116                )117                self.assertTrue(mock.called)118                used_handler = mock.call_args[0][0]119                self.assertIsInstance(used_handler, pot_class)120class TestViewsInvocations(BaseTestCase):121    """Test PO/POT Handler invokations in the views.122    Test for both source content and translations, json and file123    responses. Test for specific download of POT file, too.124    """125    def setUp(self):126        super(TestViewsInvocations, self).setUp()127        self.resource.i18n_type = 'PO'128        self.resource.save()129        self.pslug = self.resource.project.slug130        self.rslug = self.resource.slug131        self.rname = self.resource.name132        self.mclient = self.client['maintainer']133    @patch.object(POHandler, 'compile')134    @patch.object(POTHandler, 'compile')135    def test_get(self, mock_pot, mock_po):136        po_source_url = reverse(137            'download_for_translation', kwargs={138                'project_slug': self.pslug,139                'resource_slug': self.rslug,140                'lang_code': 'en'141            }142        )143        po_translation_url = reverse(144            'download_for_translation', kwargs={145                'project_slug': self.pslug,146                'resource_slug': self.rslug,147                'lang_code': 'el'148            }149        )150        pot_url = reverse(151            'download_pot', kwargs={152                'project_slug': self.pslug,153                'resource_slug': self.rslug,154            }155        )156        for url in (po_source_url, po_translation_url):157            res = self.mclient.get(url)158            self.assertTrue(mock_po.called)159            attachment = res.items()[3][1]160            filename = attachment[22:]161            self.assertTrue(filename.endswith('po'))162        res = self.mclient.get(pot_url)163        self.assertTrue(mock_pot.called)164        attachment = res.items()[3][1]165        filename = attachment[22:]166        self.assertTrue(filename.endswith('pot'))167    @patch.object(FormatsBackend, '_import_content')168    def test_put(self, import_mock):169        """Check file upload through views.170        Specifically,171        - resource_edit view172        - upload_create_resource_form173        - create_translation_form174        - update_translation_form175        """176        pofile_path = os.path.join(177            settings.TX_ROOT, 'resources/tests/lib/pofile'178        )179        po_filename = os.path.join(pofile_path, "pt_BR.po")180        pot_filename = os.path.join(pofile_path, "general/test.pot")181        po_class = type(registry.handler_for('PO'))182        pot_class = type(registry.handler_for('POT'))183        resource_edit_url = reverse(184            'resource_edit', kwargs={185                'project_slug': self.pslug,186                'resource_slug': self.rslug,187            }188        )189        filenames, klasses = [po_filename, pot_filename], [po_class, pot_class]190        for (filename, klass) in zip(filenames, klasses):191            with open(filename) as f:192                self.mclient.post(193                    resource_edit_url, data={194                        'sourcefile': f,195                        'slug': self.resource.slug,196                        'name': self.resource.name,197                    }198                )199                self.assertTrue(import_mock.called)200                used_handler = import_mock.call_args[0][0]201                self.assertIsInstance(used_handler, klass)202        # Test template tags203        factory = RequestFactory()204        # Create request for template tags205        url = reverse('project_detail', kwargs={'project_slug': self.pslug})206        for (filename, klass) in zip(filenames, klasses):207            with open(filename) as f:208                request = factory.post(209                    url, data={210                        'create_resource': True,211                        'create_form-name': 'Name',212                        'create_form-i18n_method': 'PO',213                        'create_form-source_file': f214                    }215                )216                # we need to patch the request.user object217                with patch.object(request, 'user', create=True) as mock:218                    mock.return_value = self.user['maintainer']219                    upload_create_resource_form(request, self.project)220                    self.assertTrue(import_mock.called)221                    used_handler = import_mock.call_args[0][0]222                    self.assertIsInstance(used_handler, klass)223        with open(po_filename) as f:224            lang_code = 'en_US'225            url = reverse(226                'update_translation',227                kwargs={228                    'project_slug': self.pslug,229                    'resource_slug': self.rslug,230                    'lang_code': lang_code,231                }232            )233            request = factory.post(234                url, data={235                    'name': po_filename,236                    'attachment': f237                }238            )239            # we need to patch the request.user object for the request240            with patch.object(request, 'user', create=True) as mock:241                mock.return_value = self.user['maintainer']242                update_translation(243                    request, project_slug=self.pslug,244                    resource_slug=self.rslug, lang_code=lang_code245                )246                self.assertTrue(import_mock.called)247                used_handler = import_mock.call_args[0][0]248                self.assertIsInstance(used_handler, po_class)249            request = factory.post(250                url, data={251                    'name': po_filename,252                    'attachment': f,253                    'language_code': 'en_US'254                }255            )256            # we need to patch the request.user object for the request257            with patch.object(request, 'user', create=True) as mock:258                mock.return_value = self.user['maintainer']259                update_translation(260                    request, project_slug=self.pslug, resource_slug=self.rslug261                )262                self.assertTrue(import_mock.called)263                used_handler = import_mock.call_args[0][0]...test__init__.py
Source:test__init__.py  
...39    def test_no_errors(self):40        """Payload gets written to file and added to C{pdata}."""41        import_mock = self.mocker.replace(importer.import_module,42                                          passthrough=False)43        import_mock(self.expected_module_name)44        self.mocker.result(self.module_fake)45        self.mocker.replay()46        handlers.walker_handle_handler(self.data, self.ctype, self.filename,47                                       self.payload)48        self.assertEqual(1, self.data["handlercount"])49    def test_import_error(self):50        """Module import errors are logged. No handler added to C{pdata}."""51        import_mock = self.mocker.replace(importer.import_module,52                                          passthrough=False)53        import_mock(self.expected_module_name)54        self.mocker.throw(ImportError())55        self.mocker.replay()56        handlers.walker_handle_handler(self.data, self.ctype, self.filename,57                                       self.payload)58        self.assertEqual(0, self.data["handlercount"])59    def test_attribute_error(self):60        """Attribute errors are logged. No handler added to C{pdata}."""61        import_mock = self.mocker.replace(importer.import_module,62                                          passthrough=False)63        import_mock(self.expected_module_name)64        self.mocker.result(self.module_fake)65        self.mocker.throw(AttributeError())66        self.mocker.replay()67        handlers.walker_handle_handler(self.data, self.ctype, self.filename,68                                       self.payload)69        self.assertEqual(0, self.data["handlercount"])70class TestHandlerHandlePart(MockerTestCase):71    def setUp(self):72        self.data = "fake data"73        self.ctype = "fake ctype"74        self.filename = "fake filename"75        self.payload = "fake payload"76        self.frequency = settings.PER_INSTANCE77        self.headers = {...test_agent_types.py
Source:test_agent_types.py  
1#    Licensed under the Apache License, Version 2.0 (the "License"); you may2#    not use this file except in compliance with the License. You may obtain3#    a copy of the License at4#5#         http://www.apache.org/licenses/LICENSE-2.06#7#    Unless required by applicable law or agreed to in writing, software8#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT9#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the10#    License for the specific language governing permissions and limitations11#    under the License.12from unittest import mock13from opflexagent import gbp_agent14from opflexagent.test import base15from oslo_config import cfg16class TestGBPOpflexAgentTypes(base.OpflexTestBase):17    def setUp(self):18        super(TestGBPOpflexAgentTypes, self).setUp()19        cfg.CONF.set_default('quitting_rpc_timeout', 10, 'AGENT')20        # UTs will hang when run from tox w/o this21        self.signal_patch = mock.patch('signal.signal')22        self.signal_patch.start()23    def tearDown(self):24        super(TestGBPOpflexAgentTypes, self).tearDown()25        self.signal_patch.stop()26    def test_opflex_agent_mode(self):27        opflex_agent = mock.patch('opflexagent.gbp_agent.GBPOpflexAgent')28        opflex_patch = opflex_agent.start()29        metadata_mgr = mock.patch(30            'opflexagent.as_metadata_manager.AsMetadataManager')31        metadata_patch = metadata_mgr.start()32        cfg.CONF.set_override('agent_mode', 'opflex', 'OPFLEX')33        resources = [34            mock.patch('os.path.basename'),35            mock.patch('sys.argv')]36        with base.nested_context_manager(*resources):37            gbp_agent.main()38            self.assertEqual(1, opflex_patch.call_count)39            self.assertEqual(1, metadata_patch.call_count)40        opflex_agent.stop()41        metadata_mgr.stop()42    def test_dvs_agent_mode(self):43        mock_dvs_instance = mock.MagicMock()44        import_mock = mock.patch('importlib.import_module',45                                 return_value=mock_dvs_instance)46        import_patch = import_mock.start()47        cfg.CONF.set_override('agent_mode', 'dvs', 'OPFLEX')48        resources = [49            mock.patch('os.path.basename'),50            mock.patch('sys.argv')]51        with base.nested_context_manager(*resources):52            gbp_agent.main()53            self.assertEqual(1, import_patch.call_count)54            self.assertEqual(55                1, mock_dvs_instance.create_agent_config_map.call_count)56        import_mock.stop()57    def test_dvs_agent_no_binding_mode(self):58        mock_dvs_instance = mock.MagicMock()59        import_mock = mock.patch('importlib.import_module',60                                 return_value=mock_dvs_instance)61        import_patch = import_mock.start()62        cfg.CONF.set_override('agent_mode', 'dvs_no_binding', 'OPFLEX')63        resources = [64            mock.patch('os.path.basename'),65            mock.patch('sys.argv')]66        with base.nested_context_manager(*resources):67            gbp_agent.main()68            self.assertEqual(1, import_patch.call_count)69            self.assertEqual(70                1, mock_dvs_instance.create_agent_config_map.call_count)71        import_mock.stop()72    def test_dvs_agent_mode_no_package(self):73        import_mock = mock.patch('importlib.import_module',74                                 side_effect=ValueError)75        import_patch = import_mock.start()76        cfg.CONF.set_override('agent_mode', 'dvs', 'OPFLEX')77        resources = [78            mock.patch('os.path.basename'),79            mock.patch('sys.argv'),80        ]81        with base.nested_context_manager(*resources):82            with mock.patch('sys.exit') as sys_patch:83                try:84                    gbp_agent.main()85                except AttributeError:86                    self.assertEqual(1, sys_patch.call_count)87                self.assertEqual(1, import_patch.call_count)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
