/tests/web/test_multipartformdata.py

https://bitbucket.org/prologic/circuits/ · Python · 86 lines · 61 code · 22 blank · 3 comment · 0 complexity · 3f484304a3a4d85ba3fe89adb76ffedb MD5 · raw file

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