Best Python code snippet using localstack_python
views.py
Source:views.py
1#!/usr/bin/env python2# coding=utf-83import commands4import dbus5import uuid6from rest_framework.views import APIView7from rest_framework.response import Response8from rest_framework import status9from . import conststr10import NetworkManager11import nm_common12c = NetworkManager.const13__author__ = 'liushaolin@inspur.com'14class DeviceList(APIView):15 """16 Get network device info and activate or deactivate chosen devices17 """18 def get(self, request, format=None):19 """20 Get network device info21 :param request:22 :param format:23 :return:24 """25 dlist = self.get_devices(request)26 return Response(dlist, status=status.HTTP_200_OK)27 def post(self, request, format=None):28 """29 Change the state of a device or connection30 :param request:31 :param format:32 :return:33 """34 req_dict = request.data35 result = self.change_state(req_dict)36 if result[conststr.RET_CODE] != 0:37 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)38 else:39 return Response(result[conststr.RET_MSG], status=status.HTTP_200_OK)40 def delete(self, request, format=None):41 """42 Delete a connection43 :param request:44 :param format:45 :return:46 """47 result = {}48 req_dict = request.data49 connectionId = req_dict['Uuid']50 try:51 conn = NetworkManager.Settings.GetConnectionByUuid(connectionId)52 except dbus.exceptions.DBusException, reason:53 result[conststr.RET_TYPE] = conststr.FAILED_RES54 result[conststr.RET_MSG] = str(reason).split(':')[-1]55 result[conststr.RET_CODE] = -156 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)57 conn.Delete()58 result[conststr.RET_TYPE] = conststr.SUCCESS_RES59 result[conststr.RET_MSG] = conststr.DELETE_SUCCESS_RES60 result[conststr.RET_CODE] = 061 return Response(result[conststr.RET_MSG], status=status.HTTP_200_OK)62 def get_devices(self, req):63 """64 Get device and connections basic information.65 :param req:66 :return:67 """68 values = req.META69 # Get http host address from meta information70 http_host = values['REMOTE_ADDR']71 devices_dict = {'Devices': []}72 for dev in NetworkManager.NetworkManager.GetDevices():73 # Get ethernet device information74 if c('device_type', dev.DeviceType) == 'ethernet':75 deviceInfo = nm_common.get_ethernet_info(dev, http_host)76 devices_dict['Devices'].append(deviceInfo)77 # Get loopback information78 if c('device_type', dev.DeviceType) == 'generic' and dev.Interface == 'lo':79 deviceInfo = nm_common.get_lo_info(dev, http_host)80 devices_dict['Devices'].append(deviceInfo)81 return devices_dict82 def change_state(self, operation):83 """84 Activate or deactivate a network device or connection85 :param operation:86 :return:87 """88 result = {}89 deviceId = operation['DevName']90 try:91 dev = NetworkManager.NetworkManager.GetDeviceByIpIface(deviceId)92 except dbus.exceptions.DBusException, reason:93 result[conststr.RET_TYPE] = conststr.FAILED_RES94 result[conststr.RET_MSG] = str(reason).split(':')[-1]95 result[conststr.RET_CODE] = -196 return result97 # Activate or deactivate a device/connection98 if operation['Label'] == 'device':99 if operation['Action'] == 'activate':100 cmd = conststr.ACTIVATE_DEVICE_CMD101 else:102 cmd = conststr.DEACTIVATE_DEVICE_CMD103 cmd = cmd % deviceId104 (code, res) = commands.getstatusoutput(cmd)105 if code != 0:106 result[conststr.RET_TYPE] = conststr.FAILED_RES107 result[conststr.RET_MSG] = res108 result[conststr.RET_CODE] = code109 else:110 result[conststr.RET_TYPE] = conststr.SUCCESS_RES111 result[conststr.RET_MSG] = conststr.CHANGE_SUCCESS_RES112 result[conststr.RET_CODE] = 0113 elif operation['Label'] == 'connection':114 connectionId = operation['Uuid']115 try:116 conn = NetworkManager.Settings.GetConnectionByUuid(connectionId)117 except dbus.exceptions.DBusException, reason:118 result[conststr.RET_TYPE] = conststr.FAILED_RES119 result[conststr.RET_MSG] = str(reason).split(':')[-1]120 result[conststr.RET_CODE] = -1121 return result122 if operation['Action'] == 'activate':123 try:124 NetworkManager.NetworkManager.ActivateConnection(conn, dev, '/')125 except dbus.exceptions.DBusException, reason:126 result[conststr.RET_TYPE] = conststr.FAILED_RES127 result[conststr.RET_MSG] = str(reason).split(':')[-1]128 result[conststr.RET_CODE] = -1129 return result130 else:131 try:132 NetworkManager.NetworkManager.DeactivateConnection(conn)133 except dbus.exceptions.DBusException, reason:134 result[conststr.RET_TYPE] = conststr.FAILED_RES135 result[conststr.RET_MSG] = str(reason).split(':')[-1]136 result[conststr.RET_CODE] = -1137 return result138 result[conststr.RET_TYPE] = conststr.SUCCESS_RES139 result[conststr.RET_MSG] = conststr.CHANGE_SUCCESS_RES140 result[conststr.RET_CODE] = 0141 return result142class AddConnection(APIView):143 """144 Add a new connection for a device145 """146 def get(self, request, format=None):147 """148 Get mac address list149 :param request:150 :param format:151 :return:152 """153 mac_address_dict = {'mac-addresses': []}154 mac_address_list = nm_common.get_macs()155 mac_address_dict['mac-addresses'] = mac_address_list156 return Response(mac_address_dict, status=status.HTTP_200_OK)157 def post(self, request, format=None):158 """159 Add a wired connection160 :param request:161 :param format:162 :return:163 """164 result = {}165 connection_info = request.data166 new_connection = {167 '802-3-ethernet': {},168 'connection': {},169 'ipv4': {},170 'ipv6': {},171 }172 connectionId = str(uuid.uuid4())173 if connection_info['Identity']:174 (info_802_3, result) = nm_common.get_802_3_info(**connection_info)175 if result:176 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)177 new_connection['802-3-ethernet'] = info_802_3178 connection = nm_common.get_connection_info(connectionId, **connection_info)179 new_connection['connection'] = connection180 if connection_info['IPv4']:181 (ipv4_info, result) = nm_common.get_ipv4_info(**connection_info)182 if result:183 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)184 new_connection['ipv4'] = ipv4_info185 if connection_info['IPv6']:186 (ipv6_info, result) = nm_common.get_ipv6_info(**connection_info)187 if result:188 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)189 new_connection['ipv6'] = ipv6_info190 NetworkManager.Settings.AddConnection(new_connection)191 result[conststr.RET_TYPE] = conststr.SUCCESS_RES192 result[conststr.RET_MSG] = conststr.ADD_SUCCESS_RES193 result[conststr.RET_CODE] = 0194 return Response(result[conststr.RET_MSG], status=status.HTTP_200_OK)195class ConnectionDetail(APIView):196 """197 Modify configure information of a connection198 """199 def get(self, request, uuid, format=None):200 """201 Get details of a connection,include identity,IPv4,IPv6 information.202 :param request:203 :param uuid:the id of a connection204 :param format:205 :return:206 """207 connectionId = uuid208 conn = NetworkManager.Settings.GetConnectionByUuid(connectionId)209 settings = conn.GetSettings()210 connection_info = {211 'Identity': {},212 'IPv4': {},213 'IPv6': {},214 }215 mac_address_list = nm_common.get_macs()216 connection_info['Identity']['mac-address-list'] = mac_address_list217 if settings['802-3-ethernet']:218 if 'mac-address' in settings['802-3-ethernet']:219 mac_address = settings['802-3-ethernet']['mac-address']220 name = [x['name'] for x in mac_address_list if x['mac-address'] == mac_address][0]221 connection_info['Identity']['mac-address'] = {'name': name, 'mac-address': mac_address}222 else:223 connection_info['Identity']['mac-address'] = ''224 if 'cloned-mac-address' in settings['802-3-ethernet']:225 connection_info['Identity']['cloned-mac-address'] = settings['802-3-ethernet']['cloned-mac-address']226 else:227 connection_info['Identity']['cloned-mac-address'] = ''228 if 'mtu' in settings['802-3-ethernet']:229 connection_info['Identity']['mtu'] = settings['802-3-ethernet']['mtu']230 else:231 connection_info['Identity']['mtu'] = 0232 if settings['connection']:233 connection_info['Identity']['name'] = settings['connection']['id']234 if 'permissions' in settings['connection'] and settings['connection']['permissions']:235 connection_info['Identity']['permissions'] = False236 else:237 connection_info['Identity']['permissions'] = True238 if 'autoconnect' in settings['connection']:239 connection_info['Identity']['autoconnect'] = False240 else:241 connection_info['Identity']['autoconnect'] = True242 if settings['ipv4']:243 if settings['ipv4']['addresses']:244 connection_info['IPv4']['addresses'] = settings['ipv4']['addresses']245 else:246 connection_info['IPv4']['addresses'] = ''247 if settings['ipv4']['dns']:248 connection_info['IPv4']['dns'] = settings['ipv4']['dns']249 else:250 connection_info['IPv4']['dns'] = ''251 if settings['ipv4']['method']:252 connection_info['IPv4']['method'] = settings['ipv4']['method']253 if 'ignore-auto-dns' in settings['ipv4']:254 connection_info['IPv4']['ignore-auto-dns'] = True255 else:256 connection_info['IPv4']['ignore-auto-dns'] = False257 if 'never-default' in settings['ipv4']:258 connection_info['IPv4']['never-default'] = True259 else:260 connection_info['IPv4']['never-default'] = False261 if settings['ipv6']:262 if settings['ipv6']['addresses']:263 connection_info['IPv6']['addresses'] = settings['ipv6']['addresses']264 else:265 connection_info['IPv6']['addresses'] = ''266 if settings['ipv6']['dns']:267 connection_info['IPv6']['dns'] = settings['ipv6']['dns']268 else:269 connection_info['IPv6']['dns'] = ''270 if settings['ipv6']['method']:271 connection_info['IPv6']['method'] = settings['ipv6']['method']272 if 'ignore-auto-dns' in settings['ipv6']:273 connection_info['IPv6']['ignore-auto-dns'] = True274 else:275 connection_info['IPv6']['ignore-auto-dns'] = False276 if 'never-default' in settings['ipv6']:277 connection_info['IPv6']['never-default'] = True278 else:279 connection_info['IPv6']['never-default'] = False280 return Response(connection_info, status=status.HTTP_200_OK)281 def post(self, request, uuid, format=None):282 """283 Reset the configure information of a connection284 :param request:285 :param uuid:the id of a connection286 :param format:287 :return:288 """289 connection_info = request.data290 name = connection_info['Identity']['name']291 result = {}292 connectionId = uuid293 conn = NetworkManager.Settings.GetConnectionByUuid(connectionId)294 settings = conn.GetSettings()295 update_connection = {296 '802-3-ethernet': {},297 'connection': {},298 'ipv4': {},299 'ipv6': {},300 }301 if 'mac-address' in settings['802-3-ethernet']:302 update_connection['802-3-ethernet']['mac-address'] = settings['802-3-ethernet']['mac-address']303 update_connection['connection']['uuid'] = connectionId304 update_connection['connection']['id'] = name305 update_connection['connection']['type'] = '802-3-ethernet'306 update_connection['ipv4'] = {'method': 'auto'}307 update_connection['ipv6'] = {'method': 'auto'}308 conn.Update(update_connection)309 result[conststr.RET_TYPE] = conststr.SUCCESS_RES310 result[conststr.RET_MSG] = conststr.RESET_SUCCESS_RES311 result[conststr.RET_CODE] = 0312 return Response(result[conststr.RET_MSG], status=status.HTTP_200_OK)313 def put(self, request, uuid, format=None):314 """315 Update the configure information of a connection316 :param request:317 :param uuid:the id of a connection318 :param format:319 :return:320 """321 result = {}322 connection_info = request.data323 connectionId = uuid324 update_connection = {325 '802-3-ethernet': {},326 'connection': {},327 'ipv4': {},328 'ipv6': {},329 }330 if connection_info['Identity']:331 (info_802_3, result) = nm_common.get_802_3_info(**connection_info)332 if result:333 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)334 update_connection['802-3-ethernet'] = info_802_3335 connection = nm_common.get_connection_info(connectionId, **connection_info)336 update_connection['connection'] = connection337 if connection_info['IPv4']:338 (ipv4_info, result) = nm_common.get_ipv4_info(**connection_info)339 if result:340 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)341 update_connection['ipv4'] = ipv4_info342 if connection_info['IPv6']:343 (ipv6_info, result) = nm_common.get_ipv6_info(**connection_info)344 if result:345 return Response(result[conststr.RET_MSG], status=status.HTTP_500_INTERNAL_SERVER_ERROR)346 update_connection['ipv6'] = ipv6_info347 conn = NetworkManager.Settings.GetConnectionByUuid(connectionId)348 conn.Update(update_connection)349 result[conststr.RET_TYPE] = conststr.SUCCESS_RES350 result[conststr.RET_MSG] = conststr.UPDATE_SUCCESS_RES351 result[conststr.RET_CODE] = 0...
test_friend_finder2.py
Source:test_friend_finder2.py
...8 def setUpClass(cls) -> None:9 graph = MockGraph()10 # Example from online for testing purposes11 graph.create_connection(0, 1) # a to b12 graph.update_connection(0, 1, 3) # weight 313 graph.create_connection(0, 2) # a to c14 graph.update_connection(0, 2, 5) # weight 515 graph.create_connection(0, 3) # a to d16 graph.update_connection(0, 3, 6) # weight 617 graph.create_connection(1, 3) # b to d18 graph.update_connection(1, 3, 2) # weight 219 graph.create_connection(2, 3) # c to d20 graph.update_connection(2, 3, 2) # weight 221 graph.create_connection(2, 4) # c to e22 graph.update_connection(2, 4, 6) # weight 623 graph.create_connection(2, 5) # c to f24 graph.update_connection(2, 5, 3) # weight 325 graph.create_connection(2, 6) # c to g26 graph.update_connection(2, 6, 7) # weight 727 graph.create_connection(3, 5) # d to f28 graph.update_connection(3, 5, 7) # weight 929 graph.create_connection(4, 5) # e to f30 graph.update_connection(4, 5, 5) # weight 531 graph.create_connection(4, 6) # e to g32 graph.update_connection(4, 6, 2) # weight 733 graph.create_connection(5, 6) # f to g34 graph.update_connection(5, 6, 1) # weight 135 cls.finder = FriendFinder(36 graph37 )38 def testDijkstraCorrectness(self):39 d = self.finder.dijkstra(0) # dijstra for a40 self.assertEqual(d[0], 0) # a = 041 self.assertEqual(d[1], 3) # b = 342 self.assertEqual(d[2], 5) # c = 543 self.assertEqual(d[3], 5) # d = 544 self.assertEqual(d[4], 11) # e = 1145 self.assertEqual(d[5], 8) # f = 846 self.assertEqual(d[6], 9) # g = 947 def testGetRecommendations(self):48 d = self.finder.get_recommendations(2, 0) # get top 2 recommendations...
test_friend_finder.py
Source:test_friend_finder.py
...9 graph = MockGraph()10 # I drew this and did Dijkstra's by hand11 graph.create_connection(0, 1)12 graph.create_connection(0, 2)13 graph.update_connection(0, 2, 1.5)14 graph.create_connection(0, 3)15 graph.update_connection(0, 3, 0.5)16 graph.create_connection(1, 2)17 graph.update_connection(1, 2, 0.4)18 graph.create_connection(2, 4)19 graph.create_connection(2, 3)20 graph.update_connection(2, 3, 0.8)21 graph.create_connection(3, 4)22 graph.update_connection(3, 4, 1.5)23 graph.create_connection(4, 5)24 graph.update_connection(4, 5, 0.2)25 graph.create_connection(4, 6)26 graph.update_connection(4, 6, 0.3)27 cls.finder = FriendFinder(28 graph29 )30 def testDijkstraCorrectness(self):31 d = self.finder.dijkstra(0)32 self.assertEqual(d[0], 0)33 self.assertEqual(d[1], 1.0)34 self.assertEqual(d[2], 1.3)35 self.assertEqual(d[3], 0.5)36 self.assertEqual(d[4], 2)37 self.assertEqual(d[5], 2.2)38 self.assertEqual(d[6], 2.3)39 def testGetRecommendations(self):40 d = self.finder.get_recommendations(2, 0)...
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!!