2012-05-03 3 views
2

を渡すのdoctestを作成するが、マニュアルまたはweb2pyの本でカバーされていないようです...の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) 

などmymethod(param1=9, param2='a', param3=3.7)として呼び出しの戻り値を評価するためにdoctestの(メソッド定義を持つインライン)を構築する方法はあります?事前

答えて

3

おかげでだけのdoctest内request.varsで必要な値を置く:

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

doctestの権利を取得するには、あなたが開始することができますweb2pyのシェルで遊ぶことができます次のように:

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

(つまり、-Mオプションが何をするかだ)、実行アプリケーションのモデルファイルと環境で、あなたのPythonシェルを与えること。 mycontrollerが指定されているので、mycontroller内の任意の関数を呼び出すこともできます。シェルでいくつかのコマンドを実行し、そのセッションをドキュメントストリングに貼り付けます。

+0

Aha!それであなたはそれをやる方法です。私はそれがそれと同じくらい単純なものになると期待した。大変感謝しているアンソニー – monch1962

0

@Anthonyが提供する優れた例以外にも、私は安らかなサービスをテストするときに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 
関連する問題