fix: raise exception if doc before save is not found (#18796)

* fix: raise exception if doc before save is not found

* test: ensure error is raised when trying to save new doc using `doc.save()`

* chore: add comment explaining condition

* test: clearer name and docstring
This commit is contained in:
Sagar Vora 2022-11-09 14:15:41 +00:00 committed by GitHub
parent 1dd719b123
commit a42ca7d8c1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 4 deletions

View file

@ -744,12 +744,13 @@ class Document(BaseDocument):
Will also validate document transitions (Save > Submit > Cancel) calling
`self.check_docstatus_transition`."""
self.load_doc_before_save()
self.load_doc_before_save(raise_exception=True)
self._action = "save"
previous = self.get_doc_before_save()
previous = self._doc_before_save
if not previous or self.meta.get("is_virtual"):
# previous is None for new document insert
if not previous:
self.check_docstatus_transition(0)
return
@ -1048,7 +1049,7 @@ class Document(BaseDocument):
self.set_title_field()
def load_doc_before_save(self):
def load_doc_before_save(self, *, raise_exception: bool = False):
"""load existing document from db before saving"""
self._doc_before_save = None
@ -1059,6 +1060,9 @@ class Document(BaseDocument):
try:
self._doc_before_save = frappe.get_doc(self.doctype, self.name, for_update=True)
except frappe.DoesNotExistError:
if raise_exception:
raise
frappe.clear_last_message()
def run_post_save_methods(self):

View file

@ -411,6 +411,19 @@ class TestDocument(FrappeTestCase):
todo.save()
self.assertEqual(todo.notify_update.call_count, 1)
def test_error_on_saving_new_doc_with_name(self):
"""Trying to save a new doc with name should raise DoesNotExistError"""
doc = frappe.get_doc(
{
"doctype": "ToDo",
"description": "this should raise frappe.DoesNotExistError",
"name": "lets-trick-doc-save",
}
)
self.assertRaises(frappe.DoesNotExistError, doc.save)
class TestDocumentWebView(FrappeTestCase):
def get(self, path, user="Guest"):