【问题标题】:web2py: creating doctests that pass parametersweb2py:创建传递参数的文档测试
【发布时间】:2012-05-03 13:31:28
【问题描述】:

希望是一个简单的问题,但文档或 web2py 书籍中似乎没有涵盖它...

我有一个看起来像这样的 web2py 控制器方法:

def mymethod():
    '''
    doctests go here
    '''
    param1 = request.vars['param1']
    param2 = request.vars['param2']
    param3 = request.vars['param3']
    # Stuff happens...
    return dict(result=result)

根据文档将参数作为请求变量传入

有没有办法构建一个 doctest(与方法定义内联)来评估调用的返回值,例如 mymethod(param1=9, param2='a', param3=3.7)

提前致谢

【问题讨论】:

    标签: python web2py doctest url-parameters


    【解决方案1】:

    只需将所需的值放在 doctest 中的 request.vars 中即可:

    def mymethod():
        '''
        >>> request.vars.update(param1=9, param2='a', param3=3.7)
        >>> mymethod()
        [expected output of mymethod goes here]
        '''
    

    为了获得正确的 doctest,您可以在 web2py shell 中进行操作,您可以按如下方式开始:

    python web2py.py -S myapp/mycontroller -M -N
    

    这将为您提供一个环境中的 Python shell,并执行应用程序的模型文件(这就是 -M 选项的作用)。由于指定了 mycontroller,您还可以调用 mycontroller 中的任何函数。在 shell 中运行一些命令,然后将会话粘贴到您的文档字符串中。

    【讨论】:

    • 啊哈!所以你就是这样做的。我希望事情就这么简单。非常感谢安东尼
    【解决方案2】:

    除了@Anthony 提供的出色示例外,我还尝试在测试 urllib2.urlopen(...) 时使用 urllib2.urlopen(...) 。从文档的角度来看,代码不是很干净,但它可以工作。

    @request.restful()
    def api():
        '''The following code demostrates how to interact with this api via python.
    
        >>> import urllib2, urllib, httplib, json
        >>> host = 'localhost:8000'
        >>> func = 'api'  # Otherwise request.function is NOT current function name during doctest
        >>> base = 'http://%s/%s/%s/%s' % (host, request.application, request.controller, func)
    
    
        Read all stuff.
        >>> json.load(urllib2.urlopen(base))
        {u'content': []}
    
        Create an entries.
        >>> p = {'name': 'Peter Pan', 'address': 'Neverland',}
        >>> r = json.load(urllib2.urlopen(base, urllib.urlencode(p)))
        >>> r['id'] > 0 and r['errors'] == {}  # typically as {'errors': {}, 'id': 1}
        True
    
        blah blah
    
        '''
        # the function body goes here
    

    【讨论】:

      猜你喜欢
      • 2011-09-14
      • 1970-01-01
      • 2021-12-08
      • 2015-11-19
      • 2022-01-02
      • 1970-01-01
      • 2021-05-25
      • 2015-03-14
      • 1970-01-01
      相关资源
      最近更新 更多