File: test_multipartformdata.py

package info (click to toggle)
circuits 3.1.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,756 kB
  • sloc: python: 15,945; makefile: 130
file content (86 lines) | stat: -rw-r--r-- 1,991 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python

import pytest

from os import path
from io import BytesIO

from circuits.web import Controller

from .multipartform import MultiPartForm
from .helpers import urlopen, Request


@pytest.fixture()
def sample_file(request):
    return open(
        path.join(
            path.dirname(__file__),
            "static", "unicode.txt"
        ),
        "rb"
    )


class Root(Controller):

    def index(self, file, description=""):
        yield "Filename: %s\n" % file.filename
        yield "Description: %s\n" % description
        yield "Content:\n"
        yield file.value

    def upload(self, file, description=""):
        return file.value


def test(webapp):
    form = MultiPartForm()
    form["description"] = "Hello World!"

    fd = BytesIO(b"Hello World!")
    form.add_file("file", "helloworld.txt", fd, "text/plain; charset=utf-8")

    # Build the request
    url = webapp.server.http.base
    data = form.bytes()
    headers = {
        "Content-Type": form.get_content_type(),
        "Content-Length": len(data),
    }

    request = Request(url, data, headers)

    f = urlopen(request)
    s = f.read()
    lines = s.split(b"\n")

    assert lines[0] == b"Filename: helloworld.txt"
    assert lines[1] == b"Description: Hello World!"
    assert lines[2] == b"Content:"
    assert lines[3] == b"Hello World!"


def test_unicode(webapp, sample_file):
    form = MultiPartForm()
    form["description"] = sample_file.name
    form.add_file(
        "file", "helloworld.txt", sample_file,
        "text/plain; charset=utf-8"
    )

    # Build the request
    url = "{0:s}/upload".format(webapp.server.http.base)
    data = form.bytes()
    headers = {
        "Content-Type": form.get_content_type(),
        "Content-Length": len(data),
    }

    request = Request(url, data, headers)

    f = urlopen(request)
    s = f.read()
    sample_file.seek(0)
    expected_output = sample_file.read()  # use the byte stream
    assert s == expected_output