[ Get actual DB state of Mongoengine for unit testing ]
I have a unit test that tests if a comment to a post is properly added to the MongoDB database. There is a collection Post
that has a ListField
containing strings called comments
. Post
is a class inheriting from MongoEngine's Document
, it has custom methods create
and add_comment
.
class TestNotSaving(TestCase):
def setUp(self):
Post.create(text='sample post')
def tearDown(self):
# Post.drop_collection()
pass
def test_comments(self):
comment = 'This is a sample comment.'
post = Post.objects[0]
post.add_comment(comment)
# post.save()
self.assertEqual(post.comments[0], comment)
The problem is that if i don't save the document to the DB using save
method, the MongoEngine still behaves as if the document is created and the comment is stored. I, however, want to write a test that fails if you don't properly save the document in the code. How can i refresh the state of a MongoEngine document?
Answer 1
This can't really be achieved without trying to load the data from the database to ensure it was saved.
MongoEngine in save
does check for the existence of an _id
or self._created
but that's so it knows to try and do an insert or upsert. But only doing the save and speaking to the database will let you know that it was successful and any unique indexes weren't contravened.
However, you can persist data to the database using insert
and / or update
(which is more explicit than using save
which under the covers uses them).