Best Python code snippet using tempest_python
test_network_basic_ops.py
Source:test_network_basic_ops.py  
...628            msg='After router rescheduling')629    @test.requires_ext(service='network', extension='port-security')630    @test.idempotent_id('7c0bb1a2-d053-49a4-98f9-ca1a1d849f63')631    @test.services('compute', 'network')632    def test_port_security_macspoofing_port(self):633        """Tests port_security extension enforces mac spoofing634        Neutron security groups always apply anti-spoof rules on the VMs. This635        allows traffic to originate and terminate at the VM as expected, but636        prevents traffic to pass through the VM. Anti-spoof rules are not637        required in cases where the VM routes traffic through it.638        The test steps are :639        1. Create a new network.640        2. Connect (hotplug) the VM to a new network.641        3. Check the VM can ping the DHCP interface of this network.642        4. Spoof the mac address of the new VM interface.643        5. Check the Security Group enforces mac spoofing and blocks pings via644           spoofed interface (VM cannot ping the DHCP interface).645        6. Disable port-security of the spoofed port- set the flag to false.646        7. Retest 3rd step and check that the Security Group allows pings via...exclude_tests.py
Source:exclude_tests.py  
1#!/usr/bin/python2import click3import subprocess4JUJU='juju'5JUJU_RC='admin-openrc.sh'6DIRECTOR='director'7DIRECTOR_RC='overcloudrc'8# Dictionary that shows which tempest tests to exclude, by release9excluded_test_matrix = {10    'stable/newton': [11        ('tempest.api.network.test_floating_ips.FloatingIPTestJSON.test_floating_ip_update_different_router',12         'Test uses overlapping CIDRs in the same VRF'),13        ('tempest.api.network.test_networks.NetworksTest.test_external_network_visibility',14         'BUG: https://github.com/noironetworks/support/issues/916'),15        ('tempest.api.network.test_security_groups.SecGroupTest.test_create_show_delete_security_group_rule',16         'BUG: https://github.com/noironetworks/support/issues/710'),17        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_subnet_details',18         "BIG: https://github.com/noironetworks/support/issues/915"),19        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_update_router_admin_state',20         'BUG: https://github.com/noironetworks/support/issues/491'),21        ('neutron.tests.tempest.api.test_floating_ips_negative.FloatingIPNegativeTestJSON.test_associate_floatingip_with_port_with_floatingip',22         'Test uses overlapping CIDRs in the same VRF'),23        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_create_sg_with_timestamp',24         'BUG: https://github.com/noironetworks/support/issues/710'),25        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_create_sgrule_with_timestamp',26         'BUG: https://github.com/noironetworks/support/issues/710'),27        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_show_sg_attribute_with_timestamp',28         'BUG: https://github.com/noironetworks/support/issues/710'),29        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_show_sgrule_attribute_with_timestamp',30         'BUG: https://github.com/noironetworks/support/issues/710'),31        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_update_sg_with_timestamp',32         'BUG: https://github.com/noironetworks/support/issues/710')33    ],34    'stable/ocata': [35        ('tempest.api.network.test_floating_ips.FloatingIPTestJSON.test_floating_ip_update_different_router',36         'Test uses overlapping CIDRs in the same VRF'),37        ('tempest.api.network.test_networks.NetworksTest.test_external_network_visibility',38         'BUG: https://github.com/noironetworks/support/issues/916'),39        ('tempest.api.network.test_security_groups.SecGroupTest.test_create_show_delete_security_group_rule',40         'BUG: https://github.com/noironetworks/support/issues/710'),41        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_subnet_details',42         "BIG: https://github.com/noironetworks/support/issues/915"),43        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_update_router_admin_state',44         'BUG: https://github.com/noironetworks/support/issues/491'),45        ('neutron.tests.tempest.api.test_floating_ips_negative.FloatingIPNegativeTestJSON.test_associate_floatingip_with_port_with_floatingip',46         'Test uses overlapping CIDRs in the same VRF'),47        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_create_sg_with_timestamp',48         'BUG: https://github.com/noironetworks/support/issues/710'),49        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_create_sgrule_with_timestamp',50         'BUG: https://github.com/noironetworks/support/issues/710'),51        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_show_sg_attribute_with_timestamp',52         'BUG: https://github.com/noironetworks/support/issues/710'),53        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_show_sgrule_attribute_with_timestamp',54         'BUG: https://github.com/noironetworks/support/issues/710'),55        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_update_sg_with_timestamp',56         'BUG: https://github.com/noironetworks/support/issues/710')57    ],58    'stable/pike': [59        ('tempest.api.network.test_floating_ips.FloatingIPTestJSON.test_floating_ip_update_different_router',60         'Test uses overlapping CIDRs in the same VRF'),61        ('tempest.api.network.test_networks.NetworksTest.test_external_network_visibility',62         'BUG: https://github.com/noironetworks/support/issues/916'),63        ('tempest.api.network.test_security_groups.SecGroupTest.test_create_show_delete_security_group_rule',64         'BUG: https://github.com/noironetworks/support/issues/710'),65        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_subnet_details',66         "BIG: https://github.com/noironetworks/support/issues/915"),67        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_update_router_admin_state',68         'BUG: https://github.com/noironetworks/support/issues/491'),69        ('neutron.tests.tempest.api.test_floating_ips_negative.FloatingIPNegativeTestJSON.test_associate_floatingip_with_port_with_floatingip',70         'Test uses overlapping CIDRs in the same VRF'),71        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_create_sg_with_timestamp',72         'BUG: https://github.com/noironetworks/support/issues/710'),73        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_create_sgrule_with_timestamp',74         'BUG: https://github.com/noironetworks/support/issues/710'),75        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_show_sg_attribute_with_timestamp',76         'BUG: https://github.com/noironetworks/support/issues/710'),77        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_show_sgrule_attribute_with_timestamp',78         'BUG: https://github.com/noironetworks/support/issues/710'),79        ('neutron.tests.tempest.api.test_timestamp.TestTimeStampWithSecurityGroup.test_update_sg_with_timestamp',80         'BUG: https://github.com/noironetworks/support/issues/710')81    ],82    'stable/queens': [83        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_subnet_details',84         "BIG: https://github.com/noironetworks/support/issues/915"),85        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_update_router_admin_state',86         'BUG: https://github.com/noironetworks/support/issues/491'),87        ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.test_port_security_macspoofing_port',88         'Why is this failing?'),89        ('tempest.api.network.test_floating_ips.FloatingIPTestJSON.test_floating_ip_update_different_router',90         'Test uses overlapping CIDRs in the same VRF'),91        ('tempest.api.compute.servers.test_attach_interfaces.AttachInterfacesTestJSON.test_create_list_show_delete_interfaces_by_fixed_ip',92         'Upstream bug: https://bugs.launchpad.net/tempest/+bug/1790864'),93        ('neutron_tempest_plugin.api.test_revisions.TestRevisions.test_update_network_constrained_by_revision',94         'Why is this test failing?'),95        ('neutron_tempest_plugin.api.test_timestamp.TestTimeStampWithL3.test_show_floatingip_attribute_with_timestamp',96         'Why is this test failing?'),97        ('neutron_tempest_plugin.scenario.test_connectivity.NetworkConnectivityTest.test_connectivity_through_2_routers',98         'The apic_aim mechanism driver does not support transit routes (connect networks to same neutron router instead)'),99        ('neutron_tempest_plugin.scenario.test_internal_dns.InternalDNSTest.test_dns_domain_and_name',100         'This is an upstream bug (non-optimized has same failure)')101    ],102}103class Excluder(object):104    def __init__(self, undercloud_type=DIRECTOR):105        if undercloud_type == DIRECTOR:106            self.KEY = 'source ~/' + DIRECTOR_RC + ' && '107        elif undercloud_type == JUJU:108            self.KEY = 'source ~/' + JUJU_RC + ' && '109        self.KEY = 'source ~/' + DIRECTOR_RC + ' && '110        self.version = self.get_openstack_version()111    def get_openstack_version(self):112        # we rely on the openstack client repo113        cmd1 = "cd python-openstackclient/ && "114        cmd2 = "git status | grep 'branch stable\|eol' "115        cmd3 = "| awk 'NF>1{print $NF}' && cd .."116        cmd = self.KEY + cmd1 + cmd2 + cmd3117        print cmd118        subprocess.check_output(['bash','-c', cmd])119        version_string = subprocess.check_output(['bash','-c', cmd])120        version_list = [version.strip()121                        for version in version_string.split("\n") if version]122        version = version_list[0]123        if version == 'newton-eol':124            version = 'stable/newton'125        return version126        127    def get_test_info(self, test):128        test_pieces = test.split(".")129        path = "-".join(test_pieces[0].split("_")) + "/" + "/".join(test_pieces[0:-2]) + ".py"130        test_class = test_pieces[-2:-1][0]131        test_name = test.split(".")[-1:][0]132        return path, test_class, test_name133    def exclude_tests(self):134        for test, reason in excluded_test_matrix[self.version]:135            path, test_class, test_name = self.get_test_info(test)136            def add_line(file_name, before_line, new_line):137                # find the first instance of the string138                index = None139                all_lines = None140                with open(file_name, "r") as fd:141                    all_lines = fd.readlines()142                for count in range(len(all_lines)):143                    line = all_lines[count]144                    if before_line in line:145                        strip_line = line[:-1]146                        indent_len = len(strip_line) - len(strip_line.strip())147                        indent = line[:indent_len] if indent_len else ''148                        new_line = indent + new_line149                        index = count150                        break151                if index:152                    all_lines.insert(index, new_line)153                    with open(file_name, "w+") as fd:154                        contents = "".join(all_lines)155                        fd.write(contents)156      157            cmd = "egrep testtools %s" % path158            try:159                subprocess.check_output(['bash','-c', cmd])160            except Exception as e:161                # not present, so add testtools162                add_line(path, "import", "import testtools\n")163                pass164            # need to escape backslashes165            166            reason_str = '@testtools.skip("' + reason + '")\n'167            # Skip this test168            add_line(path, 'def ' + test_name, reason_str)169@click.command()170@click.option('--undercloud-type', default='director',171              help='Type of undercloud (juju or director)')172def exclude_tests(undercloud_type):173    excluder = Excluder(undercloud_type=undercloud_type)174    excluder.exclude_tests()175    click.echo("Iniitialization complete, and tempest config generated")176if __name__ == '__main__':...test_tempest_mail.py
Source:test_tempest_mail.py  
1import mock2import os3import unittest4from email.mime.text import MIMEText5import tempestmail.config6import tempestmail.mail7from tempestmail import tests8JOB = 'periodic-tripleo-ci-centos-7-ovb-ha-tempest'9class TestTempestMail(unittest.TestCase):10    def setUp(self):11        self.template_path = os.path.join(os.path.dirname(tests.__file__),12                                          'fixtures', 'mail')13        self.config_file = os.path.join(os.path.dirname(tests.__file__),14                                        'fixtures', 'config_validate',15                                        'good.yaml')16        self.config = tempestmail.config.loadConfig(self.config_file)17        self.config.template_path = self.template_path18        self.job = self.config.jobs[JOB]19        self.fail = [20            ('tempest.scenario.test_volume_boot_pattern.TestVolumeBootPattern.'21             'test_volume_boot_pattern'),22            ('tempest.scenario.test_volume_boot_pattern.TestVolumeBootPattern'23             'V2.test_volume_boot_pattern')24        ]25        self.covered = [26            ('tempest.api.volume.admin.v3.test_user_messages.UserMessagesTest'27             '.test_list_messages'),28            ('tempest.api.identity.v3.test_tokens.TokensV3Test.'29             'test_create_token')30        ]31        self.new = [32            ('tempest.scenario.test_network_basic_ops.TestNetworkBasicOps.'33             'test_port_security_macspoofing_port'),34            ('tempest.scenario.test_network_advanced_server_ops.TestNetworkA'35             'dvancedServerOps.test_server_connectivity_suspend_resume')36        ]37        self.errors = [38            ('tempest.api.volume.test_volumes_snapshots_negative.VolumesV1S'39             'napshotNegativeTestJSON.test_create_snapshot_with_nonexistent_'40             'volume_id'),41            ('tempest.api.volume.test_volumes_negative.VolumesV2NegativeTest.'42             'test_reserve_volume_with_negative_volume_status')43        ]44    def test_render_template(self):45        _mail = tempestmail.mail.Mail(self.config)46        data = {47            'failed': self.fail,48            'covered': self.covered,49            'new': self.new,50            'errors': self.errors51        }52        render = _mail.render_template('template.html', data)53        self.assertIn('<h2>New failures</h2>', render)54        data.pop('new')55        render = _mail.render_template('template.html', data)56        self.assertIn('<h2>Success</h2>', render)57        data.pop('failed')58        render = _mail.render_template('template.html', data)59        self.assertIn('<h2>unexpected failures</h2>', render)60    @mock.patch('smtplib.SMTP')61    def test_send_mail(self, smtp_mock):62        _mail = tempestmail.mail.Mail(self.config)63        data = {64            'failed': self.fail,65            'covered': self.covered,66            'new': self.new,67            'errors': self.errors68        }69        render = _mail.render_template('template.html', data)70        msg = MIMEText(render)71        msg['Subject'] = self.job.subject72        msg['From'] = ''73        msg['To'] = ",".join(['arxcruz@gmail.com'])74        _mail.send_mail(self.job, data)75        smtp_mock.assert_called_once()76        smtp_mock.return_value.sendmail.assert_called_with(77            '', ['arxcruz@gmail.com'], msg.as_string())78        smtp_mock.reset_mock()79        self.job.is_template = False80        self.job.message = 'Hello World'81        msg = MIMEText(self.job.message)82        msg['Subject'] = self.job.subject83        msg['From'] = ''84        msg['To'] = ",".join(['arxcruz@gmail.com'])85        _mail.send_mail(self.job, data)86        smtp_mock.assert_called_once()87        smtp_mock.return_value.sendmail.assert_called_with(...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!!
