# Copyright (c) 2019, XhiveFramework Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE

import xhiveframework
from xhiveframework.desk.reportview import export_query
from xhiveframework.tests.utils import XhiveFrameworkTestCase


class TestReportview(XhiveFrameworkTestCase):
	def test_csv(self):
		from csv import QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC, DictReader
		from io import StringIO

		xhiveframework.local.form_dict = xhiveframework._dict(
			doctype="DocType",
			file_format_type="CSV",
			fields=("name", "module", "issingle"),
			filters={"issingle": 1, "module": "Core"},
		)

		for delimiter in (",", ";", "\t", "|"):
			xhiveframework.local.form_dict.csv_delimiter = delimiter
			for quoting in (QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC):
				xhiveframework.local.form_dict.csv_quoting = quoting

				export_query()

				self.assertTrue(xhiveframework.response["filename"].endswith(".csv"))
				self.assertEqual(xhiveframework.response["type"], "binary")
				with StringIO(xhiveframework.response["filecontent"].decode("utf-8")) as result:
					reader = DictReader(result, delimiter=delimiter, quoting=quoting)
					for row in reader:
						self.assertEqual(int(row["Is Single"]), 1)
						self.assertEqual(row["Module"], "Core")
