from project.common.tests import BaseTestCase
from project.home.models import HomePage
from .models import BlogIndexPage, BlogPage


class BlogIndexPageTestCase(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.create_model(BlogIndexPage, {
            'title': 'The blog',
            'body': '<p>Some test content</p>',
        })
        self.page = BlogIndexPage.objects.get(title='The blog')

    def test_create_child(self):
        create_response = self.create_model(BlogPage, {
            'title': 'Test blog post',
            'body': '<p>Blogging stuff</p>',
        }, parent=self.page)
        self.assertEqual(create_response.status_code, 302)
        self.assertTrue(BlogPage.objects.filter(title='Test blog post').exists())

    def test_create_invalid_child(self):
        create_response = self.create_model(HomePage, {
            'title': 'A home page',
            'body': '<p>Some home page</p>',
        }, parent=self.page)
        self.assertEqual(create_response.status_code, 403)
        self.assertFalse(HomePage.objects.filter(title='A home page').exists())

    def test_context(self):
        for i in range(3):
            create_response = self.create_model(BlogPage, {
                'title': 'Test blog post {}'.format(i),
                'body': '<p>Blogging stuff for post {}</p>'.format(i),
            }, parent=self.page)
            self.assertEqual(create_response.status_code, 302)
        create_response = self.create_model(BlogPage, {
            'title': 'Test blog post',
            'body': '<p>Blogging stuff for post</p>',
        })
        self.assertEqual(create_response.status_code, 302)
        self.assertEqual(BlogPage.objects.count(), 4)
        response = self.client.get(self.page.url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context_data['blogs'].count(), 3)
        self.assertFalse(response.context_data['blogs'].filter(title='Test blog post').exists())

    def test_page(self):
        response = self.client.get(self.page.url)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, str(self.page.body))


class BlogPageTestCase(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.create_model(BlogPage, {
            'title': 'Some blog page',
            'body': '<p>Some test content</p>',
        })
        self.page = BlogPage.objects.get(title='Some blog page')

    def test_page(self):
        response = self.client.get(self.page.url)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, str(self.page.body))
