Best Python code snippet using molotov_python
tests.py
Source:tests.py  
1# file: address/tests.py2from django.test import TestCase3from django.urls import reverse4from django.contrib.auth.models import User5from netdevice.tests import create_router, create_interface6from address.models import ipv6_address, ipv4_address7def create_v4_address(logical_interface, address):8    v4_address = ipv4_address.objects.create(interface=logical_interface,9                                             host=address,10                                             cidr=24,11                                            )12    return  v4_address13def create_v6_address(logical_interface, address):14    v6_address = ipv6_address.objects.create(interface=logical_interface,15                                             host=address,16                                             cidr=64,17                                            )18    return v6_address19class AddressViewTests(TestCase):20    def setUp(self):21        test_user = User.objects.get_or_create(username='testuser')[0]22        self.client.force_login(test_user)23    def test_config_view_with_one_ios_address(self):24        """25        Create a test IOS router, with one ipv4 and one ipv6 address26        then check config view.27        """28        test_router     = create_router('ios')29        test_interface  = create_interface(test_router)30        test_v4_address = create_v4_address(test_interface, '1.1.1.1')31        test_v6_address = create_v6_address(test_interface, '2600::1')32        url             = reverse(33                                  'netdevice:router_config',34                                  kwargs={'router_id': test_router.id},35                                 )36        response = self.client.get(url)37        self.assertEqual(response.status_code, 200)38        self.assertContains(response, 'ip address 1.1.1.1 255.255.255.0')39        self.assertContains(response, 'ipv6 address 2600::1/64')40    def test_config_view_with_one_junos_address(self):41        """42        Create a test JunOS router, with one ipv4 and one ipv6 address43        then check config view.44        """45        test_router     = create_router('junos')46        test_interface  = create_interface(test_router)47        test_v4_address = create_v4_address(test_interface, '1.1.1.1')48        test_v6_address = create_v6_address(test_interface, '2600::1')49        url             = reverse(50                                  'netdevice:router_config',51                                  kwargs={'router_id': test_router.id},52                                 )53        response = self.client.get(url)54        self.assertEqual(response.status_code, 200)55        self.assertContains(response, 'address 1.1.1.1/24')56        self.assertContains(response, 'address 2600::1/64')57    def test_config_view_with_multiple_ios_address(self):58        """59        Create a test IOS router, then add 100 ipv4 and ipv6 addresses,60        confirm they are in the final template.61        """62        test_router     = create_router('ios')63        test_interface  = create_interface(test_router)64        address_count   = 10065        for i in range(1, address_count):66            create_v4_address(test_interface, '1.1.' + str(i) + '.1')67            create_v6_address(test_interface, '2600:' + str(i) + '::1')68        url      = reverse(69                           'netdevice:router_config',70                           kwargs={'router_id': test_router.id},71                          )72        response = self.client.get(url)73        self.assertEqual(response.status_code, 200)74        for i in range(1, address_count):75            self.assertContains(76                                response,77                                'ip address 1.1.' + str(i) + '.1 255.255.255.0'78                               )79            self.assertContains(80                                response,81                                'ipv6 address 2600:' + str(i) + '::1/64'82                               )83    def test_config_view_with_multiple_junos_address(self):84        """85        Create a test IOS router, then add 100 ipv4 and ipv6 addresses,86        confirm they are in the final template.87        """88        test_router     = create_router('junos')89        test_interface  = create_interface(test_router)90        address_count   = 10091        for i in range(1, address_count):92            create_v4_address(test_interface, '1.1.' + str(i) + '.1')93            create_v6_address(test_interface, '2600:' + str(i) + '::1')94        url      = reverse(95                           'netdevice:router_config',96                           kwargs={'router_id': test_router.id},97                          )98        response = self.client.get(url)99        self.assertEqual(response.status_code, 200)100        for i in range(1, address_count):101            self.assertContains(response, 'address 1.1.' + str(i) + '.1/24')102            self.assertContains(response, 'address 2600:' + str(i) + '::1/64')103    def test_ipv6_address_create_form_view(self):104        """105        Create a test router and interface, then test the106        form view of ipv6_address_create is displayed correctly.107        """108        test_router    = create_router('junos')109        test_interface = create_interface(test_router)110        url            = reverse(111                                 'address:ipv6_address_create',112                                 kwargs={113                                         'logical_interface_id':114                                         test_interface.id115                                        },116                                )117        response = self.client.get(url)118        test_text = 'test-router ge-0/0/0.10 (A logical test description.)'119        self.assertEqual(response.status_code, 200)120        self.assertContains(response, test_text)121    def test_ipv4_address_create_form_view(self):122        """123        Create a test router and interface, then test the form view124        of ipv4_address_create is displayed correctly.125        """126        test_router    = create_router('junos')127        test_interface = create_interface(test_router)128        url            = reverse(129                                 'address:ipv4_address_create',130                                 kwargs={131                                         'logical_interface_id':132                                         test_interface.id133                                        },134                                )135        response = self.client.get(url)136        test_text = 'test-router ge-0/0/0.10 (A logical test description.)'137        self.assertEqual(response.status_code, 200)138        self.assertContains(response, test_text)139    def test_ipv6_address_edit_form_view(self):140        """141        Create a test router, interface and address, then test142        the form view of ipv6_address_edit is displayed correctly.143        """144        test_router    = create_router('junos')145        test_interface = create_interface(test_router)146        test_address   = create_v6_address(test_interface, '2001:db8:1::1')147        url            = reverse(148                                 'address:ipv6_address_edit',149                                 kwargs={'ipv6_address_id': test_address.id},150                                )151        response = self.client.get(url)152        test_text = ''.join([153                     '<input type="text" name="host" value="2001:db8:1::1" ',154                     'class="form-control" placeholder="Host" title="" ',155                     'required id="id_host">',156                    ])157        self.assertEqual(response.status_code, 200)158        self.assertContains(response, test_text)159    def test_ipv4_address_edit_form_view(self):160        """161        Create a test router, interface and address, then test162        the form view of ipv4_address_edit is displayed correctly.163        """164        test_router    = create_router('junos')165        test_interface = create_interface(test_router)166        test_address   = create_v4_address(test_interface, '192.0.2.1')167        url            = reverse(168                                 'address:ipv4_address_edit',169                                 kwargs={'ipv4_address_id': test_address.id},170                                )171        response = self.client.get(url)172        test_text = ''.join([173                     '<input type="text" name="host" value="192.0.2.1" ',174                     'class="form-control" placeholder="Host" title="" ',175                     'required id="id_host">',176                    ])177        self.assertEqual(response.status_code, 200)...test_unit_gphostcachelookup.py
Source:test_unit_gphostcachelookup.py  
1#!/usr/bin/env python2#3# Copyright (c) Greenplum Inc 2012. All Rights Reserved. 4#5""" Unittesting for gphostcachelookup module6"""7import os, sys8import unittest9from gppylib import gplog10from gppylib.commands.base import Command, ExecutionError11FILEDIR=os.path.expanduser("~")12FILENAME=".gphostcache"13CACHEFILE = os.path.join(FILEDIR, FILENAME)14logger = gplog.get_unittest_logger()15try:16    if os.getenv('GPHOME') is '':17        raise Exception("Environment variable GPHOME not set")18except Exception, e:19    sys.stderr.write("Exception found: %s \n" % str(e))20GPHOSTLOOKUP = os.path.join(os.getenv('GPHOME'), 'bin/lib/', 'gphostcachelookup.py')21class GpHostCacheLookupTestCase(unittest.TestCase):22    LOOKUP_FAIL_MSG = '__lookup_of_hostname_failed__'23    def test01_gphost_lookup(self):24        """ Test gphostcachelookup for known interface (present in host cache)"""25        self._remove_old_cache_entries()26        test_interface = "localhost"27        hostname = os.uname()[1]28        result = self._run_gphost_lookup(test_interface)29        self.assertEqual(hostname, result)30    def test02_gphost_lookup(self):31        """Test gphostcachelookup for unknown interface (not present in host cache)"""32        test_interface = "foo"33        result = self._run_gphost_lookup(test_interface)34        self.assertIn(self.LOOKUP_FAIL_MSG, result)35    def test03_gphost_lookup(self):36        """Test gphostcachelookup for empty interface name """37        test_interface = ""38        result = self._run_gphost_lookup(test_interface)39        self.assertIn(self.LOOKUP_FAIL_MSG, result)40#-------------------------------- Non-test Helper -----------------------41    def _run_gphost_lookup(self, test_interface):42        """This is a helper function to simply run 'gphostcachelookup.py' for given interface"""43        44        cmd = Command("Running host lookup for given interface",45                        "echo %s | python %s" % (test_interface, GPHOSTLOOKUP))46        try:47            cmd.run(validateAfter = True)48            49        except ExecutionError, e:50            self.fail("ExecutionError %s" % str(e))51        result = cmd.get_results().stdout.strip()52        return result53    def _remove_old_cache_entries(self):54        """ This function will be used to remove already present 'localhost' entries from gphostcache file """55        with open(CACHEFILE, "r") as fr:56            lines = fr.readlines()57        with open(CACHEFILE, "w") as fw:58            for line in lines:59                if "localhost" not in line:60                    fw.write(line)61#------------------------------- Mainline --------------------------------62if __name__ == '__main__':...test_boundary_interface.py
Source:test_boundary_interface.py  
1# -*- coding: utf-8 -*-2"""3Created on Wed May 31 17:45:28 20174@author: mtopper5"""6import pytest7from aneris.boundary.interface import FileInterface8from aneris.control.sockets import NamedSocket9import aneris.test.interfaces as interfaces10def test_FileInterface():11    12    test_interface = 'SPTInterface'13    14    interface = NamedSocket("FileInterface")15    interface.discover_interfaces(interfaces)16    file_interface = interface.get_interface_object(test_interface)17    18    assert isinstance(file_interface, FileInterface)19    20def test_FileInterface_check_path(tmpdir):21    22    test_interface = 'SPTInterface'23    test_path = tmpdir.mkdir("sub").join("test.spt")24    test_path.ensure(file=True)25    test_path_str = str(test_path)26    27    interface = NamedSocket("FileInterface")28    interface.discover_interfaces(interfaces)29    file_interface = interface.get_interface_object(test_interface)30    31    file_interface.set_file_path(test_path_str)32    file_interface.check_path()33    34    assert True35    36def test_FileInterface_check_path_fail_ext(tmpdir):37    38    test_interface = 'SPTInterface'39    test_path = tmpdir.mkdir("sub").join("test.csv")40    test_path.ensure(file=True)41    test_path_str = str(test_path)42    43    interface = NamedSocket("FileInterface")44    interface.discover_interfaces(interfaces)45    file_interface = interface.get_interface_object(test_interface)46    47    file_interface.set_file_path(test_path_str)48    49    with pytest.raises(IOError) as excinfo:50        file_interface.check_path()51    assert 'File extension' in str(excinfo.value)52        53        54def test_FileInterface_check_path_fail_missing(tmpdir):55    56    test_interface = 'SPTInterface'57    test_path = tmpdir.mkdir("sub").join("test.spt")58    test_path_str = str(test_path)59    60    interface = NamedSocket("FileInterface")61    interface.discover_interfaces(interfaces)62    file_interface = interface.get_interface_object(test_interface)63    64    file_interface.set_file_path(test_path_str)65    66    with pytest.raises(IOError) as excinfo:67        file_interface.check_path(check_exists=True)68    assert 'No file or directory exists for path' in str(excinfo.value)69    70    ...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!!
