سؤال

Hopefully a simple question, but it doesn't seem to be covered in the documentation or web2py book...

I've got a web2py controller method that looks something like:

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

with the parameters being passed in as request variables as per the documentation

Is there any way to build a doctest (inline with the method definition) to evaluate the return value of a call such as mymethod(param1=9, param2='a', param3=3.7)?

Thanks in advance

هل كانت مفيدة؟

المحلول

Just put the desired values in request.vars within the doctest:

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

To get the doctest right, you can play around in a web2py shell, which you can start as follows:

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

That will give you a Python shell in an environment with your application's model files executed (that's what the -M option does). Because mycontroller is specified, you'll also be able to call any function in mycontroller. Run some commands in the shell and then paste the session into your docstring.

نصائح أخرى

Besides the excellent example provided by @Anthony, I also tried using urllib2.urlopen(...) when testing a restful service. The code is not very clean from the doc perspective, but it works.

@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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top