python doctest两阶段测试

时间:2016-10-14 20:10:20

标签: python doctest

我通过编写XML API接口来学习python。大多数呼叫都需要从登录呼叫中获取的访问令牌。有没有办法从登录调用中捕获令牌以用于其他调用?即有没有办法对show_account调用进行doctest:

import requests

url = "http://api.peak.org/cgi-bin/api"
headers = {"Content-type": "application/xml"}

def login(account, pw):
    """
    login api call

    >>> login("aj@peak.org", "xyzzy") #doctest: +ELLIPSIS
    u'<?xml version="1.0" encoding="UTF-8" ?>\\n<response version="0.0.1">\\n\\n<code>0</code>\\n<message>Success</message>\\n<access_token>...</access_token>\\n</response>\\n'

    """
    login_req = '''<request version="1.0.0">
    <command>login</command>
    <account>{account}</account>
    <password>{pw}</password>
    </request>
    '''.format(account=account, pw=pw)

#    print "Sending:\n", login_req
    response = requests.post(url, headers=headers, data=login_req)
    return response.text

#
# Show Account
#

def show_account(token, target):
    """
    show_account api call

    >>> login("aj@peak.org", "xyzzy") #doctest: +ELLIPSIS
    u'<?xml version="1.0" encoding="UTF-8" ?>\\n<response version="0.0.1">\\n\\n<code>0</code>\\n<message>Success</message>\\n<access_token>...</access_token>\\n</response>\\n'
    >>> show_account("{token}", "aj@peak.org") #doctest: +ELLIPSIS
    u'<?xml version="1.0" encoding="UTF-8" ?>\\n<response version="0.0.1">\\n<code>0</code>\\n<first_name>A.J.</first_name>\\n<last_name>Brown</last_name>\\n<message>Success</message>\\n</response>\\n

    """

    acct_req = '''<request version="1.0.0">
<command>show_account</command>
<access_token>{token}</access_token>
<target_account>{target}</target_account>
</request>
'''.format(token=token, target=target)

#    print "Sending:\n", acct_req
    response = requests.post(url, headers=headers, data=acct_req)
    return response.text

if __name__ == "__main__":
    import doctest
    doctest.testmod()

0 个答案:

没有答案