<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sugandh Mishra on Medium]]></title>
        <description><![CDATA[Stories by Sugandh Mishra on Medium]]></description>
        <link>https://medium.com/@sugandhmishra?source=rss-9c933fdee1b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5Xa1HltE2lwCgWGL.</url>
            <title>Stories by Sugandh Mishra on Medium</title>
            <link>https://medium.com/@sugandhmishra?source=rss-9c933fdee1b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:04:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sugandhmishra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unit Testing FastAPIs/MongoDB by mocking motor]]></title>
            <link>https://medium.com/@sugandhmishra/unit-testing-fastapis-mongodb-by-mocking-motor-361d20595a0e?source=rss-9c933fdee1b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/361d20595a0e</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[Sugandh Mishra]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 08:12:23 GMT</pubDate>
            <atom:updated>2023-01-02T08:24:36.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Glad that you are here! Today, we are going to learn how do we effectively test async Fast APIs with mongoDB. You can go to <a href="https://testdriven.io/blog/fastapi-mongo/">this article</a> to learn how to setup FastAPIs with MongoDB using <a href="https://motor.readthedocs.io/en/stable/">motor</a>.</p><h3>API Example:</h3><p>Let’s take an example from the <a href="https://testdriven.io/blog/fastapi-mongo/">article</a>, which builds an API to add student records of a college into the mongoDB.</p><pre>@router.post(&quot;/&quot;, response_description=&quot;Student data added into the database&quot;)<br>async def add_student_data(student: StudentSchema = Body(...)):<br>    student = jsonable_encoder(student)<br>    new_student = await add_student(student)<br>    return ResponseModel(new_student, &quot;Student added successfully.&quot;)</pre><h3>Mocking Motor</h3><p>Now, How do we test the above API <strong>POST /student</strong>? It’s little tricky as we don’t have a running database.</p><p><strong>Here, </strong><a href="https://pypi.org/project/mongomock-motor/"><strong>mongomock-motor </strong></a><strong>comes to rescue us. mongomock-motor is a best effort async built on mongomock library. In our example, We are going to unit-test with the pytest framework.</strong></p><p>Let’s install the below packages for setting up the test enviroment(Install other required packages mentioned in the <a href="https://testdriven.io/blog/fastapi-mongo/">article</a>).</p><pre>pip install mongomock-motor<br>pip install pytest</pre><p>Now, we would create a reusable pytest fixture to initialise motor mock, that can we used across the test cases. To learn more about pytest fixture read <a href="https://docs.pytest.org/en/6.2.x/fixture.html">this</a> article.</p><h3>Pytest Fixture:</h3><pre>import pytest<br>from fastapi.testclient import TestClient<br>from mongomock_motor import AsyncMongoMockClient<br>from beanie import init_beanie<br>from mongomock_motor import AsyncMongoMockClient<br>from app.core.schemas.student import Student<br><br><br>client = TestClient(app=app)<br><br>@pytest.fixture()<br>async def resource(<br>studentData<br>):<br>    app = AsyncMongoMockClient()<br><br>    await init_beanie(<br>        document_models=[Student], database=app.get_database(name=&quot;testdb&quot;)<br>    )</pre><p>Now, our fixture is ready, we can get started with writing a unit test case.<br>Let’s dig little bit in the pytest fixture.</p><p><strong>app:</strong> app is the instance of the application that is in testing purview here. You can find more about this in the <a href="https://testdriven.io/blog/fastapi-mongo/">article</a> I linked at the top.</p><p><strong>AysncMongoMockClient(): </strong>This is the heart of the testing infrastructure here, which mocks the mongo DB instance.</p><p><strong>init_beanie() : </strong><a href="https://github.com/roman-right/beanie">Beanie</a> — is an asynchronous Python object-document mapper (ODM) for MongoDB. Data models are based on <a href="https://pydantic-docs.helpmanual.io/">Pydantic</a>. init_beanie function initialises the mongo db document models.</p><h3>A unit test case code snippet:</h3><pre>@pytest.mark.asyncio<br>async def test_createStudent(<br>    resource, studentPayload<br>):<br>    await resource<br>    response = client.post(<br>        f&quot;{version}/student&quot;,<br>        json=studentPayload,<br>    )<br><br>    assert response.status_code == 201</pre><p>Let’s try to understand few variables that are used in the above test case.</p><p><strong>resource: </strong>resource is coming from the pytest fixture, which takes care of the all initialisation needed for the test cases.</p><p><strong>studentPayload: </strong>Below is the example for the studentPayload, that can be stored in a separate file and can be used a test data.</p><pre>{<br>     &quot;fullname&quot;: &quot;John Doe&quot;,<br>     &quot;email&quot;: &quot;jdoe@x.edu.ng&quot;,<br>     &quot;course_of_study&quot;: &quot;Water resources engineering&quot;,<br>     &quot;year&quot;: 2,<br>     &quot;gpa&quot;: &quot;3.0&quot;<br>  }</pre><h3>Running the test:</h3><p>One can easily run the above test with <a href="https://docs.pytest.org/en/7.1.x/getting-started.html">pytest</a> command.</p><h3>Conclusion</h3><p>In this article you have learnt how to unit test a CRUD app with FastAPI and MongoDB. As the next steps, you can work on creating a test setup for yourself and create a CI job that will run your unit tests and output the code coverage.</p><h3>References</h3><ul><li><a href="https://fastapi.tiangolo.com/tutorial/testing/">Testing - FastAPI</a></li><li><a href="https://testdriven.io/blog/fastapi-mongo/">Building a CRUD App with FastAPI and MongoDB</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361d20595a0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>