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 87
|
#!/usr/bin/env python
from io import BytesIO
from os import path
import pytest
from circuits.web import Controller
from .helpers import Request, urlopen
from .multipartform import MultiPartForm
@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 = f'{webapp.server.http.base:s}/upload'
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
|