Best Python code snippet using molecule_python
test_topology_classes.py
Source:test_topology_classes.py  
...49        kwargs = node.as_dict()50        node = Node(**kwargs)51        self.assertEqual(node.systemmac, systemmac)52    def test_create_node_systemmac_only(self):53        systemmac = random_string()54        node = Node(systemmac=systemmac)55        self.assertEqual(node.systemmac, systemmac)56    @classmethod57    def test_create_node_failure(cls):58        try:59            _ = Node()60        except TypeError:61            pass62    def test_create_node_neighbors_valid(self):63        nodeattrs = create_node()64        remote_device = random_string()65        remote_interface = random_string()66        neighbors = {'Ethernet1': {'device': remote_device, 67                                   'port': remote_interface}}68        nodeattrs.add_neighbors(neighbors)69        kwargs = nodeattrs.as_dict()70        node = Node(**kwargs)71        self.assertIsNotNone(node.neighbors('Ethernet1'))72        self.assertEqual(node.neighbors('Ethernet1')[0].device, 73                         remote_device)74        self.assertEqual(node.neighbors('Ethernet1')[0].interface, 75                         remote_interface)76    def test_create_node_neighbors_remote_interface_missing(self):77        nodeattrs = create_node()78        remote_device = random_string()79        neighbors = {'Ethernet1': {'remote_device': remote_device}}80        nodeattrs.add_neighbors(neighbors)81        kwargs = nodeattrs.as_dict()82        try:83            node = None84            node = Node(**kwargs)85        except NodeError:86            pass87        finally:88            self.assertIsNone(node)89    def test_create_node_neighbors_remote_device_missing(self):90        nodeattrs = create_node()91        remote_interface = random_string()92        neighbors = {'Ethernet1': {'remote_interface': remote_interface}}93        nodeattrs.add_neighbors(neighbors)94        kwargs = nodeattrs.as_dict()95        try:96            node = None97            node = Node(**kwargs)98        except NodeError:99            pass100        finally:101            self.assertIsNone(node)102    def test_add_neighbor(self):103        systemmac = random_string()104        peer = Mock()105        intf = random_string()106        node = Node(systemmac=systemmac)107        node.add_neighbor(intf, [dict(device=peer.remote_device, 108                                      port=peer.remote_interface)])109        self.assertIsNotNone(node.neighbors(intf))110        self.assertEqual(node.neighbors(intf)[0].device, 111                         peer.remote_device)112        self.assertEqual(node.neighbors(intf)[0].interface, 113                         peer.remote_interface)114    def test_add_neighbor_existing_interface(self):115        systemmac = random_string()116        peer = Mock()117        intf = random_string()118        node = Node(systemmac=systemmac)119        node.add_neighbor(intf, [dict(device=peer.remote_device, 120                                      port=peer.remote_interface)])121        self.assertRaises(NodeError, node.add_neighbor,122                          intf, [dict(device=peer.remote_device, 123                                      port=peer.remote_interface)])124    def test_add_neighbors_success(self):125        nodeattrs = create_node()126        remote_device = random_string()127        remote_interface = random_string()128        neighbors = {'Ethernet1': [{'device': remote_device, 129                                    'port': remote_interface}]}130        kwargs = nodeattrs.as_dict()131        node = Node(**kwargs)132        node.add_neighbors(neighbors)133        self.assertIsNotNone(node.neighbors('Ethernet1'))134        self.assertEqual(node.neighbors('Ethernet1')[0].device, 135                         remote_device)136        self.assertEqual(node.neighbors('Ethernet1')[0].interface, 137                         remote_interface)138    def test_serialize_success(self):139        nodeattrs = create_node()140        kwargs = nodeattrs.as_dict()141        node = Node(**kwargs)142        result = node.serialize()143        self.assertEqual(result, nodeattrs.as_dict())144class FunctionsUnitTests(unittest.TestCase):145    def test_exactfunction_true(self):146        value = random_string()147        func = ExactFunction(value)148        self.assertTrue(func.match(value))149    def test_exactfunction_false(self):150        value = random_string()151        func = ExactFunction(value)152        self.assertFalse(func.match(random_string()))153    def test_includesfunction_true(self):154        value = random_string()155        func = IncludesFunction(value)156        self.assertTrue(func.match(value))157    def test_includesfunction_false(self):158        value = random_string()159        func = IncludesFunction(value)160        self.assertFalse(func.match(random_string()))161    def test_excludesfunction_true(self):162        value = random_string()163        func = ExcludesFunction(value)164        self.assertTrue(func.match(random_string()))165    def test_excludesfunction_false(self):166        value = random_string()167        func = ExcludesFunction(value)168        self.assertFalse(func.match(value))169    def test_regexfunction_true(self):170        value = r'[\w+]'171        func = RegexFunction(value)172        self.assertTrue(func.match(random_string()))173    def test_regexfunction_false(self):174        value = '[^a-zA-Z0-9]'175        func = RegexFunction(value)176        self.assertFalse(func.match(random_string()))177class TestPattern(unittest.TestCase):178    def test_create_pattern_with_defaults(self):179        obj = Pattern(None, None, None)180        self.assertIsInstance(obj, Pattern)181    def test_create_pattern_with_kwargs(self):182        obj = Pattern(name='test',183                                         definition='test',184                                         node='abc123',185                                         variables={'var': 'test'},186                                         interfaces=[{'Ethernet1': 'any'}])187        self.assertEqual(obj.name, 'test')188        self.assertEqual(obj.definition, 'test')189        self.assertEqual(obj.node, 'abc123')190        self.assertDictEqual({'var': 'test'}, obj.variables)191        self.assertEqual(1, len(obj.interfaces))192    def test_add_interface(self):193        obj = Pattern(interfaces=[{'Ethernet1': 'any'}])194        self.assertEqual(len(obj.interfaces), 1)195class PatternUnitTests(unittest.TestCase):196    def test_create_pattern(self):197        pattern = Pattern(random_string())198        self.assertIsInstance(pattern, Pattern)199    def test_create_pattern_kwargs(self):200        kwargs = dict(name=random_string(),201                      definition=random_string(),202                      interfaces=None)203        pattern = Pattern(**kwargs)204        self.assertIsInstance(pattern, Pattern)205    @classmethod206    def test_add_interface_success(cls):207        kwargs = dict(name=random_string(),208                      definition=random_string(),209                      interfaces=None)210        pattern = Pattern(**kwargs)211        remote_remote_device = random_string()212        remote_intf = random_string()213        neighbors = dict(Ethernet1={'device': remote_remote_device,214                                    'port': remote_intf})215        pattern.add_interface(neighbors)216            217    def test_add_interface_failure(self):218        kwargs = dict(name=random_string(),219                      definition=random_string(),220                      interfaces=None)221        pattern = Pattern(**kwargs)222        self.assertRaises(PatternError, pattern.add_interface, 223                          random_string())224class TestInterfacePattern(unittest.TestCase):225    def test_create_interface_pattern(self):226        intf = 'Ethernet1'227        remote_device = random_string()228        remote_interface = random_string()229        obj = InterfacePattern(intf, remote_device,230                               remote_interface,231                               random_string())232        reprobj = 'InterfacePattern(interface=%s, remote_device=%s, ' \233                   'remote_interface=%s)' % \234                  (intf, remote_device, remote_interface)235        self.assertEqual(repr(obj), reprobj)236    def test_match_success(self):237        interface = random_string()238        remote_device = random_string()239        remote_interface = random_string()240        neighbor = Neighbor(remote_device, remote_interface)241        for intf in ['any', interface]:242            for remote_d in ['any', remote_device]:243                for remote_i in ['any', remote_interface]:244                    245                    pattern = InterfacePattern(intf, remote_d, remote_i,246                                               random_string())247                    result = pattern.match(interface, [neighbor])248                    self.assertTrue(result)249    def test_match_failure(self):250        interface = random_string()251        remote_device = random_string()252        remote_interface = random_string()253        for intf in ['none', interface + 'dummy']:254            pattern = InterfacePattern(intf, remote_device, 255                                       remote_interface,256                                       random_string())257            neighbor = Neighbor(remote_device, remote_interface)258            result = pattern.match(interface, [neighbor])259            self.assertFalse(result)260        for remote_d in ['none', remote_device + 'dummy']:261            pattern = InterfacePattern(interface, remote_d, 262                                       remote_interface,263                                       random_string())264            neighbor = Neighbor(remote_device, remote_interface)265            result = pattern.match(interface, [neighbor])266            self.assertFalse(result)267        for remote_i in ['none', remote_interface + 'dummy']:268            pattern = InterfacePattern(interface, remote_device, 269                                       remote_i, random_string())270            neighbor = Neighbor(remote_device, remote_interface)271            result = pattern.match(interface, [neighbor])272            self.assertFalse(result)273        for remote_d in ['none', remote_device + 'dummy']:274            for remote_i in ['none', remote_interface + 'dummy']:275                pattern = InterfacePattern(interface, remote_d, 276                                           remote_i, random_string())277                neighbor = Neighbor(remote_device, remote_interface)278                result = pattern.match(interface, [neighbor])279                self.assertFalse(result)280        for intf in ['none', interface + 'dummy']:281            for remote_i in ['none', remote_interface + 'dummy']:282                pattern = InterfacePattern(intf, remote_device, 283                                           remote_i, random_string())284                neighbor = Neighbor(remote_device, remote_interface)285                result = pattern.match(interface, [neighbor])286                self.assertFalse(result)287        for intf in ['none', interface + 'dummy']:288            for remote_d in ['none', remote_device + 'dummy']:289                pattern = InterfacePattern(intf, remote_d, 290                                           remote_interface, random_string())291                neighbor = Neighbor(remote_device, remote_interface)292                result = pattern.match(interface, [neighbor])293                self.assertFalse(result)294        for intf in ['none', interface + 'dummy']:295            for remote_d in ['none', remote_device + 'dummy']:296                for remote_i in ['none', remote_interface + 'dummy']:297                    pattern = InterfacePattern(intf, remote_d, 298                                               remote_i, random_string())299                    neighbor = Neighbor(remote_device, remote_interface)300                    result = pattern.match(interface, [neighbor])301                    self.assertFalse(result)302    def compile_known_function(self, interface, cls):303        pattern = InterfacePattern(random_string(),304                                   interface,305                                   random_string(),306                                   random_string())307        self.assertIsInstance(pattern.remote_device_re, cls)308    def test_compile_exact_function(self):309        interface = 'exact(\'%s\')' % random_string()310        self.compile_known_function(interface, ExactFunction)311    def test_compile_includes_function(self):312        interface = 'includes(\'%s\')' % random_string()313        self.compile_known_function(interface, IncludesFunction)314    def test_compile_excludes_function(self):315        interface = 'excludes(\'%s\')' % random_string()316        self.compile_known_function(interface, ExcludesFunction)317    def test_compile_regex_function(self):318        interface = 'regex(\'%s\')' % random_string()319        self.compile_known_function(interface, RegexFunction)320    def test_compile_no_function(self):321        interface = random_string()322        self.compile_known_function(interface, ExactFunction)323    def test_compile_unknown_function(self):324        interface = '%s(\'%s\')' % (random_string(), random_string())325        self.assertRaises(InterfacePatternError,326                          InterfacePattern,327                          random_string(), interface,328                          random_string(), random_string())329if __name__ == '__main__':330    enable_logging()...test_repository.py
Source:test_repository.py  
...41from server_test_lib import enable_logging, random_string42class FileObjectUnitTests(unittest.TestCase):43    @patch('ztpserver.serializers.load')44    def test_read_success(self, m_load):45        m_load.return_value = random_string()46        obj = FileObject(random_string())47        result = obj.read()48        self.assertEqual(m_load.return_value, result)49    @patch('ztpserver.serializers.load')50    def test_read_failure(self, m_load):51        m_load.side_effect = SerializerError52        obj = FileObject(random_string())53        self.assertRaises(FileObjectError, obj.read)54    @classmethod55    @patch('ztpserver.serializers.dump')56    def test_write_success(cls, _):57        obj = FileObjectError(random_string())58        obj = FileObject(random_string())59        obj.write(random_string())60    @patch('ztpserver.serializers.dump')61    def test_write_failure(self, m_dump):62        m_dump.side_effect = SerializerError63        obj = FileObject(random_string())64        self.assertRaises(FileObjectError, obj.write, random_string())65class RepositoryUnitTests(unittest.TestCase):66    @classmethod67    @patch('os.makedirs')68    def test_add_folder_success(cls, _):69        store = Repository(random_string())70        store.add_folder(random_string())71    @patch('os.makedirs')72    def test_add_folder_failure(self, m_makedirs):73        m_makedirs.side_effect = OSError74        store = Repository(random_string())75        self.assertRaises(RepositoryError, store.add_folder, random_string())76    @patch('ztpserver.repository.FileObject')77    @patch('os.chmod')78    def test_create_file_success(self, _, m_fileobj):79        store = Repository(random_string())80        store.add_file(random_string())81        self.assertFalse(m_fileobj.return_value.write.called)82    @patch('ztpserver.repository.FileObject')83    @patch('os.chmod')84    def test_create_file_with_contents_success(self, _,85                                               m_fileobj):86        store = Repository(random_string())87        store.add_file(random_string(), random_string())88        self.assertTrue(m_fileobj.return_value.write.called)89            90    @patch('ztpserver.repository.FileObject')91    def test_create_file_failure(self, m_fileobj):92        m_fileobj.return_value.write.side_effect = FileObjectError93        store = Repository(random_string())94        self.assertRaises(FileObjectError, store.add_file,95                          random_string(), random_string())96    @patch('os.path.exists')97    def test_exists_success(self, _):98        store = Repository(random_string())99        result = store.exists(random_string())100        self.assertTrue(result)101    @patch('os.path.exists')102    def test_exists_missing_file(self, m_exists):103        m_exists.return_value = False104        store = Repository(random_string())105        result = store.exists(random_string())106        self.assertFalse(result)107    @patch('os.path.exists')108    @patch('ztpserver.repository.FileObject')109    def test_get_file_success(self, m_fileobj, _):110        store = Repository(random_string())111        store.get_file(random_string())112        self.assertTrue(m_fileobj.called)113    @patch('os.path.exists')114    @patch('ztpserver.repository.FileObject')115    def test_get_file_failure(self, m_fileobj, m_exists):116        m_exists.return_value = False117        store = Repository(random_string())118        self.assertRaises(FileObjectNotFound, store.get_file, random_string())119        self.assertFalse(m_fileobj.called)120    @patch('os.remove')121    def test_delete_file_success(self, m_remove):122        store = Repository(random_string())123        store.delete_file(random_string())124        self.assertTrue(m_remove.called)125    @patch('os.remove')126    def test_delete_file_failure(self, m_remove):127        m_remove.side_effect = OSError128        store = Repository(random_string())129        self.assertRaises(RepositoryError, store.delete_file, random_string())130if __name__ == '__main__':131    enable_logging()...contact.py
Source:contact.py  
...16    if o == "-n":17        n = int(a)18    elif o == "-f":19        f = a20def random_string(prefix, maxlen):21    symbols = string.ascii_letters + string.digits + string.punctuation + " "22    return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])23def random_numbers(prefix, maxlen):24    symbols = string.digits25    return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])26testdata = [Contact(first_name="", middle_name="", last_name="", nickname="", title="", company="", address="",27                    phone_home="", phone_mobile="", phone_work="", fax="", email_1="", email_2="", email_3="",28                    homepage="", address_2="", phone_2="", notes="")] + [29               Contact(first_name=random_string("first name", 10), middle_name=random_string("middle name", 10),30                       last_name=random_string("last name", 10), nickname=random_string("nickname", 10),31                       title=random_string("title", 5), company=random_string("company", 10),32                       address=random_string("address", 20), phone_home=random_numbers("22", 7),33                       phone_mobile=random_numbers("22", 7), phone_work=random_numbers("22", 7),34                       fax=random_numbers("22", 7), email_1=random_string("email1", 10),35                       email_2=random_string("email2", 10), email_3=random_string("email2", 10),36                       homepage=random_string("homepage", 10), address_2=random_string("address2", 10),37                       phone_2=random_numbers("22", 7), notes=random_string("notes", 20))38               for i in range(n)39           ]40file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)41with open(file, "w") as out:42    jsonpickle.set_encoder_options("json", indent=2)...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!!
