Best Python code snippet using yandex-tank
PerformanceTiming.py
Source:PerformanceTiming.py  
1from robot.libraries.BuiltIn import BuiltIn2import csv3import datetime4import time5from os import path6class PerformanceTiming:7    def __init__(self, filename='resource_output.csv'):8        self.filename = filename9    def Measure_Time(self, function, type_operation,test_type,nfr,user_type,user_name):10        for loop_count in range(60):11            if  function ==  "login":12                load_time = self.Measure_Login(type_operation , test_type,loop_count,nfr,user_type,user_name)13            elif function == "Home_Search":14                load_time = self.Measure_Home_Search(type_operation ,test_type,loop_count,nfr,user_type,user_name)15            elif function == "Home_Search_All":16                load_time = self.Measure_Home_Search_All(type_operation , test_type,loop_count,nfr,user_type,user_name)17            elif function == "Home_Facets_Apply":18                load_time = self.Measure_Home_Facets(type_operation , test_type,loop_count,nfr,user_type,user_name)19            elif function == "Home_Facets_Clear":20                load_time = self.Measure_Home_Facets_Clear(type_operation , test_type,loop_count,nfr,user_type,user_name)21            elif function == "Home_Bar_Chart":22                load_time = self.Measure_Home_Bar_Chart(type_operation , test_type,loop_count,nfr,user_type,user_name)23            elif function == "List_View_Search":24                load_time = self.Measure_List_View_Search(type_operation , test_type,loop_count,nfr,user_type,user_name)25            elif function == "List_View_Facets_Apply":26                load_time = self.Measure_List_View_Facets(type_operation , test_type,loop_count,nfr,user_type,user_name)27            elif function == "List_View_Facets_Clear":28                load_time = self.Measure_List_View_Facets_Clear(type_operation , test_type,loop_count,nfr,user_type,user_name)29            elif function == "List_View_Pagination":30                load_time = self.Measure_List_View_Pagination(type_operation , test_type,loop_count,nfr,user_type,user_name)31            elif function == "Traversal":32                load_time = self.Measure_Traversal(type_operation , test_type,loop_count,nfr,user_type,user_name)33            elif function == "Neighbours":34                load_time = self.Measure_Neighbours(type_operation , test_type,loop_count,nfr,user_type,user_name)35            elif function == "Map_View_Switch":36                load_time = self.Measure_Map_View_Switch(type_operation , test_type,loop_count,nfr,user_type,user_name)37            elif function == "Map_View_Search":38                load_time = self.Measure_Map_View_Search(type_operation , test_type,loop_count,nfr,user_type,user_name)39            elif function == "Map_View_Facets_Apply":40                load_time = self.Measure_Map_View_Facets(type_operation , test_type,loop_count,nfr,user_type,user_name)41            elif function == "Map_View_Facets_Clear":42                load_time = self.Measure_Map_View_Facets_Clear(type_operation , test_type,loop_count,nfr,user_type,user_name)43            elif function == "Analyse_Summary_Assets":44                load_time = self.Measure_Analyse_Summary_Assets_Under_Analysis(type_operation , test_type,loop_count,nfr,user_type,user_name)45            elif function == "Analyse_Summary_Relationships":46                load_time = self.Measure_Analyse_Summary_Relationships(type_operation , test_type,loop_count,nfr,user_type,user_name)47            elif function == "Analyse_Usage_Switch":48                load_time = self.Measure_Analyse_Usage_Switch(type_operation , test_type,loop_count,nfr,user_type,user_name)49            elif function == "Analyse_Usage_Search":50                load_time = self.Measure_Analyse_Usage_Search(type_operation , test_type,loop_count,nfr,user_type,user_name)51            elif function == "Analyse_Usage_Search_All":52                load_time = self.Measure_Analyse_Usage_Search_All(type_operation , test_type,loop_count,nfr,user_type,user_name)53            elif function == "Analyse_Compliance_Switch":54                load_time = self.Measure_Analyse_Compliance_Switch(type_operation , test_type,loop_count,nfr,user_type,user_name)55            elif function == "Analyse_Compliance_Search":56                load_time = self.Measure_Analyse_Compliance_Search(type_operation , test_type,loop_count,nfr,user_type,user_name)57            elif function == "Analyse_Compliance_Search_All":58                load_time = self.Measure_Analyse_Compliance_Search_All(type_operation , test_type,loop_count,nfr,user_type,user_name)59            elif function == "Legacy_Workflow_Switch":60                load_time = self.Measure_Action_Workflow_Switch(type_operation , test_type,loop_count,nfr,user_type,user_name)61            elif function == "Legacy_Workflow_Search":62                load_time = self.Measure_Action_Workflow_Search(type_operation , test_type,loop_count,nfr,user_type,user_name)63            elif function == "Legacy_Workflow_Search_All":64                load_time = self.Measure_Action_Workflow_Search_All(type_operation , test_type,loop_count,nfr,user_type,user_name)65            elif function == "Execute_Report":66                load_time = self.Measure_Action_Execute_Report(type_operation , test_type,loop_count,nfr,user_type,user_name)67            elif function == "Measure_Glossary_Tab_Search":68                load_time = self.Measure_Glossary_Tab_Search(type_operation , test_type,loop_count,nfr,user_type,user_name)69            elif function == "Glossary_Tab_Facets_Apply":70                load_time = self.Measure_Glossary_Tab_Facets(type_operation , test_type,loop_count,nfr,user_type,user_name)71            elif function == "Glossary_Tab_Facets_Clear":72                load_time = self.Measure_Glossary_Tab_Facets_Clear(type_operation , test_type,loop_count,nfr,user_type,user_name)73            elif function == "Switch_To_Glossary_Tab_From_List_View":74                load_time = self.Measure_Switch_To_Glossary_Tab_From_List_View(type_operation , test_type,loop_count,nfr,user_type,user_name)75            elif function == "Switch_To_List_View_From_Glossary_Tab":76                load_time = self.Measure_Switch_To_List_View_From_Glossary_Tab(type_operation , test_type,loop_count,nfr,user_type,user_name)77            elif function == "Measure":78                load_time = self.Measure_All_Resources(type_operation , test_type,loop_count,nfr,user_type,user_name)79            elif function == "Enrich_Open":80                load_time = self.Measure_Enrich_Open(type_operation , test_type,loop_count,nfr,user_type,user_name)81            elif function == "Enrich_Edit":82                load_time = self.Measure_Enrich_Edit(type_operation , test_type,loop_count,nfr,user_type,user_name)83            elif function == "Change_Workflow_Dashboard_Type":84                load_time = self.Measure_Action_Workflow_Type_Change(type_operation , test_type,loop_count,nfr,user_type,user_name)85            elif function == "Change_Compliance_Dashboard_Type":86                load_time = self.Measure_Analyse_Compliance_Dashboard_Type_Change(type_operation , test_type,loop_count,nfr,user_type,user_name)87            elif function == "Change_Usage_Dashboard_Type":88                load_time = self.Measure_Analyse_Usage_Dashboard_Type_Change(type_operation , test_type,loop_count,nfr,user_type,user_name)89            elif function == "List_View_Sorting":90                load_time = self.Measure_List_View_Sorting(type_operation , test_type,loop_count,nfr,user_type,user_name)91            elif function == "List_View_Keep_Only":92                load_time = self.Measure_Keep_Only(type_operation , test_type,loop_count,nfr,user_type,user_name)93            elif function == "List_View_Bulk_Edit":94                load_time = self.Measure_Bulk_Edit(type_operation , test_type,loop_count,nfr,user_type,user_name)95            if  load_time > 0.001:96                break97            time.sleep(10)98            print("sleep for 10 seconds")99            print("Loop Number",loop_count)100        return load_time101    # Below public method names are used as keywords102    def Measure_Login(self,type_operation , test_type,loop_count,nfr,user_type,user_name):103        checked_resources = ['favouriteQueries','viewUserActionHistory', 'chartStats']104        return self.Measure_Resources("main.css", "chartStats",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)105    def Measure_Home_Search(self, type_operation , test_type, loop_count,nfr,user_type, user_name):106        checked_resources = ['checkQueryComplexity','search','facets','fullContext', 'chartStats']107        return self.Measure_Resources("checkQueryComplexity", "chartStats", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)108    def Measure_Home_Search_All(self, type_operation , test_type, loop_count,nfr,user_type, user_name):109        checked_resources = ['checkQueryComplexity','search','facets','fullContext', 'chartStats']110        return self.Measure_Resources("checkQueryComplexity", "chartStats", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)111    def Measure_Home_Facets(self, type_operation , test_type, loop_count,nfr,user_type, user_name):112        checked_resources = ['query','chartStats']113        return self.Measure_Resources("query", "chartStats",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)114    def Measure_Home_Facets_Clear(self, type_operation , test_type, loop_count,nfr,user_type, user_name):115        checked_resources = ['query','chartStats']116        return self.Measure_Resources("query", "chartStats", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)117    def Measure_List_View_Search(self, type_operation , test_type, loop_count,nfr,user_type, user_name):118        checked_resources = ['search','fullContext','datatableAjax?dataTableName=EXPLORE']119        return self.Measure_Resources("checkQueryComplexity", "datatableAjax?dataTableName=EXPLORE",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)120    def Measure_Home_Bar_Chart(self,type_operation , test_type, loop_count,nfr,user_type, user_name):121        checked_resources = ['queryBarChart','datatableAjax?dataTableName=EXPLORE']122        return self.Measure_Resources("queryBarChart","datatableAjax?dataTableName=EXPLORE",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)123    def Measure_List_View_Pagination(self,type_operation , test_type, loop_count,nfr,user_type, user_name):124        checked_resources = ['datatableAjax?dataTableName=EXPLORE']125        return self.Measure_Resources("csrf","datatableAjax?dataTableName=EXPLORE",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)126    def Measure_List_View_Facets(self, type_operation , test_type, loop_count,nfr,user_type, user_name):127        checked_resources = ['query','datatableAjax?dataTableName=EXPLORE']128        return self.Measure_Resources("query", "datatableAjax?dataTableName=EXPLORE",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)129    def Measure_List_View_Facets_Clear(self, type_operation , test_type, loop_count,nfr,user_type, user_name):130        checked_resources = ['query','datatableAjax?dataTableName=EXPLORE']131        return self.Measure_Resources("query", "datatableAjax?dataTableName=EXPLORE",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)132    def Measure_Traversal(self, type_operation , test_type, loop_count,nfr,user_type, user_name):133        checked_resources = ['datatableAjax?dataTableName=EXPLORE']134        return self.Measure_Resources("validateGovernanceSettingsCompliance", "datatableAjax?dataTableName=EXPLORE", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)135    def Measure_Neighbours(self,type_operation , test_type, loop_count,nfr,user_type, user_name):136        checked_resources = ['datatableAjax?dataTableName=EXPLORE']137        return self.Measure_Resources("validateGovernanceSettingsCompliance", "datatableAjax?dataTableName=EXPLORE", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)138    def Measure_Map_View_Switch(self,type_operation , test_type, loop_count,nfr,user_type, user_name):139        checked_resources = ['visualizeNodes', 'getRotationList']140        return self.Measure_Resources("visualizeNodes", "getRotationList", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)141    def Measure_Map_View_Search(self,type_operation , test_type, loop_count,nfr,user_type, user_name):142        checked_resources = ['visualizeNodes', 'getRotationList']143        return self.Measure_Resources("checkQueryComplexity", "getRotationList",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)144    def Measure_Map_View_Facets(self,type_operation , test_type, loop_count,nfr,user_type, user_name):145        checked_resources = ['visualizeNodes', 'getRotationList']146        return self.Measure_Resources("query", "getRotationList", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)147    def Measure_Map_View_Facets_Clear(self,type_operation , test_type, loop_count,nfr,user_type, user_name):148        checked_resources = ['visualizeNodes', 'getRotationList']149        return self.Measure_Resources("query", "getRotationList", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)150    def Measure_Analyse_Summary_Assets_Under_Analysis(self, type_operation , test_type, loop_count,nfr,user_type, user_name):151        checked_resources = ['activeNodeSummary']152        return self.Measure_Resources("activeNodeSummary", "activeNodeSummary",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)153    def Measure_Analyse_Summary_Relationships(self,type_operation , test_type, loop_count,nfr,user_type, user_name):154        checked_resources = ['relationshipSummary']155        return self.Measure_Resources("relationshipSummary", "relationshipSummary",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)156    def Measure_Analyse_Usage_Switch(self,type_operation ,test_type, loop_count,nfr,user_type, user_name):157        checked_resources = ['matrix?rowLabel']158        return self.Measure_Resources("matrixControls", "matrix?rowLabel",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)159    def Measure_Analyse_Usage_Search(self,type_operation , test_type, loop_count,nfr,user_type, user_name):160        checked_resources = ['fullContext','search', 'matrix','facets']161        return self.Measure_Resources("checkQueryComplexity", "fullContext",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)162    def Measure_Analyse_Usage_Search_All(self,type_operation ,test_type, loop_count,nfr,user_type, user_name):163        checked_resources = ['search', 'matrix','facets','fullContext']164        return self.Measure_Resources("checkQueryComplexity", "fullContext",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)165    def Measure_Analyse_Compliance_Switch(self,type_operation , test_type, loop_count,nfr,user_type, user_name):166        checked_resources = ['scatterChart','pivotTable']167        return self.Measure_Resources("scatterChart", "pivotTable", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)168    def Measure_Analyse_Compliance_Search(self,type_operation ,test_type, loop_count,nfr,user_type, user_name):169        checked_resources = ['scatterChart','pivotTable','facets']170        return self.Measure_Resources("checkQueryComplexity", "pivotTable",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)171    def Measure_Analyse_Compliance_Search_All(self,type_operation , test_type, loop_count,nfr,user_type, user_name):172        checked_resources = ['scatterChart','pivotTable','facets']173        return self.Measure_Resources("checkQueryComplexity", "pivotTable",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)174    def Measure_Action_Workflow_Switch(self,type_operation , test_type, loop_count,nfr,user_type, user_name):175        checked_resources = [ 'workflow']176        return self.Measure_Resources("workflow", "workflow", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)177    def Measure_Action_Workflow_Search(self,type_operation ,test_type, loop_count,nfr,user_type, user_name):178        checked_resources = [ 'search','fullContext','facets']179        return self.Measure_Resources("checkQueryComplexity", "fullContext", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)180    def Measure_Action_Workflow_Search_All(self,type_operation , test_type, loop_count,nfr,user_type, user_name):181        checked_resources = ['facets','fullContext','search']182        return self.Measure_Resources("checkQueryComplexity", "fullContext",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)183    def Measure_Action_Execute_Report(self,type_operation , test_type, loop_count,nfr,user_type, user_name):184        checked_resources = ['report','datatableAjax']185        return self.Measure_Resources("report", "datatableAjax",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)186    def Measure_Glossary_Tab_Search(self, type_operation ,test_type, loop_count,nfr,user_type, user_name):187        checked_resources = ['datatableAjax?dataTableName=GLOSSARY']188        return self.Measure_Resources("checkQueryComplexity", "datatableAjax?dataTableName=GLOSSARY",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)189    def Measure_Glossary_Tab_Facets(self, type_operation , test_type, loop_count,nfr,user_type, user_name):190        checked_resources = ['query','datatableAjax?dataTableName=GLOSSARY']191        return self.Measure_Resources("query", "datatableAjax?dataTableName=GLOSSARY", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)192    def Measure_Glossary_Tab_Facets_Clear(self, type_operation , test_type, loop_count,nfr,user_type, user_name):193        checked_resources = ['query','datatableAjax?dataTableName=GLOSSARY']194        return self.Measure_Resources("query", "datatableAjax?dataTableName=GLOSSARY", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)195    def Measure_Switch_To_Glossary_Tab_From_List_View(self, type_operation ,test_type, loop_count,nfr,user_type, user_name):196        checked_resources = ['filterContext?dataTableName=GLOSSARY','datatableAjax?dataTableName=GLOSSARY']197        return self.Measure_Resources("filterContext?dataTableName=GLOSSARY", "datatableAjax?dataTableName=GLOSSARY", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)198    def Measure_Switch_To_List_View_From_Glossary_Tab(self, type_operation , test_type, loop_count,nfr,user_type, user_name):199        checked_resources = ['filterContext?dataTableName=EXPLORE','datatableAjax?dataTableName=EXPLORE']200        return self.Measure_Resources("filterContext?dataTableName=EXPLORE", "datatableAjax?dataTableName=EXPLORE", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)201    def Measure_Enrich_Open(self, type_operation ,test_type, loop_count,nfr,user_type, user_name):202        checked_resources = ['enrich?id','discussion?subject=node']203        return self.Measure_Resources("enrich?id", "discussion?subject=node",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)204    def Measure_Enrich_Edit(self, type_operation , test_type, loop_count,nfr,user_type, user_name):205        checked_resources = ['submit','discussion?subject=node']206        return self.Measure_Resources("submit", "discussion?subject=node",type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)207    def Measure_Action_Workflow_Type_Change(self,type_operation , test_type, loop_count,nfr,user_type, user_name):208        checked_resources = [ 'workflow']209        return self.Measure_Resources("workflow", "workflow", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)210    def Measure_Analyse_Usage_Dashboard_Type_Change(self,type_operation , test_type, loop_count,nfr,user_type, user_name):211        checked_resources = [ 'matrix']212        return self.Measure_Resources("matrix", "matrix", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)213    def Measure_Analyse_Compliance_Dashboard_Type_Change(self,type_operation , test_type, loop_count,nfr,user_type, user_name):214        checked_resources = [ 'pivotTable']215        return self.Measure_Resources("pivotTable", "pivotTable", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)216    def Measure_List_View_Sorting(self,type_operation , test_type, loop_count,nfr,user_type, user_name):217        checked_resources = [ 'datatableAjax?dataTableName=EXPLORE']218        return self.Measure_Resources("datatableAjax?dataTableName=EXPLORE", "datatableAjax?dataTableName=EXPLORE", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)219    def Measure_Keep_Only(self, type_operation , test_type, loop_count,nfr,user_type, user_name):220        checked_resources = ['multiKeepOnly','datatableAjax?dataTableName=EXPLORE']221        return self.Measure_Resources("validateGovernanceSettingsCompliance", "datatableAjax?dataTableName=EXPLORE", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)222    def Measure_Bulk_Edit(self, type_operation , test_type, loop_count,nfr,user_type, user_name):223        checked_resources = ['update','datatableAjax?dataTableName=EXPLORE']224        return self.Measure_Resources("update", "datatableAjax?dataTableName=EXPLORE", type_operation ,test_type, checked_resources, loop_count,nfr,user_type,user_name)225    def Clear_Resources(self):226        self.Clear_API_Cache()227    def Measure_All_Resources(self, type_operation, test_type,loop_count,nfr,user_type,user_name):228        return self.All_Resources(type_operation , test_type, loop_count,nfr,user_type,user_name)229    # Below private methods are used by above public methods230    def Measure_Resources(self, start_resource, end_resource, operation_type,  test_type, checked_resources, loop_count,nfr,user_type,user_name):231        sl = BuiltIn().get_library_instance('SeleniumLibrary')232        driver = sl.driver233        ''' Use Resource Timing  API to calculate the timings that matter the most '''234        resource_timing = driver.execute_script('''235            let resourceList = window.performance.getEntriesByType("resource");236            let resourceLength = 0;237            let completeResourceLoad;238            let maxResourceLoad = 0;239            let validResources = [];    // Resources which started after given first resource240            241            let checkedResources = arguments[2];242            let checkedResourceLength = checkedResources && checkedResources.length > 0 ? checkedResources.length : 0;243            let stallTimeArray = [];244            let nameArray = [];245            let validNameArray = [];246            let stallSum = 0;247            let first = 0;248            let firstStartTime = 10000000000; // this is dummy big value to avoid previously started resources249            let last = 0;250            for (let i = 0; i < resourceList.length; i++) {251                let resourcePrefixArray = resourceList[i].name.split('/');252                if (resourcePrefixArray && resourcePrefixArray.length > 0) {253                    let resourcePrefix = resourcePrefixArray[resourcePrefixArray.length - 1];254                    let timingMap = getTiming(resourceList[i]);255                    nameArray[nameArray.length] = resourcePrefix;256                    if (resourcePrefix.includes(arguments[0])) {257                        first = resourceList[i];258                        firstStartTime = resourceList[i].startTime;259                    } else if (resourcePrefix.includes(arguments[1])) {260                        last = resourceList[i];261                    }262                    263        264                    if (resourceList[i].startTime >= firstStartTime) {265                        resourceLength++;266                        validResources[validResources.length] = resourceList[i];267                        validNameArray[validNameArray.length] = resourcePrefix;268                        stallTimeArray[stallTimeArray.length] = timingMap["Stall_Time"];269                        stallSum = stallSum + timingMap["Stall_Time"];270                    }271                }272            }273            274            // Waiting for additional resources specified275            if (checkedResourceLength) {276                let isAllResIncluded = true;277                for (let j = 0; j < checkedResourceLength; j++) {278                    let checkedRes = checkedResources[j];279                    let isCurrentIncluded = false;280                    for (let i = 0; i < validNameArray.length; i++) {281                        let name = validNameArray[i];282                        if (name && checkedRes && name.includes(checkedRes)) {283                            isCurrentIncluded = true;284                        }285                    }286                    isAllResIncluded = isAllResIncluded && isCurrentIncluded287                }288                if (isAllResIncluded) {289                    validResources.sort(function (a, b) {290                        return b.responseEnd - a.responseEnd;291                    });292                    293                    if (validResources.length > 0) {294                        maxResourceLoad = validResources[0].responseEnd - validResources[validResources.length - 1].startTime;295                    }296                }297            }298        299            stallTimeArray.sort(function (a, b) {300                return b - a;301            });302            303            if (first !== 0 && last === 0 && arguments[0] === arguments[1]) {304                last = first;305            }306            307            completeResourceLoad = last.responseEnd - first.startTime;308        309            let max = stallTimeArray[0];310            let min = stallTimeArray[stallTimeArray.length - 1];311            let avg = stallSum / (stallTimeArray.length - 1);312            let sum = stallSum;313        314            return [round(max), round(min), round(avg), round(sum), round(completeResourceLoad), resourceLength, round(maxResourceLoad), nameArray, first.startTime, last.responseEnd];315        316            function getTiming(resourceObj) {317                let timingMap = {};318        319                if (resourceObj) {320                    let stallTime = resourceObj.requestStart - resourceObj.connectEnd;321                    let serverTime = resourceObj.responseStart - resourceObj.requestStart;322                    let contentDownloadingTime = resourceObj.responseEnd - resourceObj.responseStart;323                    let completeTime = resourceObj.responseEnd - resourceObj.startTime;324        325                    timingMap["Stall_Time"] = stallTime;326                    timingMap["Server_Time"] = serverTime;327                    timingMap["Content_Downloading_Time"] = contentDownloadingTime;328                    timingMap["Complete_Resource_Time"] = completeTime;329                }330        331                return timingMap;332            }333            334            function round(value, decimals) {335                let deci = decimals ? decimals : 3; // Default to set it to show milliseconds336                let val = value ? value/1000 : value;337                return Number(Math.round(val + 'e' + deci) + 'e-' + deci);338            }339        ''', start_resource, end_resource, checked_resources)340        is_checked_available = checked_resources and len(checked_resources) > 0341        is_last_loop = is_checked_available and loop_count == 50342        # Sending results to display343        self.Display_Test_Results(resource_timing, operation_type,   test_type,  is_last_loop,nfr,user_type,user_name)344        output = resource_timing[4]345        if checked_resources and len(checked_resources) > 0:346            output = resource_timing[6]347        return output   # Returning Loading Times to compare348    def All_Resources(self, type_operation  ,test_type, loop_count,nfr,user_type,user_name):349        sl = BuiltIn().get_library_instance('SeleniumLibrary')350        driver = sl.driver351        # ''' Use Navigation Timing  API to calculate the timings that matter the most '''352        # navigationStart = driver.execute_script("return window.performance.timing.navigationStart")353        # responseStart = driver.execute_script("return window.performance.timing.responseStart")354        # loadEnd = driver.execute_script("return window.performance.timing.loadEventEnd")355        ''' Use Resource Timing  API to calculate the timings that matter the most '''356        resource_timing = driver.execute_script('''357            let resourceList = window.performance.getEntriesByType("resource");358            let resourceLength = resourceList.length;359            let completeResourceLoad = 0;360            let maxResourceLoad = 0;361            let stallTimeArray = [];362            let nameArray = [];363            let stallSum = 0;364            let first = {startTime: 0};365            let last = {responseEnd: 0};366        367            if (resourceList.length > 0) {368                first = resourceList[0];369                last = resourceList[resourceList.length - 1];370        371                completeResourceLoad = last.responseEnd - first.startTime;372            }373        374            for (let i = 0; i < resourceList.length; i++) {375                let resourcePrefixArray = resourceList[i].name.split('/');376                if (resourcePrefixArray && resourcePrefixArray.length > 0) {377                    let timingMap = getTiming(resourceList[i]);378                    nameArray[nameArray.length] = resourcePrefixArray[resourcePrefixArray.length -1];379                    stallTimeArray[stallTimeArray.length] = timingMap["Stall_Time"];380                    stallSum = stallSum + timingMap["Stall_Time"];381                }382            }383        384            stallTimeArray.sort(function (a, b) {385                return b - a386            });387        388            let max = stallTimeArray[0];389            let min = stallTimeArray[stallTimeArray.length - 1];390            let avg = stallSum / (stallTimeArray.length - 1);391            let sum = stallSum;392        393            return [round(max), round(min), round(avg), round(sum), round(completeResourceLoad), resourceLength, maxResourceLoad, nameArray];394        395            function getTiming(resourceObj) {396                let timingMap = {};397        398                if (resourceObj) {399                    let stallTime = resourceObj.requestStart - resourceObj.connectEnd;400                    let serverTime = resourceObj.responseStart - resourceObj.requestStart;401                    let contentDownloadingTime = resourceObj.responseEnd - resourceObj.responseStart;402                    let completeTime = resourceObj.responseEnd - resourceObj.startTime;403        404                    timingMap["Stall_Time"] = stallTime;405                    timingMap["Server_Time"] = serverTime;406                    timingMap["Content_Downloading_Time"] = contentDownloadingTime;407                    timingMap["Complete_Resource_Time"] = completeTime;408                }409        410                return timingMap;411            }412            413            function round(value, decimals) {414                let deci = decimals ? decimals : 3; // Default to set it to show milliseconds415                let val = value ? value/1000 : value;416                return Number(Math.round(val + 'e' + deci) + 'e-' + deci);417            }418        ''')419        # Sending results to display420        self.Display_Test_Results(resource_timing, type_operation ,   test_type,  loop_count,nfr,user_type,user_name)421        return resource_timing[4]   # Returning 'Complete Loading Time' to compare422    @staticmethod423    def Clear_API_Cache():424        sl = BuiltIn().get_library_instance('SeleniumLibrary')425        driver = sl.driver426        clearResponse = driver.execute_script('''427                window.performance.clearResourceTimings();428                let resourceList = window.performance.getEntriesByType("resource");429                return resourceList === "[]";430            ''')431        print("Previous resources are cleared %s" % clearResponse)432    # Display Resource API output in a csv file433    def Display_Test_Results(self, results_array, operation_type,   test_type, is_last_loop, nfr,user_type,user_name):434        current_date_time = datetime.datetime.now()435        date = current_date_time.strftime("%d-%m-%Y")436        time = current_date_time.strftime("%H:%M:%S")437        display_array = [date, time, test_type,   operation_type,   nfr,user_type,user_name]438        csv_results = results_array[:-3]439        display_array = display_array + csv_results440        if is_last_loop or results_array[6] > 0:441            if not path.exists(self.filename):442                test_file = open(self.filename, 'w')443                test_writer = csv.writer(test_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)444                header_row = ['Date', 'Time',  'Search Type',  'Type of Operation','NFR','User Type','User Name','Maximum Stall Time', 'Minimum Stall Time', 'Average Stall Time', 'Sum of Stall Times', 'Page Loading Time','Number of Resources','Complete Loading Time']445                test_writer.writerow(header_row)446            print("Writing results to CSV")447            with open(self.filename, mode='a') as test_file:448                test_writer = csv.writer(test_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)449                test_writer.writerow(display_array)450        print("Complete Loading s: %s secs" % results_array[6])451        print("Page Loading Time: %s secs" % results_array[6])452        print("Maximum Stall Time: %s secs" % results_array[0])453        print("Minimum Stall Time: %s secs" % results_array[1])454        print("Average Stall Time: %s secs" % results_array[2])455        print("Sum of Stall Times: %s secs" % results_array[3])456        print("Number of Resources: %s" % results_array[5])457        print("Start time: %s Milli seconds" % results_array[8])458        print("End time: %s milli seconds" % results_array[9] )459        for x in range(len(results_array[7])):...maximumConsecutiveSequence.py
Source:maximumConsecutiveSequence.py  
1# Determining the maximum number of sequential numbers in a list2# Using a loop in a loop, as we need to iterate through a list while keeping track of all the sequential numbers3# Outer loop keeps track of where we currently are in the loop and instantiates sequence details4# Inner loop keeps track of sequence details and records them5# I wanted to record the details of each sequence, so I created an object and recorded them in a list67class Sequence:8    def __init__(self, minimum_value, maximum_value, length):9        self.minimum_value = minimum_value10        self.maximum_value = maximum_value11        self.length = length121314provided_list = [5, 2, 99, 3, 4, 1, 100, 11, 9, 14, 12, 10, 13, 15]1516# code works whether your sort it or not of course17provided_list.sort()1819sequence_list = []2021loop_count = 02223while loop_count < len(provided_list):24    current_minimum_value = provided_list[loop_count]25    current_maximum_value = provided_list[loop_count]26    sequence_bool = False27    current_sequence_length = 02829    if loop_count == len(provided_list) - 1:30        # you're at the last value, don't think anything needs to be done here31        break3233    # code to determine if the next item in list is a sequential number, and iterates until  it no longer is34    elif provided_list[loop_count + 1] - provided_list[loop_count] == 1:35        sequence_bool = True3637        # Keeps iterating until the next number is not sequential OR you're at the end of the list38        while sequence_bool and loop_count < len(provided_list):3940            current_sequence_length += 14142            if current_minimum_value > provided_list[loop_count]:43                current_minimum_value = provided_list[loop_count]4445            if current_maximum_value < provided_list[loop_count]:46                current_maximum_value = provided_list[loop_count]4748            if loop_count == len(provided_list) - 1:49                # We want to be in here when we're at the last digit to record sequence information50                # but we need to break before the next if statement, because it will throw out of range exception51                break5253            if provided_list[loop_count + 1] - provided_list[loop_count] != 1:54                sequence_bool = False5556            loop_count += 157        58        # recording sequence details59        sequence_list.append(Sequence(current_minimum_value, current_maximum_value, current_sequence_length))60    61    else:62        loop_count += 16364sequence_list.sort(key=lambda x: x.length, reverse=True)6566for i in sequence_list:
...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!!
