Best Python code snippet using localstack_python
check_widget.py
Source:check_widget.py  
1# !/usr/bin/env python2# -*- coding: utf-8 -*-3# ==============================================================4#  @Author     : RunningMan5#  @File       : interface.py6#  @Create Time: 2020/03/11 16:15:477# ==============================================================8import os9from widget import *10# ------------------------- class --------------------------11class TaskThread(QtCore.QThread):12    finished = QtCore.Signal(object)13    def __init__(self, cls, check_table, parent=None):14        super(TaskThread, self).__init__(parent)15        self.cls = cls16        self.check_table = check_table17    def run(self):18        try:19            result = self.cls().run()20        except:21            result = 'no'22        # getattr(self.check_table, self.cls.__name__+"label").setVisible(False)23        self.finished.emit(result)24class ImagePlayer(QtWidgets.QLabel):25    def __init__(self, filename, parent=None):26        super(ImagePlayer, self).__init__(parent)27        self.setImg(filename)28        29    def setImg(self, img):30        # Load the file into a QMovie31        self.movie = QtGui.QMovie(img, QtCore.QByteArray(), self)32        # Set gif zize33        self.movie.setScaledSize(QtCore.QSize(30, 30))34        # Make label fit the gif35        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)36        self.setAlignment(QtCore.Qt.AlignCenter)37        # Add the QMovie object to the label38        self.movie.setCacheMode(QtGui.QMovie.CacheAll)39        self.movie.setSpeed(100)40        41        self.setMovie(self.movie)42    def start(self):43        """sart animnation"""44        self.movie.start()45    def clear(self):46        self.movie.destroyed()47class ResultWidget(QtWidgets.QWidget):48    def __init__(self, data, parent=None):49        super(ResultWidget, self).__init__(parent)50        self.setWindowTitle(r"æ£æ¥ç»æ")51        self.resize(600, 400)52        self.data = data53        result_wgt = self.buildWgt()54        lay = QtWidgets.QVBoxLayout(self)55        lay.addWidget(result_wgt)56    57    def buildWgt(self):58        tree_wgt = QtWidgets.QTreeWidget(self)59        tree_wgt.setHeaderHidden(True)60        if isinstance(self.data, dict):61            for key, val in self.data.iteritems():62                root = QtWidgets.QTreeWidgetItem(tree_wgt)63                root.setText(0, key)64                root.setExpanded(True)65                for v in val:66                    root = QtWidgets.QTreeWidgetItem(root)67                    root.setText(0, v)68        elif isinstance(self.data, list):69            for root in self.data:70                root = QtWidgets.QTreeWidgetItem(tree_wgt)71                root.setText(0, key)72        return tree_wgt73class CheckWidget(QtWidgets.QWidget):74    def __init__(self, engine='', parent=None):75        super(CheckWidget, self).__init__(parent)76        self._engine = engine()77        self._par = parent78        self._build_data = self._engine.getCheckingList()79        self._init_ui()80    def _init_ui(self):81        # create check widget82        self.check_btn = QtWidgets.QPushButton('Check')83        self.fix_btn = QtWidgets.QPushButton('Fix All')84        self.check_table = MyTableWidget()85        86        # create layout87        lay1 = QtWidgets.QHBoxLayout()88        lay1.addStretch()89        lay1.addWidget(self.check_btn)90        lay1.addWidget(self.fix_btn)91        lay1.addStretch()92        self.lay = QtWidgets.QVBoxLayout(self)93        self.lay.addLayout(lay1)94        self.lay.addWidget(self.check_table)95        # build check widget96        self.buildCheckItem()97        self.setMiddleCenter()98        # create signal99        self.check_btn.clicked.connect(self.start)100        self.check_btn.clicked.connect(self.checkResult)101        self.fix_btn.clicked.connect(self.fixAll)102        self.fix_btn.clicked.connect(self.checkResult)103    def setMiddleCenter(self):104        '''105        设置表格åä½å±
ä¸106        '''107        row = self.check_table.rowCount()108        col = self.check_table.columnCount()109        for x in range(row):110            for y in range(col):111                item = self.check_table.item(x, y)112                if item:113                    item.setTextAlignment(QtCore.Qt.AlignCenter)114    def addWidgetToCell(self, widget_cls, margin=0):115        '''116        æ§ä»¶æ·»å å°QTreeWidgetItem å¯ä»¥å±
䏿¾ç¤ºã117        ææ§ä»¶æ·»å å°ä¸ä¸ªæ°çå¸å±ä¸ï¼ç¶å设置为widgetçå¸å±ï¼è¿åwidgetã118        '''119        widget = QtWidgets.QWidget()120        lay = QtWidgets.QHBoxLayout()121        # lay.addSpacing(0.1)122        # lay.setMargin(1)123        lay.addWidget(widget_cls)124        widget.setLayout(lay)125        return widget126    def buildCheckItem(self):127        '''128        å»ºç«æ£æ¥é¡¹ï¼ç¬¬ä¸åæ¯åç§°ï¼ç¬¬äºåæ£æ¥è¿åº¦ï¼ç¬¬ä¸åæ¥çæ£æ¥ç»æ129        '''130        self.check_table.setColumnCount(5)131        self.check_table.setColumnWidth(0, 230)132        self.check_table.setColumnWidth(1, 300)133        self.check_table.setColumnWidth(2, 60)134        self.check_table.setColumnWidth(3, 60)135        self.check_table.setColumnWidth(4, 60)136        self.check_table.customStyle()137        self.check_table.setHorizontalHeaderLabels(["Check item", u"Result", u"State", 'Fix', 'Select'])138        self.check_table.setRowCount(len(self._build_data))139        for index, item in enumerate(self._build_data):140            checkable = item[1]141            check_cls = item[0]142            # å¾å°æ³¨åç±» çåå143            cls_name = check_cls.__name__144            # å建ä¸ä¸ªåå为 "'class'name"ç屿§, å¹¶å®ä¾å QTableWidgetItem145            name = check_cls().cnLabel()146            setattr(self.check_table, cls_name+"name", QtWidgets.QTableWidgetItem(name))147            item = getattr(self.check_table, cls_name+"name")148            # if checkable:149            #     item.setCheckState(QtCore.Qt.Checked)150            # else:151            #     item.setCheckState(QtCore.Qt.Unchecked)152            item.setCheckState(QtCore.Qt.Checked)153            # ç¨æ¥æ¾ç¤ºæ£æ¥ç»æ154            setattr(self.check_table, cls_name+"result", QtWidgets.QTableWidgetItem())155            result_item = getattr(self.check_table, cls_name+"result")156            # å建ä¸ä¸ªåå为 "'class'progrss"ç屿§,å®ä¾åä¸ä¸ª ImagePlayer157            img = ImagePlayer("{0}/icons/loading.gif".format(os.path.dirname(__file__)))158            setattr(self.check_table, cls_name+"label", img)159            label = getattr(self.check_table, cls_name+"label")160            # å建ä¸ä¸ªåå为 "check_btn"ç屿§,å®ä¾åä¸ä¸ª QPushButton161            setattr(self.check_table, cls_name+"fix_btn", QtWidgets.QPushButton('Fix'))162            fix_btn = getattr(self.check_table, cls_name+"fix_btn")163            fix_btn.setEnabled(False)164            # å建ä¸ä¸ªåå为 "fix_btn"ç屿§,å®ä¾åä¸ä¸ª QPushButton165            setattr(self.check_table, cls_name+"sel_btn", QtWidgets.QPushButton('Select'))166            sel_btn = getattr(self.check_table, cls_name+"sel_btn")167            sel_btn.setEnabled(False)168            # 设置åå
æ ¼å¼169            self.check_table.setItem(index, 0, item)170            self.check_table.setItem(index, 1, result_item)171            # self.check_table.setCellWidget(index, 2, label)172            self.check_table.setCellWidget(index, 3, fix_btn)173            self.check_table.setCellWidget(index, 4, sel_btn)174    def runCheck(self, cls):175        result = cls().run()176        if not result:177            return 'OK'178        return result179    def runFix(self, cls):180        if hasattr(cls, 'fix'):181            cls().fix()182        return 'OK'183    def getAllCheckItems(self):184        result = list()185        for index, check_item in enumerate(self._build_data):186            for num, state in enumerate(self.check_table.getRowState()):187                if index == num and state[1] == 'Checked':188                    result.append(check_item)189                # 䏿£æ¥çæ¶åå é¤å¾æ 190                elif index == num and state[1] == 'Unchecked':191                    self.check_table.item(index, 1).setText('')192        return result193    def start(self):194        '''195        å¼å§æ£æ¥ï¼å建ä¸ä¸ªå
å«æææ£æ¥é¡¹çè¿ä»£å¨ï¼ è¿ä»£ç¬¬ä¸ä¸ªæ£æ¥é¡¹196        '''197        self.check_btn.setEnabled(False)198        # å¾å°å¾éçæ£æ¥é¡¹199        self._to_check_data = self.getAllCheckItems()200        # å建è¿ä»£å¨201        self.data_iter = iter(self._to_check_data)202        # è¿ä»£æ£æ¥é¡¹203        self.continueIter()204    def continueIter(self):205        '''206        è¿ä»£æ¯ä¸ªæ£æ¥é¡¹207        '''208        try:209            # æ´æ¹å½åæ£æ¥é¡¹ç徿 210            self.check_index = self.data_iter.next()211            check_cls = self.check_index[0]212            getattr(self.check_table, check_cls.__name__+"label").start()213            result = self.runCheck(check_cls)214            # æ´æ°æ£æ¥é¡¹çæé®ç¶æ215            self.updateFixBtn(result)216            # è¿ä»£æ£æ¥é¡¹217            self.continueIter()218        except StopIteration:219            # éå°StopIterationå°±éåºå¾ªç¯220            self.check_btn.setEnabled(True)221    def changeResult(self, item, btn):222        '''223        æ´æ¹æé®çç¶æ224        '''225        item.setText('OK')226        btn.setEnabled(False)227    def updateFixBtn(self, result):228        '''229        æ£æ¥å®æåæ´æ°çé¢230        '''231        # æ´æ° ç¶æå¾ç232        img = getattr(self.check_table, self.check_index[0].__name__+"label")233        img.setImg("{0}/icons/successful01.gif".format(os.path.dirname(__file__)))234        img.start()235        check_cls = self.check_index[0]236        result_item = getattr(self.check_table, check_cls.__name__+"result")237        fix_btn = getattr(self.check_table, check_cls.__name__+"fix_btn")238        sel_btn = getattr(self.check_table, check_cls.__name__+"sel_btn")239        if result != 'OK':240            result_item.setText(str(result))241            if hasattr(check_cls, 'fix'):242                fix_btn.setEnabled(True)243                temp = check_cls()244                fix_btn.clicked.connect(lambda: temp.fix())245                fix_btn.clicked.connect(lambda: self.changeResult(result_item, fix_btn))246                fix_btn.clicked.connect(self.checkResult)247            if hasattr(check_cls, 'select'):248                sel_btn.setEnabled(True)249                temp = check_cls()250                sel_btn.clicked.connect(lambda: temp.select())251        else:252            result_item.setText('OK')253            fix_btn.setEnabled(False)254            sel_btn.setEnabled(False)255            self.checkResult()256    def fixAll(self):257        def getAllFixItems():258            result = list()259            for index, check_item in enumerate(self._build_data):260                if self.check_table.getItem(index, 1).text() != 'OK':261                    result.append(check_item)262            return result263        # å¾å°éè¦fixçæ£æ¥é¡¹264        self._to_fix_data = getAllFixItems()265        # å建è¿ä»£å¨266        self.fix_data_iter = iter(self._to_fix_data)267        # è¿ä»£æ£æ¥é¡¹268        self.fixContinueIter()269    def fixContinueIter(self):270        '''271        è¿ä»£æ¯ä¸ªæ£æ¥é¡¹272        '''273        try:274            # æ´æ¹å½åæ£æ¥é¡¹ç徿 275            self.check_index = self.fix_data_iter.next()276            check_cls = self.check_index[0]277            getattr(self.check_table, check_cls.__name__+"label").start()278            result = self.runFix(check_cls)279            # æ´æ°æ£æ¥é¡¹çæé®ç¶æ280            self.updateFixBtn(result)281            # è¿ä»£æ£æ¥é¡¹282            self.fixContinueIter()283        except StopIteration:284            # éå°StopIterationå°±éåºå¾ªç¯285            self.check_btn.setEnabled(True)286    def checkResult(self):287        '''288        æ£æ¥æ¯ä¸é¡¹çç»æï¼å¦æé½æ¯âOKâï¼ä¸ä¸æ¥æé®å¯å¨289        妿åå¨å
¶ä»çç»æï¼ä¸ä¸æ¥æé®å
³é290        '''291        result_row = self.check_table.getAllRows(0)292        check_error = list()293        for index, item in enumerate(result_row):294            if item.checkState().name == 'Checked' and self.check_table.getItem(index, 1).text() != 'OK':295                check_error.append(item)296        if not check_error:297            self._par.next_btn.setEnabled(True)298    # def showResult(self, data):299    #     '''300    #     å¼¹åºæ£æ¥ç»æçªå£301    #     '''302    #     wgt = ResultWidget(data)303    #     wgt.show()...case_delete_hierarchical_objects.py
Source:case_delete_hierarchical_objects.py  
...16        nms_api.connect(nms_options.get('nms_ip'), nms_options.get('username'), nms_options.get('password'))17        cls.options = test_api.get_options(options_path)18    def set_up(self):19        nms_api.set_timeout(3)20    def check_table(self, del_name, check_name, row=0):21        for i in range(row, self.options.get(f'number_of_{check_name}')):22            with self.assertRaises(23                    NmsErrorResponseException,24                    msg=f'{check_name}:{i} is in place after deleting {del_name}'25            ):26                nms_api.get_param(f'{check_name}:{i}', '%row')27    def test_delete_vno(self):28        """Delete vno containing all child objects: sub-vnos, stations etc."""29        # ~1100 seconds30        nms_api.set_timeout(120)31        nms_api.load_config('vno_with_all_objects.txt')32        time.sleep(5)33        nms_api.delete('vno:0')34        self.check_table('vno', 'vno')35        self.check_table('vno', 'dashboard')36        self.check_table('vno', 'station')37        self.check_table('vno', 'sch_task')38        self.check_table('vno', 'rip_router')39        self.check_table('vno', 'port_map')40        self.check_table('vno', 'route')41    def test_delete_controller_route(self):42        """Delete controller route"""43        nms_api.load_config('controller_with_all_objects.txt')44        num = self.options.get('number_of_route')45        for i in (0, num // 2, num - 1):46            nms_api.delete(f'route:{i}')47            with self.assertRaises(NmsErrorResponseException, msg=f'route:{i} is in place after its deletion'):48                nms_api.get_param(f'route:{i}', 'type')49    def test_delete_controller_rip_router(self):50        """Delete controller rip_router"""51        nms_api.load_config('controller_with_all_objects.txt')52        num = self.options.get('number_of_rip_router')53        for i in (0, num // 2, num - 1):54            nms_api.delete(f'rip_router:{i}')55            with self.assertRaises(NmsErrorResponseException, msg=f'rip_router:{i} is in place after its deletion'):56                nms_api.get_param(f'rip_router:{i}', 'service')57    def test_delete_controller_port_map(self):58        """Delete controller port_map"""59        nms_api.load_config('controller_with_all_objects.txt')60        num = self.options.get('number_of_port_map')61        for i in (0, num // 2, num - 1):62            nms_api.delete(f'port_map:{i}')63            with self.assertRaises(NmsErrorResponseException, msg=f'port_map:{i} is in place after its deletion'):64                nms_api.get_param(f'port:{i}', 'service')65    def test_delete_controller_access(self):66        """Delete controller access"""67        nms_api.load_config('controller_with_all_objects.txt')68        for i in (1, 255, 512):69            nms_api.delete(f'access:{i}')70            with self.assertRaises(NmsErrorResponseException, msg=f'access:{i} is in place after its deletion'):71                nms_api.get_param(f'access:{i}', 'group')72    def test_delete_controller(self):73        """Delete controller containing all route, rip_router, port_map, and access"""74        nms_api.load_config('controller_with_all_objects.txt')75        nms_api.set_timeout(10)76        nms_api.delete('controller:0')77        self.check_table('controller', 'route')78        self.check_table('controller', 'rip_router')79        self.check_table('controller', 'port_map')80        self.check_table('controller', 'access', row=1)81    def test_delete_station_route(self):82        """Delete station route"""83        nms_api.load_config('station_with_all_objects.txt')84        num = self.options.get('number_of_route')85        for i in (0, num // 2, num - 1):86            nms_api.delete(f'route:{i}')87            with self.assertRaises(NmsErrorResponseException, msg=f'route:{i} is in place after its deletion'):88                nms_api.get_param(f'route:{i}', 'type')89    def test_delete_station_rip_router(self):90        """Delete station rip_router"""91        nms_api.load_config('station_with_all_objects.txt')92        num = self.options.get('number_of_rip_router')93        for i in (0, num // 2, num - 1):94            nms_api.delete(f'rip_router:{i}')95            with self.assertRaises(NmsErrorResponseException, msg=f'rip_router:{i} is in place after its deletion'):96                nms_api.get_param(f'rip_router:{i}', 'service')97    def test_delete_station_port_map(self):98        """Delete station port_map"""99        nms_api.load_config('station_with_all_objects.txt')100        num = self.options.get('number_of_port_map')101        for i in (0, num // 2, num - 1):102            nms_api.delete(f'port_map:{i}')103            with self.assertRaises(NmsErrorResponseException, msg=f'port_map:{i} is in place after its deletion'):104                nms_api.get_param(f'port:{i}', 'service')105    def test_delete_station_sch_task(self):106        """Delete station sch_task"""107        nms_api.load_config('station_with_all_objects.txt')108        time.sleep(5)109        num = self.options.get('number_of_sch_task')110        for i in (0, num // 2, num - 1):111            nms_api.delete(f'sch_task:{i}')112            with self.assertRaises(NmsErrorResponseException, msg=f'sch_task:{i} is in place after its deletion'):113                nms_api.get_param(f'sch_task:{i}', 'name')114    def test_delete_station(self):115        """Delete station containing all sch_task, route, rip_router, port_map"""116        nms_api.load_config('station_with_all_objects.txt')117        nms_api.set_timeout(10)118        nms_api.delete('station:0')119        self.check_table('station', 'route')120        self.check_table('station', 'rip_router')121        self.check_table('station', 'port_map')122        self.check_table('station', 'sch_task')123    def test_delete_network(self):124        """Delete network containing all objects"""125        # Duration 560 seconds126        nms_api.load_config('network_with_all_objects.txt')127        nms_api.set_timeout(120)  # timeout is set to a higher value in order to let NMS delete all child objects128        nms_api.delete('network:0')129        time.sleep(20)130        self.check_table('network', 'teleport')131        self.check_table('network', 'controller')132        self.check_table('network', 'vno')133        self.check_table('network', 'service')134        self.check_table('network', 'shaper')135        self.check_table('network', 'policy')136        self.check_table('network', 'polrule')137        self.check_table('network', 'group', row=1)138        self.check_table('network', 'user', row=1)139        self.check_table('network', 'access', row=1)140        self.check_table('network', 'sr_controller')141        self.check_table('network', 'sr_teleport')142        self.check_table('network', 'device')143        self.check_table('network', 'sr_license')144        self.check_table('network', 'bal_controller')145        self.check_table('network', 'profile_set')146        self.check_table('network', 'sw_upload')147        self.check_table('network', 'camera')148        self.check_table('network', 'dashboard')149        self.check_table('network', 'scheduler')150        self.check_table('network', 'sch_service')151        self.check_table('network', 'sch_range')152        self.check_table('network', 'sch_task')153        self.check_table('network', 'station')154        self.check_table('network', 'rip_router')155        self.check_table('network', 'port_map')...test_pokryciav2.py
Source:test_pokryciav2.py  
1import random234# n = 75# p = 0.4678def gnp(n, p):9    "Model G(n,p)"10    a = [[0 for j in range(n)] for i in range(n)]11    for i in range(1, n):12        for j in range(i):13            if (random.random() <= p):14                a[i][j] = a[j][i] = 115    return a1617def graph_cover_test(vertexAmount,matrix,answers):18    check_table=[]19    for i in range(vertexAmount):20        check_table.append(0)21    for answer in answers:22        for i in range(vertexAmount):23            if matrix[answer][i] == 1:24                check_table[i]=125                for j in range(vertexAmount):26                    if j!=answer:27                        if matrix[i][j] == 1:28                            check_table[j]=129    if 0 in check_table:30        return False31    else:32        return True3334def graph_cover_test_greedy(vertexAmount,matrix,answers):35    check_table=[]36    for i in range(vertexAmount):37        check_table.append(0)38    for answer in answers:39        check_table[answer] = 140        for i in range(vertexAmount):41            if matrix[answer][i] == 1:42                check_table[i]=143                for j in range(vertexAmount):44                    if j!=answer:45                        if matrix[i][j] == 1:46                            check_table[j]=147    not_covered = []48    for e in range(vertexAmount):49        if check_table[e] != 1:50            not_covered.append(e)51    if len(not_covered) > 0:52        corectly_covered = False53    else:54        corectly_covered = True5556    return corectly_covered,not_covered575859# random_answer = [2,0]60#61# matrix = gnp(n, p)62#63# print("Matrix")64# for e in matrix:65#     print(e)66#67# result = graph_cover_test_graphViz(n,matrix,random_answer)68#
...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!!
