from urllib.parse import urljoin
from cubicweb.devtools import BASE_URL

from cubicweb_web.devtools.testlib import PyramidWebCWTC
from cubicweb_web.view import View
from cubicweb_web._exceptions import Redirect


class Redirector(View):
    __regid__ = "redirector"

    def call(self, rset=None):
        self._cw.set_header("Cache-Control", "no-cache")
        raise Redirect("http://example.org")


class PyramidCoreTest(PyramidWebCWTC):
    anonymous_allowed = True

    def test_cw_to_pyramid_copy_headers_on_redirect(self):
        self.vreg.register(Redirector)
        try:
            res = self.webapp.get(
                urljoin(BASE_URL, "?vid=redirector"), expect_errors=True
            )
            self.assertEqual(res.status_int, 303)
            self.assertEqual(res.headers["Cache-Control"], "no-cache")
        finally:
            self.vreg.unregister(Redirector)


if __name__ == "__main__":
    from unittest import main

    main()
