LoginSignup
11

More than 5 years have passed since last update.

PythonのWebアプリをUnitTestするコードを書く

Last updated at Posted at 2015-07-25

WebTestモジュールを使うと、WSGIベースのWebアプリをテストするコードを簡単に書くことができます。

インストール方法

pipでインストールできます。

sudo pip install webtest

サンプルコード

以下はbottleフレームワークを使った、JSON-RPCサーバ実装の例です。

Webアプリ側

app.py
from bottle import Bottle, HTTPResponse

HOST='localhost'
PORT=8080
DEBUG=True

app = Bottle()

def makeRes(code, data):
    data['retcode'] = code
    r = HTTPResponse(status=200, body=json.dumps(data))
    r.set_header('Content-Type', 'application/json')
    return r

@app.post('/aikotoba')
def api_aikotoba():
    o = request.json
    if o is None:
        return makeRes('ERR_PARAM', {})
    if not 'kotoba' in o:
        return makeRes('ERR_PARAM', {})
    if o['kotoba']=='山':
        return makeRes('OK', {'henji':'えっ?'}
    else:
        return makeRes('OK', {'henji':'はっ?'}

if __name__=='__main__':
    app.run(host=HOST, port=PORT, debug=DEBUG, reloader=True)

UnitTest側

test_app.py
import unittest
import api 
from webtest import TestApp

os.environ['WEBTEST_TARGET_URL'] = 'http://localhost:8080'
test_app = TestApp(api.app)

class ApiTest(unittest.TestCase):
    def test_api_aikotoba1(self):
        res = test_app.post_json('/aikotoba',{
            'kotoba':'山' 
        })
        self.assertEqual(res.json['henji'], 'えっ?')
    def test_api_aikotoba2(self):
        res = test_app.post_json('/aikotoba',{
            'kotoba':'川' 
        })
        self.assertEqual(res.json['henji'], 'はっ?')

if __name__ == '__main__':
    unittest.main()

テスト実施

1.テストサーバを立ち上げます。

python app.py

2.UnitTestを実行します。

python app_test.py

3.結果を確認します。

こんな感じで結果が出力されます。

..
----------------------------------------------------------------------
Ran 2 tests in 0.079s

OK

UnitTestクラスのassertなんちゃらが不一致の場合、下記のような感じで出力されます。

.F
======================================================================
FAIL: test_api_aikotoba2 (__main__.ApiTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_app.py", line 16, in test_api_aikotoba2
    self.assertEqual(res.json['henji'], 'はっ?')
AssertionError: 'へっ?' != 'はっ?'
- へっ?
? ^
+ はっ?
? ^


----------------------------------------------------------------------
Ran 2 tests in 0.126s

FAILED (failures=1)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11