Le module WebTest facilite l'écriture de code pour tester les applications Web basées sur WSGI.
Vous pouvez l'installer avec pip.
sudo pip install webtest
Voici un exemple d'implémentation de serveur JSON-RPC utilisant le framework de bouteille.
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']=='Montagne':
		return makeRes('OK', {'henji':'hein?'}
	else:
		return makeRes('OK', {'henji':'Hein?'}
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':'Montagne' 
		})
		self.assertEqual(res.json['henji'], 'hein?')
	def test_api_aikotoba2(self):
		res = test_app.post_json('/aikotoba',{
			'kotoba':'rivière' 
		})
		self.assertEqual(res.json['henji'], 'Hein?')
if __name__ == '__main__':
    unittest.main()
python app.py
python app_test.py
Le résultat est affiché comme ceci.
..
----------------------------------------------------------------------
Ran 2 tests in 0.079s
OK
Si l'assertion de la classe UnitTest ne correspond pas, la sortie ressemblera à celle ci-dessous.
.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'], 'Hein?')
AssertionError: 'Hein?' != 'Hein?'
-Hein?
? ^
+Hein?
? ^
----------------------------------------------------------------------
Ran 2 tests in 0.126s
FAILED (failures=1)
Recommended Posts