# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import jingrow
from jingrow.tests.utils import JingrowTestCase
from jingrow.utils.data import add_to_date, today


class TestDocumentLocks(JingrowTestCase):
	def test_locking(self):
		todo = jingrow.get_pg(dict(pagetype="ToDo", description="test")).insert()
		todo_1 = jingrow.get_pg("ToDo", todo.name)

		todo.lock()
		self.assertRaises(jingrow.PageLockedError, todo_1.lock)
		todo.unlock()

		todo_1.lock()
		self.assertRaises(jingrow.PageLockedError, todo.lock)
		todo_1.unlock()

	def test_operations_on_locked_documents(self):
		todo = jingrow.get_pg(dict(pagetype="ToDo", description="testing operations")).insert()
		todo.lock()

		with self.assertRaises(jingrow.PageLockedError):
			todo.description = "Random"
			todo.save()

		# Checking for persistant locks across all instances.
		pg = jingrow.get_pg("ToDo", todo.name)
		self.assertEqual(pg.is_locked, True)

		with self.assertRaises(jingrow.PageLockedError):
			pg.description = "Random"
			pg.save()

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

	def test_locks_auto_expiry(self):
		todo = jingrow.get_pg(dict(pagetype="ToDo", description=jingrow.generate_hash())).insert()
		todo.lock()

		self.assertRaises(jingrow.PageLockedError, todo.lock)

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