# Copyright (c) 2020, InfluxFramework LLC
# License: MIT. See LICENSE

import influxframework
import influxframework.monitor
from influxframework.monitor import MONITOR_REDIS_KEY
from influxframework.tests.utils import InfluxFrameworkTestCase
from influxframework.utils import set_request
from influxframework.utils.response import build_response


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

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

		influxframework.monitor.start()
		influxframework.monitor.stop(response)

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

		log = influxframework.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):
		influxframework.utils.background_jobs.execute_job(
			influxframework.local.site, "influxframework.ping", None, None, {}, is_async=False
		)

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

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

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

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

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

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