Writing tests for Python Eve RESTful APIs against a real MongoDB

匆匆过客 提交于 2020-01-02 07:26:12

问题


I am developing my API server with Python-eve, and would like to know how to test the API endpoints. A few things that I would like to test specifically:

  • Validation of POST/PATCH requests
  • Authentication of different endpoints
  • Before_ and after_ hooks working property
  • Returning correct JSON response

Currently I am testing the app against a real MongoDB, and I can imagine the testing will take a long time to run once I have hundreds or thousands of tests to run. Mocking up stuff is another approach but I couldn't find tools that allow me to do that while keeping the tests as realistic as possible. I am wondering if there is a recommended way to test eve apps. Thanks!

Here is what I am having now:

from pymongo import MongoClient
from myModule import create_app
import unittest, json

class ClientAppsTests(unittest.TestCase):
  def setUp(self):
    app = create_app()
    app.config['TESTING'] = True
    self.app = app.test_client()

    # Insert some fake data
    client = MongoClient(app.config['MONGO_HOST'], app.config['MONGO_PORT'])
    self.db = client[app.config['MONGO_DBNAME']]
    new_app = {
      'client_id'     : 'test',
      'client_secret' : 'secret',
      'token'         : 'token'
    }
    self.db.client_apps.insert(new_app)

  def tearDown(self):
    self.db.client_apps.remove()

  def test_access_public_token(self):
    res = self.app.get('/token')
    assert res.status_code == 200

  def test_get_token(self):
    query = { 'client_id': 'test', 'client_secret': 'secret' }
    res = self.app.get('/token', query_string=query)
    res_obj = json.loads(res.get_data())
    assert res_obj['token'] == 'token'

回答1:


The Eve test suite itself is using a test db and not mocking anything. The test db gets created and dropped on every run to guarantee isolation (not super fast yes, but as close as possible to a production environment). While of course you should test your own code, you probably don't need to write tests like test_access_public_token above since, stuff like that is covered by the Eve suite already. You might want to check the Eve Mocker extension too.

Also make yourself familiar with Authentication and Authorization tutorials. It looks like the way you're going get the whole token thing going is not really appropriate (you want to use request headers for that kind of stuff).



来源:https://stackoverflow.com/questions/23748571/writing-tests-for-python-eve-restful-apis-against-a-real-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!