2

I have a Flask application, where the REST APIs are built using flask_restful with a MongoDB backend. I want to write Functional tests using pytest and mongomock for mocking the MongoDB to test the APIs but not able to configure that. Can anyone guide me providing an example where I can achieve the same? Here is the fixture I am using in the conftest.py file:

@pytest.fixture(scope='module')
   def test_client():
    # flask_app = Flask(__name__)
 
    # Flask provides a way to test your application by exposing the  Werkzeug test Client
    # and handling the context locals for you.
    testing_client = app.test_client()
 
    # Establish an application context before running the tests.
    ctx = app.app_context()
    ctx.push()
 
    yield testing_client  # this is where the testing happens!
 
    ctx.pop()
@pytest.fixture(autouse=True)
def patch_mongo():
    db = connect('testdb', host='mongomock://localhost')
    
    yield db
    db.drop_database('testdb')
    disconnect()
    db.close()

and here is the the test function for testing a post request for the creation of the user:

def test_mongo(test_client,patch_mongo):
    headers={
        "Content-Type": "application/json",
        "Authorization": "token"
    }
    response=test_client.post('/users',headers=headers,data=json.dumps(data))
    print(response.get_json())

    assert response.status_code == 200

The issue is that instead of using the testdb, pytest is creating the user in the production database. is there something missing in the configuration?

AR7
  • 366
  • 1
  • 16
  • Could you post the code you've tried and what errors you're getting? – Oin Aug 20 '20 at 08:38
  • I have added the code i was trying – AR7 Aug 20 '20 at 10:48
  • 1
    You're not patching mongo, you're just creating a new connection and returning it, but never using it. You need to patch where it's used. How does your non-test code use/create the db connection? – Oin Aug 20 '20 at 11:34
  • the non-test code is using pymongo for the connection to Mongodb – AR7 Aug 20 '20 at 11:42

0 Answers0