1#! /usr/bin/env python
2# -*- coding: utf-8 -*-
3# vi:ts=4:et
4
5from . import localhost
6import pytest
7import pycurl
8import unittest
9
10from . import appmanager
11from . import util
12
13setup_module, teardown_module = appmanager.setup(('app', 8380))
14
15# NB: HTTP RFC requires headers to be latin1 encoded, which we violate.
16# See the comments under /header_utf8 route in app.py.
17
18class HeaderTest(unittest.TestCase):
19    def setUp(self):
20        self.curl = util.DefaultCurl()
21
22    def tearDown(self):
23        self.curl.close()
24
25    def test_ascii_string_header(self):
26        self.check('x-test-header: ascii', 'ascii')
27
28    def test_ascii_unicode_header(self):
29        self.check(util.u('x-test-header: ascii'), 'ascii')
30
31    # on python 2 unicode is accepted in strings because strings are byte strings
32    @util.only_python3
33    def test_unicode_string_header(self):
34        with pytest.raises(UnicodeEncodeError):
35            self.check('x-test-header: Москва', 'Москва')
36
37    def test_unicode_unicode_header(self):
38        with pytest.raises(UnicodeEncodeError):
39            self.check(util.u('x-test-header: Москва'), util.u('Москва'))
40
41    def test_encoded_unicode_header(self):
42        self.check(util.u('x-test-header: Москва').encode('utf-8'), util.u('Москва'))
43
44    def check(self, send, expected):
45        # check as list and as tuple, because they may be handled differently
46        self.do_check([send], expected)
47        self.do_check((send,), expected)
48
49    def do_check(self, send, expected):
50        self.curl.setopt(pycurl.URL, 'http://%s:8380/header_utf8?h=x-test-header' % localhost)
51        sio = util.BytesIO()
52        self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
53        self.curl.setopt(pycurl.HTTPHEADER, send)
54        self.curl.perform()
55        self.assertEqual(expected, sio.getvalue().decode('utf-8'))
56