Skip to content

Commit

Permalink
fix: raise exception if doc before save is not found (#18796) (#18820)
Browse files Browse the repository at this point in the history
* 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

(cherry picked from commit a42ca7d)

Co-authored-by: Sagar Vora <sagar@resilient.tech>
  • Loading branch information
mergify[bot] and sagarvora committed Nov 11, 2022
1 parent a9a62af commit 7505a0d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
12 changes: 8 additions & 4 deletions frappe/model/document.py
Expand Up @@ -747,12 +747,13 @@ def check_if_latest(self):
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

Expand Down Expand Up @@ -1047,7 +1048,7 @@ def run_before_save_methods(self):

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
Expand All @@ -1058,6 +1059,9 @@ def load_doc_before_save(self):
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):
Expand Down
13 changes: 13 additions & 0 deletions frappe/tests/test_document.py
Expand Up @@ -411,6 +411,19 @@ def test_realtime_notify(self):
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"):
Expand Down

0 comments on commit 7505a0d

Please sign in to comment.