# Copyright (c) 2020, Xhive Global Ltd. and Contributors
# License: MIT. See LICENSE

import xhiveframework
import xhiveframework.monitor
from xhiveframework.monitor import MONITOR_REDIS_KEY
from xhiveframework.tests.utils import XhiveFrameworkTestCase
from xhiveframework.utils import set_request
from xhiveframework.utils.response import build_response


class TestMonitor(XhiveFrameworkTestCase):
	def setUp(self):
		xhiveframework.conf.monitor = 1
		xhiveframework.cache().delete_value(MONITOR_REDIS_KEY)

	def test_enable_monitor(self):
		set_request(method="GET", path="/api/method/xhiveframework.ping")
		response = build_response("json")

		xhiveframework.monitor.start()
		xhiveframework.monitor.stop(response)

		logs = xhiveframework.cache().lrange(MONITOR_REDIS_KEY, 0, -1)
		self.assertEqual(len(logs), 1)

		log = xhiveframework.parse_json(logs[0].decode())
		self.assertTrue(log.duration)
		self.assertTrue(log.site)
		self.assertTrue(log.timestamp)
		self.assertTrue(log.uuid)
		self.assertTrue(log.request)
		self.assertEqual(log.transaction_type, "request")
		self.assertEqual(log.request["method"], "GET")

	def test_job(self):
		xhiveframework.utils.background_jobs.execute_job(
			xhiveframework.local.site, "xhiveframework.ping", None, None, {}, is_async=False
		)

		logs = xhiveframework.cache().lrange(MONITOR_REDIS_KEY, 0, -1)
		self.assertEqual(len(logs), 1)
		log = xhiveframework.parse_json(logs[0].decode())
		self.assertEqual(log.transaction_type, "job")
		self.assertTrue(log.job)
		self.assertEqual(log.job["method"], "xhiveframework.ping")
		self.assertEqual(log.job["scheduled"], False)
		self.assertEqual(log.job["wait"], 0)

	def test_flush(self):
		set_request(method="GET", path="/api/method/xhiveframework.ping")
		response = build_response("json")
		xhiveframework.monitor.start()
		xhiveframework.monitor.stop(response)

		open(xhiveframework.monitor.log_file(), "w").close()
		xhiveframework.monitor.flush()

		with open(xhiveframework.monitor.log_file()) as f:
			logs = f.readlines()

		self.assertEqual(len(logs), 1)
		log = xhiveframework.parse_json(logs[0])
		self.assertEqual(log.transaction_type, "request")

	def tearDown(self):
		xhiveframework.conf.monitor = 0
		xhiveframework.cache().delete_value(MONITOR_REDIS_KEY)
