PageRenderTime 14ms CodeModel.GetById 2ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/web/test_multipartformdata.py

https://bitbucket.org/prologic/circuits/
Python | 86 lines | 76 code | 9 blank | 1 comment | 0 complexity | 3f484304a3a4d85ba3fe89adb76ffedb MD5 | raw file
 1#!/usr/bin/env python
 2
 3import pytest
 4
 5from os import path
 6from io import BytesIO
 7
 8from circuits.web import Controller
 9
10from .multipartform import MultiPartForm
11from .helpers import urlopen, Request
12
13
14@pytest.fixture()
15def sample_file(request):
16    return open(
17        path.join(
18            path.dirname(__file__),
19            "static", "unicode.txt"
20        ),
21        "rb"
22    )
23
24
25class Root(Controller):
26
27    def index(self, file, description=""):
28        yield "Filename: %s\n" % file.filename
29        yield "Description: %s\n" % description
30        yield "Content:\n"
31        yield file.value
32
33    def upload(self, file, description=""):
34        return file.value
35
36
37def test(webapp):
38    form = MultiPartForm()
39    form["description"] = "Hello World!"
40
41    fd = BytesIO(b"Hello World!")
42    form.add_file("file", "helloworld.txt", fd, "text/plain; charset=utf-8")
43
44    # Build the request
45    url = webapp.server.http.base
46    data = form.bytes()
47    headers = {
48        "Content-Type": form.get_content_type(),
49        "Content-Length": len(data),
50    }
51
52    request = Request(url, data, headers)
53
54    f = urlopen(request)
55    s = f.read()
56    lines = s.split(b"\n")
57
58    assert lines[0] == b"Filename: helloworld.txt"
59    assert lines[1] == b"Description: Hello World!"
60    assert lines[2] == b"Content:"
61    assert lines[3] == b"Hello World!"
62
63
64def test_unicode(webapp, sample_file):
65    form = MultiPartForm()
66    form["description"] = sample_file.name
67    form.add_file(
68        "file", "helloworld.txt", sample_file,
69        "text/plain; charset=utf-8"
70    )
71
72    # Build the request
73    url = "{0:s}/upload".format(webapp.server.http.base)
74    data = form.bytes()
75    headers = {
76        "Content-Type": form.get_content_type(),
77        "Content-Length": len(data),
78    }
79
80    request = Request(url, data, headers)
81
82    f = urlopen(request)
83    s = f.read()
84    sample_file.seek(0)
85    expected_output = sample_file.read()  # use the byte stream
86    assert s == expected_output