from ..interfaces import IURLPreview
from ..testing import PLONEINTRANET_MICROBLOG_INTEGRATION_TESTING
from .test_statusupdate import StatusUpdate
from importlib.resources import files
from unittest import mock
from urllib.request import urlopen

import unittest


def request_get(url, timeout=0):
    """Fetch a stream from local files.
    We don't need the full request.get stuff,
    we just want to open a local test file:
    urlopen is more than enough.

    See: http://stackoverflow.com/questions/10123929/python-requests-fetch-a-file-from-a-local-url  # noqa: E501
    """

    class FakeResponse:
        """This is a fake response"""

        def __init__(self, url):
            self.content = urlopen(url).read()

    return FakeResponse(url)


class URLPreviewTestCase(unittest.TestCase):
    layer = PLONEINTRANET_MICROBLOG_INTEGRATION_TESTING

    def setUp(self):
        self.portal = self.layer["portal"]

    @mock.patch("requests.get", request_get)
    def test_simple_site(self):
        su = StatusUpdate("foo bar")
        url = "file://%s" % (
            files("ploneintranet.microblog") / "tests/data/simple_site.html"
        )
        previews = IURLPreview(su).generate_preview(url)
        self.assertEqual(previews[0], "https://plone.org/logo@2x.png")

    @mock.patch("requests.get", request_get)
    def test_with_og_support(self):
        su = StatusUpdate("foo bar")
        url = "file://%s" % (
            files("ploneintranet.microblog") / "tests/data/og_support.html"
        )
        ogurl = "http://content.plone.com/plone/social/test.jpg"
        previews = IURLPreview(su).generate_preview(url)
        self.assertEqual(previews[0], ogurl)
