The "Python" implementation uploads the use cases written by Excel to the Testlink specified use case set

Source: Internet
Author: User
Tags testlink

Background

The encyclopedia says that Testlink is a web-based test case management system, where the main function is the creation, management, and execution of test cases, and also provides some simple statistical functions. Other information can be referred to their official website http://www.testlink.org/ .

The project that the landlord is in, the demand, the measurement, the test and so on are all used is the Gitlab one issue adds the label management, the use case maintenance at the beginning also uses it. Later, our direct superior position changed, the new leader recommended that we use Testlink.

After a trial period of time, we found a very frustrating place-- use case import only supports XML format , and it is not easy to write its own use case.

This is also my intention to write this use case import gadget.

Ideas

At the beginning, bloggers wanted to convert the use cases written by Excel (Excel should be the first choice for all testers to write use cases) to XML format imports, and later found a better way to encapsulate the Python testlink API.

Write more hastily, there are many areas that can be improved, first use up, follow-up optimization.

Concrete implementation of environmental dependencies
Environmental Dependency Installation Method
Python3 Slightly
XLRD Library Pip Install Xlrd
Testlink Library Pip Install Testlink-api-python-client
Directory structure

The directory structure is as follows, the TestCase directory is used to store test cases, upload_excel_data.py for use case conversion uploads, logger_better.py for logging.

D:\PROJECT\UPLOAD_DATA2TESTLIN│  logger_better.py│  upload_excel_data.py│└─testCase        testCase_Example.xlsx
How to use
    • After landing Testlink, click on the above personal account to enter the personal Center, new page click ' Generate new key ', use this key to replace the key value in the upload_excel_data.py file;

    • Use the Get_projects_info function to get the project_id of the project, replacing the project_id in upload_excel_data.py
    • Use the mouse to select the set of use cases to upload the use case, right-click to get the parent node ID, replace the father_id in upload_excel_data.py

Upload Content
#! /usr/bin/python# coding:utf-8 "" "@author: bingo.he @file: upload_excel_data.py @time: 2018/05/03" "" Import Collectionsimport testlinkimport xlrdimport osfrom logger_better Import loglogger = Log (Os.path.basename (__file__))  count_success = 0count_fail = 0def get_projects_info (): Project_ids = [] projects = Tlc.getprojects () for project In Projects:project_ids.append ({project[' name ']: project[' ID '}) return Project_idsdef get_projects_id (): P Roject_ids = [] projects = Tlc.getprojects () for project in Projects:project_ids.append (project[' ID ')) re Turn Project_idsdef get_suites (suite_id): "" "gets the use case set: return:" "" Try:suites = Tlc.gettestsuitebyid (        SUITE_ID) return suites except Testlink.testlinkerrors.TLResponseError as E: # Traceback.print_exc () Logger.warning (str (e). Split (' \ n ') [1]) logger.warning (str (e). Split (' \ n ') [0]) returndef readexcel (file_path ): "" reads the use case data: return: "" "CAse_list = [] Try:book = Xlrd.open_workbook (file_path) # Open Excel except Exception as ERROR:LOGGER.E        Rror (' Path not present or Excel incorrect: ' + str (error)) ' return error Else:sheet = Book.sheet_by_index (0) # Take the first sheet page rows = sheet.nrows # Take all lines of this sheet page for I in range (rows): if I! = 0:case_list.appe nd (Sheet.row_values (i)) # Add each test case to Case_list return case_listdef Check_excel_data (func): "" "Parameter Validation:p ARA M func:: Return: "" "Def _check (*args, **kw): Global Count_fail Global count_success # Validate Project I D and the validity of the test set ID if not args[0] in get_projects_id (): Logger.error (' project_id are not auth ') retur N If not get_suites (Args[1]): Logger.error (' father_id are not auth ') return # test data is valid Sex for K, V in Kw.items (): if v = = "" and k not in [' Summary ', ' importance ']: Logger.warni Ng ("TestCase ' {title} ' PArameter ' {k} ' is null '. Format (title=kw[' title ', K=k)) Try:func (Args[0], args[1], kw) count _success + = 1 except Exception as E:logger.error (e) Count_fail + = 1 return _checkdef form        At_info (Source_data): "" "translates the Excel Chinese keyword:p aram source_data:: Return:" "" Switcher = {"Low": 1, "Medium": 2, "High": 3, "Automation": 2, "Manual": 1} return Switcher.get (Source_data, "Param not Defind") @che    Ck_excel_datadef create_testcase (test_project_id, suits_id, data): "" ":p Aram test_project_id::p Aram suits_id:  :p Aram Data:: Return: "" "# Set priority default value and summary default value if data[' importance '] not in [1, 2, 3]: data[' importance ']        = 3 if data["Summary"] = = "": data["Summary"] = "None" # Initialize test steps and expected results for I in range (0, Len (data["Step")): Tlc.appendstep (data["step"][i][0], data["step"][i][1], data["Automation"]) Tlc.createtestcase (data["title"], Sui ts_id, test_project_id,data["Authorlogin"], data["Summary"], preconditions=data["preconditions"], importance=data[' Importan Ce '], executiontype=2) def excute_creat_testcase (test_project_id, test_father_id, Test_file_name): # to PROJECT_ID father_id do validity judgment if test_project_id not in get_projects_id (): Logger.error (' project_id are not auth ') Retu RN If not get_suites (test_father_id): Logger.error (' father_id are not auth ') return # get use case Test_case s = Readexcel (Os.path.join (' testCase ', test_file_name)) if not isinstance (Test_cases, collections. iterable): Return # Format use case data for test_case in Test_cases:testcase_data = {"title": Test_ca Se[0], "preconditions": test_case[1], "Step": List (Zip ("test_case[2].split (' \ n '), Test_case[3].split ( ' \ n ')), # with a newline character as the demarcation of the test Step "Automation": Format_info (Test_case[4]), # 1 manual, 2 Automatic "Authorlogin": tes T_CASE[5], "importance": Format_info (Test_CASE[6]), "Summary": Test_case[7]} create_testcase (test_project_id, test_father_id, **testcase_ Data) Logger.info ("The operation has committed {}, successfully imported {} bar, failed {}". Format (count_success + Count_fail, count_success, Count_fail)) If _ _name__ = = "__main__": url = "http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php" # replaced with testlink corresponding URL key = "3ac a080de61e3e24b5be209a23fa0652 "# This key is the wrong key, after landing Testlink click on the upper personal account to enter the personal Center, new page click ' Generate new key ' get file_name =" Testcase_ Example.xlsx "project_id =" 2354879 "# can be obtained by print (Get_projects_info ()) father_id =" 2054879 "# Mouse Select the set of use cases that you want to upload a use case, click Right-click to get parent Node ID TLC = Testlink. Testlinkapiclient (URL, key) # Print ("Project information:", Get_projects_info ()) excute_creat_testcase (project_id, father_id, file _name)
Logger content
#! /usr/bin/python# coding:utf-8 "" "@author: bingo.he @file: logger_better.py @time: 2018/02/12" "" Import Loggingimport Tim Eimport Oscur_path = Os.path.dirname (Os.path.realpath (__file__)) Log_path = Os.path.join (Cur_path, ' logs ') if not Os.path.exists (Log_path): Os.mkdir (Log_path) class log (): Def __init__ (self, logger, logname= ' {}.log '. Format ( Time.strftime ('%y-%m-%d ')): Self.logname = Os.path.join (Log_path, logname) Self.logger = Logging.getlogger ( Logger) Self.logger.setLevel (logging. DEBUG) Self.formatter = logging. Formatter (' [% (asctime) s]-[% (name) s]-% (levelname) s:% (message) s ') def __console (self, level, message): FH = Loggi Ng. Filehandler (Self.logname, ' a ', encoding= ' Utf-8 ') fh.setlevel (logging. DEBUG) Fh.setformatter (self.formatter) self.logger.addHandler (FH) ch = logging. Streamhandler () Ch.setlevel (logging. DEBUG) Ch.setformatter (self.formatter) self.logger.addHandler (ch) if level = = ' inFo ': self.logger.info (message) elif level = = ' Debug ': Self.logger.debug (message) elif Level = = ' Warning ': self.logger.warning (message) elif level = = ' ERROR ': Self.logger.error (mes SAGE) self.logger.removeHandler (CH) self.logger.removeHandler (FH) fh.close () def debug (self, Messa GE): Self.__console (' Debug ', message) def info (self, message): Self.__console (' info ', message) def War  Ning (self, Message): Self.__console (' warning ', message) def error (self, message): Self.__console (' Error ', message) If __name__ = = "__main__": Log = log (Os.path.basename (__file__)) log.info ("---test start----") Log.info ("Action Step 1 , 2,3 ") log.warning ("----test end----")

Other:

  • Use case Step delimiter: currently separated by line breaks, you can modify the step parameters of Testcase_data in the Excute_creat_testcase function
  • The author information in Excel must correspond to the supplied key value
Test Case format

Thanks to the author of the API here.

Python Testlink API GitHub Project Address

The "Python" implementation uploads the use cases written by Excel to the Testlink specified use case set

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.