Python+unittest+excel
阅读原文时间:2023年07月09日阅读:1

接口测试设计思想:

框架结构如下:

目录如下:

readme:

config下的run_case_config.ini 文件说明:
run_mode: 0:获取所有sheet页 1: if case_list=="":运行指定sheet页的所有用例 else 运行指定测试用例

python -m grpc_tools.protoc -I ./protoFile --python_out=./protoFile --grpc_python_out=./protoFile ./protoFile/ads_strategy.proto
python -m grpc_tools.protoc -I. --python_out=./protoFile ./protoFile/ads_voice.proto
protoc -I=$SRC_DIR descriptor_set_out=$DST_DIR/***.desc $SRC_DIR/***.proto

程序:

HTMLTestRunner.py文件:

"""
A TestRunner for use with the Python unit testing framework. It
generates a HTML report to show the result at a glance.

The simplest way to use this is to invoke its main method. E.g.

import unittest  
import HTMLTestRunner

... define your tests ...

if \_\_name\_\_ == '\_\_main\_\_':  
    HTMLTestRunner.main()

For more customization options, instantiates a HTMLTestRunner object.
HTMLTestRunner is a counterpart to unittest's TextTestRunner. E.g.

# output to a file  
fp = file('my\_report.html', 'wb')  
runner = HTMLTestRunner.HTMLTestRunner(  
            stream=fp,  
            title='My unit test',  
            description='This demonstrates the report output by HTMLTestRunner.'  
            )

# Use an external stylesheet.  
# See the Template\_mixin class for more customizable options  
runner.STYLESHEET\_TMPL = '<link rel="stylesheet" href="my\_stylesheet.css" type="text/css">'

# run the test  
runner.run(my\_test\_suite)

Copyright (c) 2004-2007, Wai Yip Tung
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name Wai Yip Tung nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

URL: http://tungwaiyip.info/software/HTMLTestRunner.html

__author__ = "Wai Yip Tung"
__version__ = "0.8.2"

"""
Change History

Version 0.8.2
* Show output inline instead of popup window (Viorel Lupu).

Version in 0.8.1
* Validated XHTML (Wolfgang Borgert).
* Added description of test classes and test cases.

Version in 0.8.0
* Define Template_mixin class for customization.
* Workaround a IE 6 bug that it does not treat

%(heading)s
%(report)s
%(ending)s



"""
# variables: (title, generator, stylesheet, heading, report, ending)

# ------------------------------------------------------------------------  
# Stylesheet  
#  
# alternatively use a <link> for external style sheet, e.g.  
#   <link rel="stylesheet" href="$url" type="text/css">

STYLESHEET\_TMPL = """  


"""

# ------------------------------------------------------------------------  
# Heading  
#

HEADING\_TMPL = """<div class='heading'>  

%(title)s


%(parameters)s

%(description)s


""" # variables: (title, parameters, description)

HEADING\_ATTRIBUTE\_TMPL = """<p class='attribute'><strong>%(name)s:</strong> %(value)s</p>  

""" # variables: (name, value)

# ------------------------------------------------------------------------  
# Report  
#

REPORT\_TMPL = """  

Show Summary Failed All

%(test\_list)s
Test Group/Test case Count Pass Fail Error View
Total %(count)s %(Pass)s %(fail)s %(error)s  


""" # variables: (test_list, count, Pass, fail, error)

REPORT\_CLASS\_TMPL = r"""  

%(desc)s %(count)s %(Pass)s %(fail)s %(error)s Detail
""" # variables: (style, desc, count, Pass, fail, error, cid)

REPORT\_TEST\_WITH\_OUTPUT\_TMPL = r"""  


%(desc)s

<!--css div popup start-->  
<a class="popup\_link" onfocus='this.blur();' href="javascript:showTestDetail('div\_%(tid)s')" >  
    %(status)s</a>

<div id='div\_%(tid)s' class="popup\_window">  
    <div style='text-align: right; color:red;cursor:pointer'>  
    <a onfocus='this.blur();' onclick="document.getElementById('div\_%(tid)s').style.display = 'none' " >  
       \[x\]</a>  
    </div>  
    <pre>  
    %(script)s  
    </pre>  
</div>  
<!--css div popup end-->

</td>  


""" # variables: (tid, Class, style, desc, status)

REPORT\_TEST\_NO\_OUTPUT\_TMPL = r"""  

%(desc)s
%(status)s
""" # variables: (tid, Class, style, desc, status)

REPORT\_TEST\_OUTPUT\_TMPL = r"""  

%(id)s: %(output)s
""" # variables: (id, output)

# ------------------------------------------------------------------------  
# ENDING  
#

ENDING\_TMPL = """<div id='ending'>&nbsp;</div>"""

-------------------- The end of the Template class -------------------

TestResult = unittest.TestResult

class _TestResult(TestResult):
# note: _TestResult is a pure representation of results.
# It lacks the output and reporting ability compares to unittest._TextTestResult.

def \_\_init\_\_(self, verbosity=1):  
    TestResult.\_\_init\_\_(self)  
    self.stdout0 = None  
    self.stderr0 = None  
    self.success\_count = 0  
    self.failure\_count = 0  
    self.error\_count = 0  
    self.verbosity = verbosity

    # result is a list of result in 4 tuple  
    # (  
    #   result code (0: success; 1: fail; 2: error),  
    #   TestCase object,  
    #   Test output (byte string),  
    #   stack trace,  
    # )  
    self.result = \[\]

def startTest(self, test):  
    TestResult.startTest(self, test)  
    # just one buffer for both stdout and stderr  
    self.outputBuffer = StringIO.StringIO()  
    stdout\_redirector.fp = self.outputBuffer  
    stderr\_redirector.fp = self.outputBuffer  
    self.stdout0 = sys.stdout  
    self.stderr0 = sys.stderr  
    sys.stdout = stdout\_redirector  
    sys.stderr = stderr\_redirector

def complete\_output(self):  
    """  
    Disconnect output redirection and return buffer.  
    Safe to call multiple times.  
    """  
    if self.stdout0:  
        sys.stdout = self.stdout0  
        sys.stderr = self.stderr0  
        self.stdout0 = None  
        self.stderr0 = None  
    return self.outputBuffer.getvalue()

def stopTest(self, test):  
    # Usually one of addSuccess, addError or addFailure would have been called.  
    # But there are some path in unittest that would bypass this.  
    # We must disconnect stdout in stopTest(), which is guaranteed to be called.  
    self.complete\_output()

def addSuccess(self, test):  
    self.success\_count += 1  
    TestResult.addSuccess(self, test)  
    output = self.complete\_output()  
    self.result.append((0, test, output, ''))  
    if self.verbosity > 1:  
        sys.stderr.write('ok ')  
        sys.stderr.write(str(test))  
        sys.stderr.write('\\n')  
    else:  
        sys.stderr.write('.')

def addError(self, test, err):  
    self.error\_count += 1  
    TestResult.addError(self, test, err)  
    \_, \_exc\_str = self.errors\[-1\]  
    output = self.complete\_output()  
    self.result.append((2, test, output, \_exc\_str))  
    if self.verbosity > 1:  
        sys.stderr.write('E  ')  
        sys.stderr.write(str(test))  
        sys.stderr.write('\\n')  
    else:  
        sys.stderr.write('E')

def addFailure(self, test, err):  
    self.failure\_count += 1  
    TestResult.addFailure(self, test, err)  
    \_, \_exc\_str = self.failures\[-1\]  
    output = self.complete\_output()  
    self.result.append((1, test, output, \_exc\_str))  
    if self.verbosity > 1:  
        sys.stderr.write('F  ')  
        sys.stderr.write(str(test))  
        sys.stderr.write('\\n')  
    else:  
        sys.stderr.write('F')

class HTMLTestRunner(Template_mixin):
"""
"""
def __init__(self, stream=sys.stdout, verbosity=1, title=None, description=None):
self.stream = stream
self.verbosity = verbosity
if title is None:
self.title = self.DEFAULT_TITLE
else:
self.title = title
if description is None:
self.description = self.DEFAULT_DESCRIPTION
else:
self.description = description

    self.startTime = datetime.datetime.now()

def run(self, test):  
    "Run the given test case or test suite."  
    result = \_TestResult(self.verbosity)  
    test(result)  
    self.stopTime = datetime.datetime.now()  
    self.generateReport(test, result)  
    print >>sys.stderr, '\\nTime Elapsed: %s' % (self.stopTime-self.startTime)  
    return result

def sortResult(self, result\_list):  
    # unittest does not seems to run in any particular order.  
    # Here at least we want to group them together by class.  
    rmap = {}  
    classes = \[\]  
    for n,t,o,e in result\_list:  
        cls = t.\_\_class\_\_  
        if not rmap.has\_key(cls):  
            rmap\[cls\] = \[\]  
            classes.append(cls)  
        rmap\[cls\].append((n,t,o,e))  
    r = \[(cls, rmap\[cls\]) for cls in classes\]  
    return r

def getReportAttributes(self, result):  
    """  
    Return report attributes as a list of (name, value).  
    Override this to add custom attributes.  
    """  
    startTime = str(self.startTime)\[:19\]  
    duration = str(self.stopTime - self.startTime)  
    status = \[\]  
    if result.success\_count: status.append('Pass %s'    % result.success\_count)  
    if result.failure\_count: status.append('Failure %s' % result.failure\_count)  
    if result.error\_count:   status.append('Error %s'   % result.error\_count  )  
    if status:  
        status = ' '.join(status)  
    else:  
        status = 'none'  
    return \[  
        ('Start Time', startTime),  
        ('Duration', duration),  
        ('Status', status),  
    \]

def generateReport(self, test, result):  
    report\_attrs = self.getReportAttributes(result)  
    generator = 'HTMLTestRunner %s' % \_\_version\_\_  
    stylesheet = self.\_generate\_stylesheet()  
    heading = self.\_generate\_heading(report\_attrs)  
    report = self.\_generate\_report(result)  
    ending = self.\_generate\_ending()  
    output = self.HTML\_TMPL % dict(  
        title = saxutils.escape(self.title),  
        generator = generator,  
        stylesheet = stylesheet,  
        heading = heading,  
        report = report,  
        ending = ending,  
    )  
    self.stream.write(output.encode('utf8'))

def \_generate\_stylesheet(self):  
    return self.STYLESHEET\_TMPL

def \_generate\_heading(self, report\_attrs):  
    a\_lines = \[\]  
    for name, value in report\_attrs:  
        line = self.HEADING\_ATTRIBUTE\_TMPL % dict(  
                name = saxutils.escape(name),  
                value = saxutils.escape(value),  
            )  
        a\_lines.append(line)  
    heading = self.HEADING\_TMPL % dict(  
        title = saxutils.escape(self.title),  
        parameters = ''.join(a\_lines),  
        description = saxutils.escape(self.description),  
    )  
    return heading

def \_generate\_report(self, result):  
    rows = \[\]  
    sortedResult = self.sortResult(result.result)  
    for cid, (cls, cls\_results) in enumerate(sortedResult):  
        # subtotal for a class  
        np = nf = ne = 0  
        for n,t,o,e in cls\_results:  
            if n == 0: np += 1  
            elif n == 1: nf += 1  
            else: ne += 1

        # format class description  
        if cls.\_\_module\_\_ == "\_\_main\_\_":  
            name = cls.\_\_name\_\_  
        else:  
            name = "%s.%s" % (cls.\_\_module\_\_, cls.\_\_name\_\_)  
        doc = cls.\_\_doc\_\_ and cls.\_\_doc\_\_.split("\\n")\[0\] or ""  
        desc = doc and '%s: %s' % (name, doc) or name

        row = self.REPORT\_CLASS\_TMPL % dict(  
            style = ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass',  
            desc = desc,  
            count = np+nf+ne,  
            Pass = np,  
            fail = nf,  
            error = ne,  
            cid = 'c%s' % (cid+1),  
        )  
        rows.append(row)

        for tid, (n,t,o,e) in enumerate(cls\_results):  
            self.\_generate\_report\_test(rows, cid, tid, n, t, o, e)

    report = self.REPORT\_TMPL % dict(  
        test\_list = ''.join(rows),  
        count = str(result.success\_count+result.failure\_count+result.error\_count),  
        Pass = str(result.success\_count),  
        fail = str(result.failure\_count),  
        error = str(result.error\_count),  
    )  
    return report

def \_generate\_report\_test(self, rows, cid, tid, n, t, o, e):  
    # e.g. 'pt1.1', 'ft1.1', etc  
    has\_output = bool(o or e)  
    tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)  
    name = t.id().split('.')\[-1\]  
    doc = t.shortDescription() or ""  
    desc = doc and ('%s: %s' % (name, doc)) or name  
    tmpl = has\_output and self.REPORT\_TEST\_WITH\_OUTPUT\_TMPL or self.REPORT\_TEST\_NO\_OUTPUT\_TMPL

    # o and e should be byte string because they are collected from stdout and stderr?  
    if isinstance(o,str):  
        # TODO: some problem with 'string\_escape': it escape \\n and mess up formating  
        # uo = unicode(o.encode('string\_escape'))  
        uo = o.decode('latin-1')  
    else:  
        uo = o  
    if isinstance(e,str):  
        # TODO: some problem with 'string\_escape': it escape \\n and mess up formating  
        # ue = unicode(e.encode('string\_escape'))  
        ue = e.decode('latin-1')  
    else:  
        ue = e

    script = self.REPORT\_TEST\_OUTPUT\_TMPL % dict(  
        id = tid,  
        output = saxutils.escape(uo+ue),  
    )

    row = tmpl % dict(  
        tid = tid,  
        Class = (n == 0 and 'hiddenRow' or 'none'),  
        style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),  
        desc = desc,  
        script = script,  
        status = self.STATUS\[n\],  
    )  
    rows.append(row)  
    if not has\_output:  
        return

def \_generate\_ending(self):  
    return self.ENDING\_TMPL

##############################################################################

Facilities for running tests from the command line

##############################################################################

Note: Reuse unittest.TestProgram to launch test. In the future we may

build our own launcher to support more specific command line

parameters like test title, CSS, etc.

class TestProgram(unittest.TestProgram):
"""
A variation of the unittest.TestProgram. Please refer to the base
class for command line parameters.
"""
def runTests(self):
# Pick HTMLTestRunner as the default test runner.
# base class's testRunner parameter is not useful because it means
# we have to instantiate HTMLTestRunner before we know self.verbosity.
if self.testRunner is None:
self.testRunner = HTMLTestRunner(verbosity=self.verbosity)
unittest.TestProgram.runTests(self)

main = TestProgram

##############################################################################

Executing this module from the command line

##############################################################################

if __name__ == "__main__":
main(module=None)

configrunmode.py

# -*- coding:utf-8 -*-

import configparser

class ConfigRunMode:
def __init__(self, run_case_config_file):
config = configparser.ConfigParser()
# 从配置文件中读取运行模式
config.read(run_case_config_file)
try:
self.run_mode = config['RUNCASECONFIG']['run_mode']
self.run_mode = int(self.run_mode)
self.excel_name = config['RUNCASECONFIG']['excel_name']
self.sheet_list = config['RUNCASECONFIG']['sheet_list']
self.case_list = config['RUNCASECONFIG']['case_list']
self.case_list = eval(self.case_list) # 把字符串类型的list转换为list
self.sheet_list = eval(self.sheet_list) # 同上
except Exception as e:
print('%s', e)

def get\_run\_mode(self):  
    return self.run\_mode

def get\_case\_list(self):  
    return self.case\_list

def get\_sheet\_list(self):  
    return self.sheet\_list

def get\_excel\_name(self):  
    return self.excel\_name

utf-8递归编码:

# -*- coding:utf-8 -*-

def unicode_convert(input):
if isinstance(input, dict):
return {unicode_convert(key): unicode_convert(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [unicode_convert(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input

if __name__=="__main__":
input = ['\\u6355\\u9c7c\\u6bd4\\u8d5b', '\\u8109\\u8109', '\\u7f8e\\u7f8e\\u7bb1', '\\u9b54buy\\u5546\\u57ce',
'\\u9b54\\u7b1b\\u6298\\u4e0a\\u6298', '\\u53ef\\u5f97\\u773c\\u955c', '\\u5c48\\u81e3\\u6c0f', '\\u4f18\\u9009',
'\\u5168\\u6c11\\u4f18\\u60e0', '\\u5c1a\\u54c1\\u7f51', '\\u826f\\u4ed3', '\\u624b\\u673a\\u5929\\u732b',
'\\u60e0\\u55b5', '\\u60e0\\u54c1\\u6298', '\\u62cd\\u56fe\\u8d2d']
result = unicode_convert(input)
print result

globalconfig.py

# -*- coding:utf-8 -*-

from configrunmode import ConfigRunMode

class Global(object):
def __init__(self):
# 读取运行模式配置
self.run_mode_config = ConfigRunMode(r'E:\NewSearchApiTest\NewSearch\config\run_case_config.ini')

# 获取运行模式配置  
def get\_run\_mode(self):  
    return self.run\_mode\_config.get\_run\_mode()

# 获取需要运行的excel  
def get\_run\_excel\_name(self):  
    return self.run\_mode\_config.get\_excel\_name()

# 获取需要单独运行的用例列表  
def get\_run\_case\_list(self):  
    return self.run\_mode\_config.get\_case\_list()

# 获取需要单独运行的sheet列表  
def get\_run\_sheet\_list(self):  
    return self.run\_mode\_config.get\_sheet\_list()

parse_excel.py

# -*- coding:utf-8 -*-
"""从excel中获取请求参数,并返回结果"""
import xlrd
import os
from collections import namedtuple
from request_method import *
from file_actions import *
import json
from element_encode import unicode_convert

col_name = ["CaseName", "API_Protocol", "Request_URL", "Request_Method", "Request_Data_Type", "Request_Data", "Check_Point", "Note", "Steps", "Action"]
col_obj = namedtuple("col", col_name)
col = col_obj(*(i for i in range(len(col_name))))

class ParseExcel(object):
"""从excel中获取请求参数"""
def __init__(self, flag, excelName, tableName = None, caseName = None):
self.excel_path = os.path.normpath(
os.path.join(os.path.join(r'E:\NewSearchApiTest\data'), str(excelName)))
self.excel_name = excelName
self.table_name = tableName
self.case_name = caseName
self.flag = flag

def \_get\_table(self):  
    """flag=1: 获取指定sheet页;flag=0: 获取所有sheet页"""  
    excel = xlrd.open\_workbook(self.excel\_path)  
    sheet\_names = excel.sheet\_names()  
    if self.flag:  
        if self.table\_name in sheet\_names:  
            return self.table\_name.split()  
        else:  
            raise ValueError("sheet {} not found in {}".format(self.table\_name, self.excel\_path))  
    else:  
        return sheet\_names

def get\_content(self):  
    sheets = self.\_get\_table()  
    excel = xlrd.open\_workbook(self.excel\_path)  
    for sheet in sheets:  
        table = excel.sheet\_by\_name(sheet)  
        line\_num = table.nrows  
        if line\_num < 2:  
            print ("The content of %s is null ! ")  
            raise ValueError("the sheet content is null!")  
        else:  
            for i in range(1, line\_num):  
                line = table.row\_values(i)  
                if line == "":  
                    pass  
                else:  
                    url = eval(json.dumps(line\[col.Request\_URL\]).strip())  
                    pre\_body = json.loads(line\[col.Request\_Data\])  
                    request\_method = line\[col.Request\_Method\]  
                    data\_type = line\[col.Request\_Data\_Type\]  
                    if self.flag == 0 or (self.flag and self.case\_name == \[\]): #获取所有用例数据 或者指定sheet页中的所有用例  
                        print "\\n用例名称:", line\[col.CaseName\]  
                        print "用例说明:", line\[col.Note\]  
                        print "请求URL:", url  
                        resp\_result = unicode\_convert(request\_methods(url, data\_type, request\_method, pre\_body))  
                        print "返回结果:" , json.dumps(resp\_result)  
                        check\_point = line\[col.Check\_Point\]  
                        write\_data('checkfile.txt', line\[col.CaseName\], check\_point)  
                        write\_data('result.txt', line\[col.CaseName\], str(resp\_result))  
                        continue  
                    elif self.flag:  
                        for case in self.case\_name:  
                            if line\[col.CaseName\] == case: #获取指定用例的数据  
                                print "\\n用例名称:", line\[col.CaseName\]  
                                print "用例说明:", line\[col.Note\]  
                                print "请求URL:", url  
                                resp\_result = unicode\_convert(request\_methods(url, data\_type, request\_method, pre\_body))  
                                print "返回结果:", json.dumps(resp\_result)  
                                check\_point = line\[col.Check\_Point\]  
                                write\_data('checkfile.txt', line\[col.CaseName\], check\_point)  
                                write\_data('result.txt', line\[col.CaseName\], str(resp\_result))  
                                break  
                            # else:  
                            #     if i == (line\_num - 1):  
                            #         raise ValueError("caseName: {} not found!".format(self.case\_name))

if __name__ == '__main__':
# 指定sheet页中指定case
excel_object = ParseExcel(1, "test_case_excel.xlsx", tableName="Sheet1", caseName="card_recom_01")

#运行指定sheet页中的所有cases  
# excel\_object = ParseExcel("test\_case\_excel.xlsx", tableName="Sheet1", flag=1)

# 运行所有sheet中的所有用例  
# excel\_object = ParseExcel("test\_case\_excel.xlsx", flag=0)  
resp\_list = excel\_object.get\_content()  
# print resp\_list

parse_response.py

# -*- coding:utf-8 -*-

from parse_excel import ParseExcel
import json
import collections
import re

def adid_appid_list(case_name):
tree = lambda: collections.defaultdict(tree)
appid_adid_list = tree()
with open(r'E:\NewSearchApiTest\NewSearch\tmp\result.txt', 'r') as f:
for line in f.readlines():
if line.split(":")[0] == case_name:
appid_list = re.findall('\d+', str(re.findall("'appId': '\d+'", line)))
adid_list = re.findall('\d+', str(re.findall("'adId': '\d+'", line)))
appid_adid_list[case_name]['appid'] = appid_list
appid_adid_list[case_name]['adid'] = adid_list
# print json.dumps(appid_adid_list)
return json.dumps(appid_adid_list), appid_list, adid_list

if __name__=="__main__":

a, b, c = adid_appid_list('card_recom_05')

print a

request_method.py

# -*- coding:utf-8 -*-

请求并返回结果

import json
import requests
import time
from ads_merge_pb2 import *
from google.protobuf.json_format import MessageToDict, ParseDict

def pbToBody(pre_body):
req_body = json.dumps(pre_body)
print '请求Body:' + req_body
pbmsg = AdsRequest()
ParseDict(js_dict=pre_body, message=pbmsg)
boby = pbmsg.SerializeToString()
return boby

def covertrespb2dict(res):
respb = AdsResponse()
respb.ParseFromString(res)
return MessageToDict(respb)

def request_methods(url, data_type, request_method, pre_body):
body = pre_body
if data_type == "json":
header = {
'Content-Type': 'application/json;charset=utf-8 '
}
elif data_type == "pb":
header = {
'Content-Type': 'application/x-protostuff;charset=UTF-8'
}
body = pbToBody(pre_body)
elif data_type == "x-java":
header = {
'Content-Type': 'application/x-java-serialized-object'
}
if request_method == "post":
resp = requests.post(url, data=body, headers=header, verify=False)
else:
resp = requests.get(url, data=json.dumps(body), headers=header, verify=False)
time.sleep(0.2)
result2 = resp.content
print resp.status_code
if data_type == "pb":
resp = covertrespb2dict(result2)
if data_type == "Json":
resp = json.loads(json.dumps(result2, ensure_ascii=False, indent=4))
return resp

run_cases.py

# -*- coding:utf-8 -*-

from Search.common.parse_excel import ParseExcel

class RunCase(object):
"""# run_mode: 1: 获取指定sheet页;0: 获取所有sheet页"""
def __init__(self, run_mode, run_excel_name, run_sheet_list, run_case_list):
self.run_mode = run_mode
self.run_excel_name = run_excel_name
self.run_sheet_list = run_sheet_list
self.run_case_list = run_case_list

def run\_case(self):  
    if self.run\_mode == 0:  # 获取所有sheet页  
        excel\_object = ParseExcel(self.run\_mode, self.run\_excel\_name)  
    if self.run\_mode == 1:  
        if self.run\_case\_list == "":  # 运行指定sheet页的所有用例  
            excel\_object = ParseExcel(self.run\_mode, self.run\_excel\_name, self.run\_sheet\_list)  
        else:  
            excel\_object = ParseExcel(self.run\_mode, self.run\_excel\_name, self.run\_sheet\_list, self.run\_case\_list)  
    excel\_object.get\_content()

zookeeper.py

# -*- coding: utf-8 -*-
import json
import sys
import time
from kazoo.client import KazooClient,KazooState
import logging
logging.basicConfig(
level=logging.DEBUG
,stream=sys.stdout
,format='%(asctime)s %(pathname)s %(funcName)s%(lineno)d %(levelname)s: %(message)s')

biz_config_path='${路经}'

def get_full_config_path(app,config_item):
return biz_config_path+'/'+app+'/'+config_item

class Ads_Zk_Config_Client(object):
def __init__(self, zk_connect_str='11.73.31.132:2181'):
self.zk=KazooClient(hosts=zk_connect_str)

def getConfig(self,app=None,config\_item=None):  
    if ( app ) and (config\_item):  
        if not self.zk.connected:  
            self.zk.start()  
        data, stat = self.zk.get(get\_full\_config\_path(app,config\_item))  
        return data  
    else:  
        print 'app or config\_tiem is none'  
        return None

def setConfig(self, app=None, config\_item=None,value=None):  
    if ( app ) and (config\_item) and ( value):  
        if not self.zk.connected:  
            self.zk.start()  
        self.zk.set(path=get\_full\_config\_path(app,config\_item),value=value)  
    else:  
        print 'app or config\_tiem  or value is none'

def close(self):  
    if not self.zk.connected:  
        self.zk.close();

def get_zk_config(host='11.73.31.132:2181',app=None,config_item=None):
zk_client = Ads_Zk_Config_Client(zk_connect_str=host)
data = zk_client.getConfig(app=app,config_item=config_item);
zk_client.close()
return data

def set_zk_config(host='11.73.31.132:2181',app=None,config_item=None,value=None):
zk_client = Ads_Zk_Config_Client(zk_connect_str=host)
data=zk_client.setConfig(app=app,config_item=config_item,value=value);
zk_client.close()
return data

def update_zk_config(app='sbid',configdict=None):
if configdict:
logging.debug(json.dumps(configdict))
for k, v in configdict.items():
if get_zk_config(app=app, config_item=k) != v:
logging.debug(msg='before change config ' + get_zk_config(app=app,config_item=k))
if type(v) == dict:
v = json.dumps(v)
set_zk_config(app=app, config_item=k, value=v)
logging.debug(msg='set config ' + v)
time.sleep(1)
logging.debug(msg='final config ' + get_zk_config(app=app, config_item=k))
else:
logging.warn("config dice is None ,do not need change config")

if __name__ == '__main__':
# print json.dumps(get_full_config_path(app='sbid',config_item='sbid-bs-default-h5-btn '))

config\_value = get\_zk\_config(app='sbid',config\_item='sbid-bs-default-h5-btn')  
# print json.dumps(config\_value)

run_case_config.ini

[RUNCASECONFIG]
run_mode = 1
excel_name = test_case_excel.xlsx
sheet_list ="Sheet1"
case_list = ['card_recom_03']

main.py

# -*- coding:utf-8 -*-

案例执行main脚本

import os
from Search.common.test_suit import *
from Search.common.run_cases import RunCase
from Search.common.globalconfig import Global
from lib.HTMLTestRunner import *
import unittest

if __name__=="__main__":
# 全局配置
global_config = Global()
run_mode = global_config.get_run_mode() # 运行模式
run_excel_name = global_config.get_run_excel_name() # 获取 excel文件名
run_sheet_list = global_config.get_run_sheet_list() # 获取需要运行的sheet页列表
run_case_list = global_config.get_run_case_list() # 需要运行的用例列表

# 删除临时文件  
if os.path.isfile(r'E:\\NewSearchApiTest\\NewSearch\\tmp\\result.txt') and os.path.isfile(r'E:\\NewSearchApiTest\\NewSearch\\tmp\\checkfile.txt'):  
    os.remove(r'E:\\NewSearchApiTest\\NewSearch\\tmp\\result.txt')  
    os.remove(r'E:\\NewSearchApiTest\\NewSearch\\tmp\\checkfile.txt')

#运行测试用例  
case\_runner = RunCase(run\_mode, run\_excel\_name, run\_sheet\_list, run\_case\_list)  
case\_runner.run\_case()  
suite = unittest.makeSuite(CheckPoint)  
path = r'E:\\NewSearchApiTest\\report'  
filename = os.path.join(path, 'CheckPoint.html')  
fp = file(filename, 'wb')  
runner = HTMLTestRunner(stream=fp, title=u'XXXXX', description=u'模块:XXXXX')  
runner.run(suite)  
fp.close()