from ploneintranet.news.subscribers.modified import fix_news_description
from unittest import mock

import unittest

BODY_TEXT_80 = (
    "This is a body text that is exactly eighty characters long, so that we can test."
)


def mock_make_description(body_text):
    return " ".join(body_text[:40].split(" ")[:-1] + ["..."])


class MockText:
    def __init__(self, text):
        self.output = text
        self.raw = text


class MockObject:
    def __init__(self, description, text):
        self.description = description
        self.text = MockText(text) if text else None


@mock.patch(
    "ploneintranet.news.subscribers.modified.make_description",
    new_callable=lambda: mock_make_description,
)
class TestFixNewsDescription(unittest.TestCase):
    def test_description_and_text(self, mock_method):
        obj = MockObject("This is the description", BODY_TEXT_80)
        fix_news_description(obj)
        self.assertTrue(hasattr(obj, "_teaser"))
        self.assertEqual(obj.description, "This is the description")
        self.assertNotEqual(obj.description, obj._teaser)

        obj.description = "Now I've changed the description"
        fix_news_description(obj)
        self.assertTrue(hasattr(obj, "_teaser"))
        self.assertEqual(obj.description, "Now I've changed the description")
        self.assertNotEqual(obj.description, obj._teaser)

    def test_empty_description(self, mock_method):
        obj = MockObject("", BODY_TEXT_80)
        fix_news_description(obj)
        self.assertTrue(hasattr(obj, "_teaser"))
        self.assertEqual(obj.description, obj._teaser)

        obj.description = "Now I've changed the description"
        fix_news_description(obj)
        self.assertTrue(hasattr(obj, "_teaser"))
        self.assertEqual(obj.description, "Now I've changed the description")
        self.assertNotEqual(obj.description, obj._teaser)

    def test_empty_text(self, mock_method):
        obj = MockObject("I'm not bothering with the body text", "")
        fix_news_description(obj)
        self.assertTrue(hasattr(obj, "_teaser"))
        self.assertEqual(obj.description, "I'm not bothering with the body text")
        self.assertNotEqual(obj.description, obj._teaser)

    def test_empty_text_and_description(self, mock_method):
        obj = MockObject("", "")
        fix_news_description(obj)
        self.assertTrue(hasattr(obj, "_teaser"))
        self.assertEqual(obj.description, "")
