import os
from unittest import mock
from django.utils.timezone import datetime, timedelta
from django.core.files.base import ContentFile
from django.core.exceptions import ValidationError
from django.conf import settings
from test_plus.test import TestCase
from ..models import Chart


class TestChart(TestCase):

    def setUp(self):
        self.c = Chart()

    def test_saving_and_retrieving_file(self):
        content = ContentFile('1, 2\n3, 4\n5, 6\n')
        self.c.save()  # necessary to get instance.pk
        filename = settings.MEDIA_ROOT + '/charts/'+str(self.c.pk).zfill(5)+'.txt'
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        # First create a file to test OverwriteStorage()
        with open(filename, 'w') as f:
            f.write('hello')
        # Overwrite the file using Chart
        self.c.filename.save('', content)  # The filename is generated in the model class
        with open(filename, 'r') as f:
            r = f.read()
        self.assertEqual(r[:1], '1')

    def test__str__(self):
        self.c.name = "c1"
        self.assertEqual(self.c.__str__(), 'c1')

    def test_pub_date(self):
        testtime = datetime.now() - timedelta(days=60)
        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = testtime
            cmock = Chart()
            cmock.save()
        self.assertEqual(cmock.pub_date, testtime)

    def test_non_valid_units(self):
        self.c.xunit = 'rr'
        self.assertRaises(ValidationError, self.c.save())
