0
votes

I am newbie... I am trying to mock the pymongo insert_one method to mongodb, and test that the function catches it and I get the correct error message back when it fails to connect. I've managed to mock the success case, but struggling to piece something together in this case. Any advice would be great.

def add_book(data):
    formatted_book = format_book(data)
    validBookChecked = check_valid(formatted_book)
    if validBookChecked == "author":
        return ("Author field must contain text characters", 400)
    elif validBookChecked == "incomplete":
        return ("All fields are mandatory", 400)
    else:
        try:
            books = db.books
            result = books.insert_one(formatted_book)
            print(formatted_book)
            return ({"message": "Book successfully added"}, 201)
        except:
            return ({"message": "Could not connect to db"}, 500)

Here is the code for the passing success case:

@patch("pymongo.collection.Collection.insert_one")
class TestAddBook(unittest.TestCase):
    def test_add_book(self, mock_insert_one):
        mock_insert_one.return_value = {
            "title": "Encyclopaedia Americana ",
            "author": "Jane Austen",
            "synopsis": "The novel follows the character development of Elizabeth Bennet, the dynamic protagonist of the book who learns about the repercussions of hasty judgments and comes to appreciate the difference between superficial goodness and actual goodness.",
            'genre': 'Horror'
        }

        self.assertEqual(
            add_book(
                {
                    "title": "Encyclopaedia Americana ",
                    "author": "Jane Austen",
                    "synopsis": "The novel follows the character development of Elizabeth Bennet, the dynamic protagonist of the book who learns about the repercussions of hasty judgments and comes to appreciate the difference between superficial goodness and actual goodness.",
                    'genre': 'Horror'
                }
            ),
            tuple(
                (
                    {
                        'message': 'Book successfully added'
                    },
                    201
                )
            )
        )