How to use serialize_headers method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_views.py

Source: test_views.py Github

copy
1from unittest.mock import call
2from unittest.mock import patch
3
4import pytest
5from django.core.exceptions import ImproperlyConfigured
6from django.test import RequestFactory
7from django.test import TestCase
8
9from django_renderpdf.views import PDFView
10from testapp import views
11
12factory = RequestFactory()
13
14
15class PromptDownloadTestCase(TestCase):
16    def test_prompt_download(self):
17        request = factory.get("/some_view")
18
19        response = views.PromptDownloadView.as_view()(request)
20        self.assertEqual(response.status_code, 200)
21        self.assertIn(
22            b"Content-Type: application/pdf", response.serialize_headers().splitlines()
23        )
24        self.assertIn(
25            b'Content-Disposition: attachment; filename="myfile.pdf"',
26            response.serialize_headers().splitlines(),
27        )
28        # Assert that response looks like a PDF
29        self.assertTrue(response.content.startswith(b"%PDF-1."))
30
31    def test_dont_prompt_download(self):
32        request = factory.get("/some_view")
33
34        response = views.NoPromptDownloadView.as_view()(request)
35        self.assertEqual(response.status_code, 200)
36        self.assertIn(
37            b"Content-Type: application/pdf", response.serialize_headers().splitlines()
38        )
39        self.assertNotIn(b"Content-Disposition:", response.serialize_headers())
40        # Assert that response looks like a PDF
41        self.assertTrue(response.content.startswith(b"%PDF-1."))
42
43
44class ForceHTMLTestCase(TestCase):
45    def test_force_html_allowed(self):
46        request = factory.get("/some_view?html=true")
47
48        response = views.AllowForceHtmlView.as_view()(request)
49        self.assertEqual(response.status_code, 200)
50        self.assertEqual(b"Hi!\n", response.content)
51        self.assertIn(
52            b"Content-Type: text/html; charset=utf-8",
53            response.serialize_headers().splitlines(),
54        )
55
56    def test_no_force_html_allowed(self):
57        request = factory.get("/some_view")
58
59        response = views.AllowForceHtmlView.as_view()(request)
60        self.assertEqual(response.status_code, 200)
61        self.assertIn(
62            b"Content-Type: application/pdf", response.serialize_headers().splitlines()
63        )
64        # Assert that response looks like a PDF
65        self.assertTrue(response.content.startswith(b"%PDF-1."))
66
67    def test_force_html_disallowed(self):
68        request = factory.get("/some_view?html=true")
69
70        response = views.DisallowForceHtmlView.as_view()(request)
71        self.assertEqual(response.status_code, 200)
72        self.assertIn(
73            b"Content-Type: application/pdf", response.serialize_headers().splitlines()
74        )
75        # Assert that response looks like a PDF
76        self.assertTrue(response.content.startswith(b"%PDF-1."))
77
78    def test_no_force_html_disallowed(self):
79        request = factory.get("/some_view")
80
81        response = views.DisallowForceHtmlView.as_view()(request)
82        self.assertEqual(response.status_code, 200)
83        self.assertIn(
84            b"Content-Type: application/pdf", response.serialize_headers().splitlines()
85        )
86        # Assert that response looks like a PDF
87        self.assertTrue(response.content.startswith(b"%PDF-1."))
88
89
90class CustomUrlFetcherTestCase(TestCase):
91    pass  # TODO
92
93
94class StaticFileResolutionTestCase(TestCase):
95    def test_url_fetcher_used(self):
96        request = factory.get("/some_view")
97
98        with patch(
99            "django_renderpdf.helpers.django_url_fetcher",
100            return_value={
101                "string": "html { margin: 0; }",
102                "mime_type": "text/css",
103            },
104            spec=True,
105        ) as fetcher:
106            response = views.TemplateWithStaticFileView.as_view()(request)
107
108        self.assertEqual(response.status_code, 200)
109        self.assertEqual(fetcher.call_count, 1)
110        self.assertEqual(
111            fetcher.call_args,
112            call("/static/path/not/relevant.css"),
113        )
114
115
116def test_view_with_no_template(rf):
117    request = factory.get("/test")
118
119    with pytest.raises(
120        ImproperlyConfigured,
121        match=r"requires either a definition of.*template_name.*get_template_names",
122    ):
123        views.NoTemplateDefinedView.as_view()(request)
124
125
126def test_view_with_missing_download_name(rf):
127    request = factory.get("/test")
128
129    with pytest.raises(
130        ImproperlyConfigured,
131        match=r"requires.*download_name",
132    ):
133        views.PromptWithMissingDownloadNameView.as_view()(request)
134
135
136def test_view_with_multiple_template_names(rf):
137    class TestView(PDFView):
138        def get_template_names(self):
139            return [
140                "test_template.html",
141                "test_template.html",
142            ]
143
144    request = factory.get("/test")
145    response = TestView.as_view()(request)
146
147    assert response.status_code == 200
148
Full Screen

tests.py

Source: tests.py Github

copy
1from __future__ import absolute_import
2
3from six.moves import reload_module
4
5from django.conf import settings
6from django.http import HttpResponseNotFound
7from django.test import TestCase
8from django.test.client import RequestFactory
9from django.contrib.sites.shortcuts import get_current_site
10from django.urls import clear_url_caches
11
12from robustredirects.middleware import RedirectMiddleware
13from robustredirects.models import Redirect
14
15
16class TestRedirectMiddleWare(TestCase):
17    def setUp(self):
18        super(TestRedirectMiddleWare, self).setUp()
19        # Every test needs access to the request factory.
20        self.factory = RequestFactory()
21        # tests should start with an empty url cache
22        clear_url_caches()
23        settings.ROBUST_REDIRECTS_IGNORED_URL_PATHS = None
24
25    @staticmethod
26    def run_redirect(request):
27        from robustredirects import dynamic_urls
28
29        reload_module(dynamic_urls)
30        middleware = RedirectMiddleware()
31        response = HttpResponseNotFound()
32        new_response = middleware.process_response(request, response)
33        return new_response
34
35    def test_redirect_request_permanent(self):
36        # Create a redirect
37        request = self.factory.get('/test/123/')
38
39        redirect = Redirect(from_url=r'test/(?P<pk>\d+)/', to_url=r'somethingelse/(?P<pk>\d+)/',
40                            site=get_current_site(request), uses_regex=True)
41
42        redirect.save()
43        new_response = self.run_redirect(request)
44
45        self.assertEqual(new_response.status_code, 301)
46        self.assertIn(b"somethingelse", new_response.serialize_headers())
47
48    def test_redirect_request_gone(self):
49        # Create a redirect
50        request = self.factory.get('/test/123/')
51
52        redirect = Redirect(from_url=r'test/(?P<pk>\d+)/', to_url='',
53                            site=get_current_site(request), uses_regex=True)
54
55        redirect.save()
56        new_response = self.run_redirect(request)
57
58        self.assertEqual(new_response.status_code, 410)
59
60    def test_redirect_request_temporary(self):
61        # Create a redirect
62        request = self.factory.get('/test/123/')
63
64        redirect = Redirect(from_url=r'test/(?P<pk>\d+)/', to_url=r'somethingelse/(?P<pk>\d+)/',
65                            site=get_current_site(request), http_status=302, uses_regex=True)
66
67        redirect.save()
68        new_response = self.run_redirect(request)
69
70        self.assertEqual(new_response.status_code, 302)
71        self.assertIn(b"somethingelse", new_response.serialize_headers())
72
73    def test_redirect_request_partial_temporary(self):
74        # Create a redirect
75        request = self.factory.get('/test/123/')
76
77        redirect = Redirect(from_url='/test/', to_url='/partialtest/', is_partial=True,
78                            site=get_current_site(request), http_status=302)
79
80        redirect.save()
81        new_response = self.run_redirect(request)
82
83        self.assertEqual(new_response.status_code, 302)
84        self.assertIn(b"partialtest", new_response.serialize_headers())
85
86    def test_redirect_request_partial_permanent(self):
87        # Create a redirect
88        request = self.factory.get('/test/123/')
89
90        redirect = Redirect(from_url='/test/', to_url='/partialtest/', is_partial=True,
91                            site=get_current_site(request), http_status=301)
92
93        redirect.save()
94        new_response = self.run_redirect(request)
95
96        self.assertEqual(new_response.status_code, 301)
97        self.assertIn(b"partialtest", new_response.serialize_headers())
98
99    def test_redirect_request_two_partial_entries_permanent(self):
100        # Create a redirect
101        old_route = '/invalidroot/partialtest'
102        redirected_route = '/test/partialtest'
103        request = self.factory.get(old_route)
104
105        redirect = Redirect(from_url='/invalidroot', to_url=redirected_route, is_partial=True,
106                            site=get_current_site(request), http_status=301)
107
108        redirect.save()
109        redirect2 = Redirect(from_url=old_route, to_url=redirected_route, is_partial=True,
110                             site=get_current_site(request), http_status=301)
111
112        redirect2.save()
113        new_response = self.run_redirect(request)
114
115        self.assertEqual(new_response.status_code, 301)
116        self.assertEqual(new_response.url, redirected_route)
117
118    def test_redirect_request_partial_gone(self):
119        # Create a redirect
120        request = self.factory.get('/test/123/')
121
122        redirect = Redirect(from_url='/test/', to_url='', is_partial=True,
123                            site=get_current_site(request), http_status=301)
124
125        redirect.save()
126        new_response = self.run_redirect(request)
127
128        self.assertEqual(new_response.status_code, 410)
129
130    def test_redirect_request_partial_prepend_slash(self):
131        # Create a redirect
132        request = self.factory.get('/test/123/')
133
134        redirect = Redirect(from_url='/test/', to_url='partialtest/', is_partial=True,
135                            site=get_current_site(request), http_status=302)
136
137        redirect.save()
138        new_response = self.run_redirect(request)
139
140        self.assertEqual(new_response.status_code, 302)
141        self.assertIn(b"/partialtest/123/", new_response.serialize_headers())
142
143    def test_redirect_exclusion(self):
144        # Create a redirect
145        request = self.factory.get('/api/test/123/')
146
147        settings.ROBUST_REDIRECTS_IGNORED_PREFIXES = '/api'
148
149        redirect = Redirect(from_url='/test/', to_url='partialtest/', is_partial=True,
150                            site=get_current_site(request), http_status=302)
151
152        redirect.save()
153        redirect2 = Redirect(from_url=r'/api/test/(?P<pk>\d+)/', to_url=r'somethingelse/(?P<pk>\d+)/',
154                             site=get_current_site(request), http_status=302, uses_regex=True)
155
156        redirect2.save()
157        new_response = self.run_redirect(request)
158
159        # no redirect should happen
160        self.assertEqual(new_response.status_code, 404)
161
Full Screen

test_folderviews_views.py

Source: test_folderviews_views.py Github

copy
1import pytest
2import os
3from django.conf import settings
4from django.conf import urls
5from django.test.utils import override_settings
6from unittest import mock
7current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
8folder_name = os.path.join(current_dir, 'fileserve')
9FOLDERVIEW_FOLDERS = [folder_name]
10# setattr(settings, 'FOLDERVIEW_FOLDERS', [folder_name])
11
12@pytest.fixture
13def index():
14    global folder_name
15    file_name = os.path.join(folder_name, 'index.html')
16    os.mkdir(folder_name)
17    with open(file_name, 'w') as f:
18        f.write('Hello Folder View')
19    yield file_name
20    os.remove(file_name)
21    os.rmdir(folder_name)
22
23
24@pytest.fixture
25def favicon():
26    global folder_name, current_dir
27    file_name = os.path.join(folder_name, 'favicon.ico')
28    favicon_file = os.path.join(current_dir, 'tests/favicon.ico')
29    os.mkdir(folder_name)
30    os.system('cp {} {}'.format(favicon_file, file_name))
31    yield file_name
32    os.remove(file_name)
33    os.rmdir(folder_name)
34    
35
36class TestViews:
37    
38    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', FOLDERVIEW_FOLDERS)
39    def test_can_serve_test_file(self, index, client):
40        location = index.split(os.path.sep)[-1]
41        folder = index.split(os.path.sep)[:-1]
42        resp = client.get('/{}'.format(location))
43        assert resp.status_code == 200
44        assert resp.getvalue() == b'Hello Folder View'
45    
46    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', FOLDERVIEW_FOLDERS)
47    def test_can_serve_index_file(self, index, client):
48        location = index.split(os.path.sep)[-1]
49        folder = index.split(os.path.sep)[:-1]
50        resp = client.get('/')
51        assert resp.status_code == 200
52        assert resp.getvalue() == b'Hello Folder View'
53        
54    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', FOLDERVIEW_FOLDERS)
55    def test_404_on_unknown_file(self, client):
56        resp = client.get('/hello.test')
57        assert resp.status_code == 404
58        assert b'The requested URL /hello.test was not found on this server.' \
59                in resp.content
60
61    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', [])
62    def test_404_on_unknown_folder(self, index, client):
63        resp = client.get('/')
64        assert resp.status_code == 404
65        assert b'The requested URL / was not found on this server.' \
66                in resp.content
67
68    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', FOLDERVIEW_FOLDERS)
69    def test_can_serve_favicon(self, favicon, client):
70        location = favicon.split(os.path.sep)[-1]
71        folder = favicon.split(os.path.sep)[:-1]
72        resp = client.get('/{}'.format(location))
73        assert resp.status_code == 200
74
75    @mock.patch('mimetypes.guess_type')
76    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', FOLDERVIEW_FOLDERS)
77    def test_can_serve_favicon(self, mock_guess_type, favicon, client):
78        mock_guess_type.return_value = ('image/vnd.microsoft.icon', 'utf-8')
79        location = favicon.split(os.path.sep)[-1]
80        folder = favicon.split(os.path.sep)[:-1]
81        resp = client.get('/{}'.format(location))
82        assert resp.status_code == 200
83        assert b'Content-Type: image/vnd.microsoft.icon' \
84                in resp.serialize_headers()
85        assert b'Content-Encoding: utf-8' in resp.serialize_headers()
86        assert b'Content-Length: 5430' in resp.serialize_headers()
87
88
89    @mock.patch('django.views.static.was_modified_since')
90    @mock.patch.object(settings, 'FOLDERVIEW_FOLDERS', FOLDERVIEW_FOLDERS)
91    def test_can_serve_favicon_not_modified(self, mock_mod, favicon, client):
92        mock_mod.return_value = False
93        location = favicon.split(os.path.sep)[-1]
94        folder = favicon.split(os.path.sep)[:-1]
95        resp = client.get('/{}'.format(location))
96        assert resp.status_code == 304
97
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)