# Copyright (c) 2015, XhiveFramework Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import xhiveframework
from xhiveframework.tests.utils import XhiveFrameworkTestCase
from xhiveframework.utils.data import add_to_date, today


class TestDocumentLocks(XhiveFrameworkTestCase):
	def test_locking(self):
		todo = xhiveframework.get_doc(dict(doctype="ToDo", description="test")).insert()
		todo_1 = xhiveframework.get_doc("ToDo", todo.name)

		todo.lock()
		self.assertRaises(xhiveframework.DocumentLockedError, todo_1.lock)
		todo.unlock()

		todo_1.lock()
		self.assertRaises(xhiveframework.DocumentLockedError, todo.lock)
		todo_1.unlock()

	def test_operations_on_locked_documents(self):
		todo = xhiveframework.get_doc(dict(doctype="ToDo", description="testing operations")).insert()
		todo.lock()

		with self.assertRaises(xhiveframework.DocumentLockedError):
			todo.description = "Random"
			todo.save()

		# Checking for persistant locks across all instances.
		doc = xhiveframework.get_doc("ToDo", todo.name)
		self.assertEqual(doc.is_locked, True)

		with self.assertRaises(xhiveframework.DocumentLockedError):
			doc.description = "Random"
			doc.save()

		doc.unlock()
		self.assertEqual(doc.is_locked, False)
		self.assertEqual(todo.is_locked, False)

	def test_locks_auto_expiry(self):
		todo = xhiveframework.get_doc(dict(doctype="ToDo", description=xhiveframework.generate_hash())).insert()
		todo.lock()

		self.assertRaises(xhiveframework.DocumentLockedError, todo.lock)

		with self.freeze_time(add_to_date(today(), days=3)):
			todo.lock()
