Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Commit 68fb9a5

Browse files
committed
Catch error if throw_on_exists flag is False for document create
1 parent cb9ae6c commit 68fb9a5

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/cloudant/database.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,10 +157,15 @@ def create_document(self, data, throw_on_exists=False):
157157
doc = DesignDocument(self, docid)
158158
else:
159159
doc = Document(self, docid)
160-
if throw_on_exists and doc.exists():
161-
raise CloudantDatabaseException(409, docid)
162160
doc.update(data)
163-
doc.create()
161+
try:
162+
doc.create()
163+
except HTTPError as error:
164+
if error.response.status_code == 409:
165+
if throw_on_exists:
166+
raise CloudantDatabaseException(409, docid)
167+
else:
168+
raise
164169
super(CouchDatabase, self).__setitem__(doc['_id'], doc)
165170
return doc
166171

tests/unit/database_tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,17 @@ def test_create_document_with_id(self):
267267
'Document with id julia06 already exists.'
268268
)
269269

270+
def test_create_document_that_already_exists(self):
271+
"""
272+
Test creating a document that already exists
273+
"""
274+
data = {'_id': 'julia'}
275+
doc = self.db.create_document(data)
276+
self.assertEqual(self.db['julia'], doc)
277+
self.assertTrue(doc['_rev'].startswith('1-'))
278+
# attempt to recreate document
279+
self.db.create_document(data, throw_on_exists=False)
280+
270281
def test_create_document_without_id(self):
271282
"""
272283
Test creating a document without supplying a document id

0 commit comments

Comments
 (0)