# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
from unittest.mock import patch

from ldap3.core.exceptions import LDAPException, LDAPInappropriateAuthenticationResult

import jingrow
from jingrow.tests.utils import JingrowTestCase
from jingrow.utils.error import _is_ldap_exception, guess_exception_source

# test_records = jingrow.get_test_records('Error Log')


class TestErrorLog(JingrowTestCase):
	def test_error_log(self):
		"""let's do an error log on error log?"""
		pg = jingrow.new_pg("Error Log")
		error = pg.log_error("This is an error")
		self.assertEqual(error.pagetype, "Error Log")

	def test_ldap_exceptions(self):
		exc = [LDAPException, LDAPInappropriateAuthenticationResult]

		for e in exc:
			self.assertTrue(_is_ldap_exception(e()))


_RAW_EXC = """
   File "apps/jingrow/jingrow/model/document.py", line 1284, in runner
     add_to_return_value(self, fn(self, *args, **kwargs))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^
   File "apps/jingrow/jingrow/model/document.py", line 933, in fn
     return method_object(*args, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "apps/jerp/jerp/selling/pagetype/sales_order/sales_order.py", line 58, in onload
     raise Exception("what")
 Exception: what
"""

_THROW_EXC = """
   File "apps/jingrow/jingrow/model/document.py", line 933, in fn
     return method_object(*args, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "apps/jerp/jerp/selling/pagetype/sales_order/sales_order.py", line 58, in onload
     jingrow.throw("what")
   File "apps/jingrow/jingrow/__init__.py", line 550, in throw
     msgprint(
   File "apps/jingrow/jingrow/__init__.py", line 518, in msgprint
     _raise_exception()
   File "apps/jingrow/jingrow/__init__.py", line 467, in _raise_exception
     raise raise_exception(msg)
 jingrow.exceptions.ValidationError: what
"""

TEST_EXCEPTIONS = (
	(
		"jerp (app)",
		_RAW_EXC,
	),
	(
		"jerp (app)",
		_THROW_EXC,
	),
)


class TestExceptionSourceGuessing(JingrowTestCase):
	@patch.object(jingrow, "get_installed_apps", return_value=["jingrow", "jerp", "3pa"])
	def test_exc_source_guessing(self, _installed_apps):
		for source, exc in TEST_EXCEPTIONS:
			result = guess_exception_source(exc)
			self.assertEqual(result, source)
