Best Python code snippet using tempest_python
test_tempestmail.py
Source:test_tempestmail.py  
1# Licensed under the Apache License, Version 2.0 (the "License");2# you may not use this file except in compliance with the License.3# You may obtain 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,9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or10# implied.11# See the License for the specific language governing permissions and12# limitations under the License.13#14# flake8: noqa15# If extensions (or modules to document with autodoc) are in another directory,16# add these directories to sys.path here. If the directory is relative to the17# documentation root, use os.path.abspath to make it absolute, like shown here.18import datetime19import mock20import re21import tempfile22import unittest23from tempestmail import Config24from tempestmail import Mail25from tempestmail import TempestMailCmd26class MailTest(unittest.TestCase):27    def setUp(self):28        self.config = self._generate_config()29        self.data = self._generate_data()30        self.render_output = self._get_render_template_output()31        self.maxDiff = None32    def _generate_config(self):33        config = Config()34        config.mail_from = 'tripleoresults@gmail.com'35        config.templates_path = 'tests/fixtures/'36        config.log_url = 'http://logs.openstack.org/periodic/'37        config.api_server = 'http://tempest-tripleoci.rhcloud.com/api/v1.0/sendmail'38        config.use_api_server = True39        config.default_log_url = 'http://logs.openstack.org'40        config.username = ''41        config.password = ''42        config.smtp = ''43        config.require_auth = True44        config.emails = [45            {'mail': 'email1@example.com', 'name': 'name 1',46             'jobs': [], 'regex': [], 'topics': ''},47            {'mail': 'email2@example.com', 'name': 'name 2',48             'jobs': [], 'regex': [], 'topics': ''}49            ]50        config.template = 'template.html'51        return config52    def _get_render_template_output(self):53        output = (u'<html>\n    <head></head>\n    <body>\n        '54                  '<p>Hello,</p>\n        <p>Here\'s the result of the latest '55                  'tempest run for job '56                  'periodic-tripleo-ci-centos-7-ovb-ha-tempest.</p>\n        '57                  '<p>The job ran on 2017-01-19 08:27:00.</p>\n        '58                  '<p>For more details, you can check the URL: '59                  'http://logs.openstack.org/periodic/periodic-tripleo-ci-'60                  'centos-7-ovb-ha-tempest/1ce5e95/console.html (It might take '61                  'a few minutes to upload the logs).</p>\n    \n    '62                  '<h2>New failures</h2>\n    <ul>\n    \n        <li>'63                  'tempest.api.object_storage.test_container_quotas.'64                  'ContainerQuotasTest.test_upload_too_many_objects</li>'65                  '\n    \n        <li>tempest.api.object_storage.test_'66                  'container_quotas.ContainerQuotasTest.'67                  'test_upload_valid_object</li>\n    \n    </ul>\n    \n\n    '68                  '\n    \n    \n    <p></p>\n    <p>You are receiving this '69                  'email because someone from TripleO team though you were '70                  'interested in these results.</p>\n    <p>\n    '71                  '</body>\n</html>\n')72        return output73    def _generate_data(self):74        data = {75            'errors': [],76            'run': True,77            'failed': [78                u'tempest.api.object_storage.test_container_quotas.ContainerQuotasTest.test_upload_too_many_objects',79                u'tempest.api.object_storage.test_container_quotas.ContainerQuotasTest.test_upload_valid_object'80            ],81            'job': 'periodic-tripleo-ci-centos-7-ovb-ha-tempest',82            'link': u'http://logs.openstack.org/periodic/periodic-tripleo-ci-centos-7-ovb-ha-tempest/1ce5e95/console.html',83            'covered': [],84            'date': datetime.datetime(2017, 1, 19, 8, 27),85            'new': [86                u'tempest.api.object_storage.test_container_quotas.ContainerQuotasTest.test_upload_too_many_objects',87                u'tempest.api.object_storage.test_container_quotas.ContainerQuotasTest.test_upload_valid_object'88            ]89        }90        return data91    def test_render_template(self):92        mail = Mail(self.config)93        content = mail.render_template(self.data)94        self.assertEqual(self.render_output, content)95    def test_filter_emails(self):96        mail = Mail(self.config)97        self.assertEqual(self.data.get('has_errors'), None)98        addresses = mail.filter_emails(99            'periodic-tripleo-ci-centos-7-ovb-ha-tempest', self.data)100        self.assertEqual({'': ['email1@example.com', 'email2@example.com']},101                         addresses)102        mail.config.emails[0]['jobs'].append('another-job')103        addresses = mail.filter_emails(104            'periodic-tripleo-ci-centos-7-ovb-ha-tempest', self.data)105        self.assertEqual({'': ['email2@example.com']}, addresses)106        self.assertEqual(self.data['has_errors'], True)107        mail.config.emails[0]['jobs'] = []108        mail.config.emails[0]['regex'].append(re.compile(109            'tempest.some.regex'))110        self.assertEqual({'': ['email2@example.com']}, addresses)111    def test_filter_emails_topics(self):112        mail = Mail(self.config)113        addresses = mail.filter_emails(114            'periodic-tripleo-ci-centos-7-ovb-ha-tempest', self.data)115        self.assertEqual({'': ['email1@example.com',116                         'email2@example.com']},117                         addresses)118        mail.config.emails[0]['jobs'].append(119            'periodic-tripleo-ci-centos-7-ovb-ha-tempest')120        mail.config.emails[0]['regex'].append(re.compile(121            'upload_too_many_objects'))122        mail.config.emails[0]['topics'] = 'many_objects'123        mail.config.emails[1]['regex'].append(re.compile(124            'upload_valid_object'))125        mail.config.emails[1]['topics'] = 'valid_object'126        new = {'mail': 'email2@example.com', 'name': 'name 2',127               'jobs': ['periodic-tripleo-ci-centos-7-ovb-ha-tempest'],128               'regex': [re.compile('upload_valid_object')],129               'topics': 'valid_object,object_storage'}130        mail.config.emails.append(new)131        addresses = mail.filter_emails(132            'periodic-tripleo-ci-centos-7-ovb-ha-tempest', self.data)133        bookaddr = {'[many_objects]': ['email1@example.com'],134                    '[valid_object]': ['email2@example.com'],135                    '[valid_object][object_storage]': ['email2@example.com']}136        self.assertEqual(bookaddr, addresses)137    @mock.patch('tempestmail.Mail._send_mail_api')138    @mock.patch('tempestmail.Mail._send_mail_local')139    def test_send_mail(self, mock_local, mock_api):140        mail = Mail(self.config)141        mail.send_mail('periodic-tripleo-ci-centos-7-ovb-ha-tempest',142                       self.data, False)143        mock_api.assert_called_with(['email1@example.com',144                                     'email2@example.com'],145                                    self.render_output,146                                    'Job periodic-tripleo-ci-centos-7-ovb-ha-'147                                    'tempest results')148        mock_local.assert_not_called()149        mock_api.reset_mock()150        self.config.use_api_server = False151        mail = Mail(self.config)152        mail.send_mail('periodic-tripleo-ci-centos-7-ovb-ha-tempest',153                       self.data, False)154        mock_local.assert_called_with(['email1@example.com',155                                       'email2@example.com'],156                                      self.render_output,157                                      'Job periodic-tripleo-ci-centos-7-ovb-ha-'158                                      'tempest results', False)159class TestTempestMailCmd(unittest.TestCase):160    def setUp(self):161        self.content_job = self._get_content_file(162            'tests/fixtures/content_job.html')163        self.console_ok = self._get_content_file(164            'tests/fixtures/console_ok.log')165        self.console_fail = self._get_content_file(166            'tests/fixtures/console_fail.log')167        self.fd_file, self.tmp_file = tempfile.mkstemp()168        self._populate_skip_file()169    def _get_content_file(self, filename):170        with open(filename) as f:171            content = f.read()172        return content173    def _populate_skip_file(self):174        content = '''175        known_failures:176        - test: '.*test_external_network_visibility'177          reason: 'Tempest test "external network visibility" fails'178          lp: 'https://bugs.launchpad.net/tripleo/+bug/1577769'179        - test: 'tempest.api.data_processing'180          reason: 'tempest.api.data_processing tests failing on newton'181          bz: 'https://bugzilla.redhat.com/show_bug.cgi?id=1357667'182        - test: 'neutron.tests.tempest.api.test_revisions.TestRevisions'183          reason: 'New test, need investigation'184        '''185        self.skip_file = open(self.tmp_file, 'w')186        self.skip_file.write(content)187        self.skip_file.close()188    @mock.patch('tempestmail.get_html')189    def test_get_index(self, html_mock):190        tmc = TempestMailCmd()191        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',192                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'193                             'oooq-master'])194        tmc.setup_logging()195        tmc.setupConfig()196        html_mock.return_value.content.decode.return_value = self.content_job.decode()197        index = tmc.get_index()198        self.assertEqual(199            index,200            [(u'http://logs.openstack.org/periodic/periodic-tripleo-ci'201             '-centos-7-ovb-nonha-tempest-oooq-master/613de4e/')])202        html_mock.return_value.content.decode.return_value = 'No links'203        index = tmc.get_index()204        self.assertEqual(index, [])205        html_mock.return_value = None206        index = tmc.get_index()207        self.assertEqual(index, [])208        html_mock.ok.return_value = None209        index = tmc.get_index()210        self.assertEqual(index, [])211        html_mock.ok.return_value = True212        html_mock.content.return_value = None213        index = tmc.get_index()214        self.assertEqual(index, [])215    @mock.patch('tempestmail.get_html')216    def test_get_console(self, html_mock):217        tmc = TempestMailCmd()218        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',219                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'220                             'oooq-master', '--file',221                             'tests/fixtures/console_ok.log'])222        tmc.setup_logging()223        tmc.setupConfig()224        console, date, log_path = tmc.get_console()225        self.assertEqual(console, self.console_ok)226        self.assertEqual(log_path, None)227        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',228                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'229                             'oooq-master', '--file',230                             'tests/fixtures/not_found.log'])231        self.assertEqual(tmc.get_console(), (None, None, None))232        html_mock.return_value.status_code = '300'233        result = tmc.get_console(job_url='http://logs.openstack.org')234        self.assertEqual(result, (None, None, None))235        html_mock.return_value.status_code = '200'236        html_mock.return_value.content = self.console_ok237        console, date, url = tmc.get_console(238            job_url='http://logs.openstack.org')239        self.assertEqual(console, self.console_ok.decode('utf-8'))240        self.assertEqual(url, 'http://logs.openstack.org/console.html.gz')241        html_mock.return_value = None242        result = tmc.get_console(job_url='http://logs.openstack.org')243        self.assertEqual(result, (None, None, None))244    def test_get_data(self):245        tmc = TempestMailCmd()246        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',247                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'248                             'oooq-master', '--file',249                             'tests/fixtures/not_found.log'])250        tmc.setup_logging()251        tmc.setupConfig()252        data = tmc.get_data(self.console_ok, None, 'http://logs.openstack.org')253        self.assertEqual(254            data['job'],255            'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-oooq-master')256        self.assertEqual(data['date'], None)257        self.assertEqual(data['run'], True)258        self.assertEqual(data['link'], 'http://logs.openstack.org')259        self.assertEqual(len(data['ok']), 2)260        self.assertEqual(data.get('failed'), None)261        self.assertEqual(data.get('covered'), None)262        self.assertEqual(data.get('new'), None)263        self.assertEqual(data.get('errors'), None)264        data = tmc.get_data('some content', None, 'http://logs.openstack.org')265        self.assertEqual(data['run'], False)266        data = tmc.get_data(self.console_fail, None,267                            'http://logs.openstack.org')268        self.assertNotEqual(data['failed'], None)269    def test_load_skip_file(self):270        tmc = TempestMailCmd()271        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',272                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'273                             'oooq-master', '--file',274                             'tests/fixtures/not_found.log', '--skip-file',275                             self.tmp_file])276        tmc.setup_logging()277        tmc.setupConfig()278        result = tmc.load_skip_file(self.tmp_file)279        expected = [280            {'test': '.*test_external_network_visibility',281             'reason': 'Tempest test "external network visibility" fails'},282            {'test': 'tempest.api.data_processing',283             'reason': 'tempest.api.data_processing tests failing on newton'},284            {'test': 'neutron.tests.tempest.api.test_revisions.TestRevisions',285             'reason': 'New test, need investigation'}286        ]287        self.assertEqual(result, expected)288        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',289                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'290                             'oooq-master', '--file',291                             'tests/fixtures/not_found.log', '--skip-file',292                             'non_exist_file.txt'])293        result = tmc.load_skip_file(self.tmp_file)294        self.assertEqual(result, [])295    def test_setup_config(self):296        tmc = TempestMailCmd()297        tmc.parse_arguments(['-c', 'tests/fixtures/config.yaml', '--job',298                             'periodic-tripleo-ci-centos-7-ovb-nonha-tempest-'299                             'oooq-master', '--file',300                             'tests/fixtures/not_found.log', '--skip-file',301                             self.tmp_file])302        tmc.setup_logging()303        tmc.setupConfig()304        config = tmc.config305        self.assertEqual(config.require_auth, True)306        self.assertEqual(config.mail_from, 'tripleoresults@gmail.com')307        self.assertEqual(config.templates_path, 'template/')308        self.assertEqual(309            config.log_url,310            'http://logs.openstack.org/periodic/')311        self.assertEqual(312            config.api_server,313            'http://tempest-tripleoci.rhcloud.com/api/v1.0/sendmail')314        self.assertEqual(config.use_api_server, True)...test_container_quotas.py
Source:test_container_quotas.py  
...44        super(ContainerQuotasTest, self).tearDown()45    @test.idempotent_id('9a0fb034-86af-4df0-86fa-f8bd7db21ae0')46    @test.requires_ext(extension='container_quotas', service='object')47    @test.attr(type="smoke")48    def test_upload_valid_object(self):49        """Attempts to uploads an object smaller than the bytes quota."""50        object_name = data_utils.rand_name(name="TestObject")51        data = data_utils.arbitrary_string(QUOTA_BYTES)52        nbefore = self._get_bytes_used()53        resp, _ = self.object_client.create_object(54            self.container_name, object_name, data)55        self.assertHeaders(resp, 'Object', 'PUT')56        nafter = self._get_bytes_used()57        self.assertEqual(nbefore + len(data), nafter)58    @test.idempotent_id('22eeeb2b-3668-4160-baef-44790f65a5a0')59    @test.requires_ext(extension='container_quotas', service='object')60    @test.attr(type="smoke")61    def test_upload_large_object(self):62        """Attempts to upload an object lagger than the bytes quota."""...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!!
