# -*- coding: utf-8 -*-
import re

from django.test import TestCase

from models import User, Reservation


class IndexTestCase(TestCase):
    def setUp(self):
        """
        初始化部分数据

        """
        super(IndexTestCase, self).setUp()
        u1 = User.objects.create(name=u'张小敏', gender=u'M')
        u2 = User.objects.create(name=u'李丽', gender=u'F')
        u3 = User.objects.create(name=u'吴美丽', gender=u'F')

        u1.save()
        u2.save()
        u3.save()
        # 5个付款的预约
        Reservation.objects.create(amount=100, paid=True, user=u1).save()
        Reservation.objects.create(amount=100, paid=True, user=u1).save()
        Reservation.objects.create(amount=100, paid=True, user=u2).save()
        Reservation.objects.create(amount=100, paid=True, user=u2).save()
        Reservation.objects.create(amount=100, paid=True, user=u3).save()
        # 3个取消的预约
        Reservation.objects.create(amount=100, cancelled=True, user=u1).save()
        Reservation.objects.create(amount=100, cancelled=True, user=u2).save()
        Reservation.objects.create(amount=100, cancelled=True, user=u3).save()
        # 2个中止的预约
        Reservation.objects.create(amount=100, suspended=True, user=u1).save()
        Reservation.objects.create(amount=100, suspended=True, user=u3).save()


    def test_tree_list(self):
        """
        测试页面有3个例表，分别是 付款的预约，取消的预约，中止的预约

        """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
        re_h1 = re.compile(r"<h1>([^<]*)</h1>")
        h1_list = re_h1.findall(response.content.decode('utf-8'))
        self.assertEqual(len(h1_list), 3)
        self.assertIn(u'付款的预约', h1_list)
        self.assertIn(u'取消的预约', h1_list)
        self.assertIn(u'中止的预约', h1_list)

    def test_list_detail(self):
        """
        确认“付款的预约”列表中有5个预约, “取消的预约”列表中有3个预约，“中止的预约”列表有2个预约。
        """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
        data = response.context['data']
        self.assertEqual(len(data.get('paid')), 5)
        self.assertEqual(len(data.get('cancelled')), 3)
        self.assertEqual(len(data.get('suspended')), 2)

    def test_total_amount(self):
        """
        确认付款的预约的总金额是正确的。
        """
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
        data = response.context['data']
        test_paid_total = sum([p.amount for p in data['paid']])
        self.assertEqual(test_paid_total, data['paid_total'])