The WebTest module makes it easy to write code to test WSGI-based web apps.
You can install it with pip.
sudo pip install webtest
The following is an example of a JSON-RPC server implementation using the bottle framework.
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']=='Mountain':
return makeRes('OK', {'henji':'eh?'}
else:
return makeRes('OK', {'henji':'Huh?'}
if __name__=='__main__':
app.run(host=HOST, port=PORT, debug=DEBUG, reloader=True)
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':'Mountain'
})
self.assertEqual(res.json['henji'], 'eh?')
def test_api_aikotoba2(self):
res = test_app.post_json('/aikotoba',{
'kotoba':'river'
})
self.assertEqual(res.json['henji'], 'Huh?')
if __name__ == '__main__':
unittest.main()
python app.py
python app_test.py
The result is output like this.
..
----------------------------------------------------------------------
Ran 2 tests in 0.079s
OK
If the asserts of the UnitTest class do not match, the output will look like the one below.
.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'], 'Huh?')
AssertionError: 'Huh?' != 'Huh?'
-Huh?
? ^
+Huh?
? ^
----------------------------------------------------------------------
Ran 2 tests in 0.126s
FAILED (failures=1)
Recommended Posts