def test_send_file_object(self): app = flask.Flask(__name__) with app.test_request_context(): with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f: rv = flask.send_file(f) rv.direct_passthrough = False with app.open_resource('static/index.html') as f: assert rv.data == f.read() assert rv.mimetype == 'text/html' rv.close() app.use_x_sendfile = True with app.test_request_context(): with open(os.path.join(app.root_path, 'static/index.html')) as f: rv = flask.send_file(f) assert rv.mimetype == 'text/html' assert 'x-sendfile' in rv.headers assert rv.headers['x-sendfile'] == \ os.path.join(app.root_path, 'static/index.html') rv.close() app.use_x_sendfile = False with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'application/octet-stream' rv.close() class PyStringIO(object): def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name) f = PyStringIO('Test') f.name = 'test.txt' rv = flask.send_file(f) rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'text/plain' rv.close() f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'text/plain' rv.close() app.use_x_sendfile = True with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) assert 'x-sendfile' not in rv.headers rv.close()
def test_json_dump_to_file(self, app, app_ctx): test_data = {'name': 'Flask'} out = StringIO() flask.json.dump(test_data, out) out.seek(0) rv = flask.json.load(out) assert rv == test_data
def test_json_dump_to_file(self): app = flask.Flask(__name__) test_data = {'name': 'Flask'} out = StringIO() with app.app_context(): flask.json.dump(test_data, out) out.seek(0) rv = flask.json.load(out) assert rv == test_data
def test_send_file_object(self, app, req_ctx): with open(os.path.join(app.root_path, "static/index.html"), mode="rb") as f: rv = flask.send_file(f, mimetype="text/html") rv.direct_passthrough = False with app.open_resource("static/index.html") as f: assert rv.data == f.read() assert rv.mimetype == "text/html" rv.close() app.use_x_sendfile = True with open(os.path.join(app.root_path, "static/index.html")) as f: rv = flask.send_file(f, mimetype="text/html") assert rv.mimetype == "text/html" assert "x-sendfile" not in rv.headers rv.close() app.use_x_sendfile = False f = StringIO("Test") rv = flask.send_file(f, mimetype="application/octet-stream") rv.direct_passthrough = False assert rv.data == b"Test" assert rv.mimetype == "application/octet-stream" rv.close() class PyStringIO(object): def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name) f = PyStringIO("Test") f.name = "test.txt" rv = flask.send_file(f, attachment_filename=f.name) rv.direct_passthrough = False assert rv.data == b"Test" assert rv.mimetype == "text/plain" rv.close() f = StringIO("Test") rv = flask.send_file(f, mimetype="text/plain") rv.direct_passthrough = False assert rv.data == b"Test" assert rv.mimetype == "text/plain" rv.close() app.use_x_sendfile = True f = StringIO("Test") rv = flask.send_file(f, mimetype="text/html") assert "x-sendfile" not in rv.headers rv.close()
def test_log_view_exception(app, client): @app.route('/') def index(): raise Exception('test') app.testing = False stream = StringIO() rv = client.get('/', errors_stream=stream) assert rv.status_code == 500 assert rv.data err = stream.getvalue() assert 'Exception on / [GET]' in err assert 'Exception: test' in err
def test_wsgi_errors_stream(app, client): @app.route('/') def index(): app.logger.error('test') return '' stream = StringIO() client.get('/', errors_stream=stream) assert 'ERROR in test_logging: test' in stream.getvalue() assert wsgi_errors_stream._get_current_object() is sys.stderr with app.test_request_context(errors_stream=stream): assert wsgi_errors_stream._get_current_object() is stream
def test_exception_logging(self): out = StringIO() app = flask.Flask(__name__) app.logger_name = 'flask_tests/test_exception_logging' app.logger.addHandler(StreamHandler(out)) @app.route('/') def index(): 1 // 0 rv = app.test_client().get('/') self.assert_equal(rv.status_code, 500) self.assert_in(b'Internal Server Error', rv.data) err = out.getvalue() self.assert_in('Exception on / [GET]', err) self.assert_in('Traceback (most recent call last):', err) self.assert_in('1 // 0', err) self.assert_in('ZeroDivisionError:', err)
def test_exception_logging(self): out = StringIO() app = flask.Flask(__name__) app.logger_name = "flask_tests/test_exception_logging" app.logger.addHandler(StreamHandler(out)) @app.route("/") def index(): 1 // 0 rv = app.test_client().get("/") self.assert_equal(rv.status_code, 500) self.assert_in(b"Internal Server Error", rv.data) err = out.getvalue() self.assert_in("Exception on / [GET]", err) self.assert_in("Traceback (most recent call last):", err) self.assert_in("1 // 0", err) self.assert_in("ZeroDivisionError:", err)
def test_send_file_object(self, app, req_ctx): with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f: rv = flask.send_file(f, mimetype='text/html') rv.direct_passthrough = False with app.open_resource('static/index.html') as f: assert rv.data == f.read() assert rv.mimetype == 'text/html' rv.close() app.use_x_sendfile = True with open(os.path.join(app.root_path, 'static/index.html')) as f: rv = flask.send_file(f, mimetype='text/html') assert rv.mimetype == 'text/html' assert 'x-sendfile' not in rv.headers rv.close() app.use_x_sendfile = False f = StringIO('Test') rv = flask.send_file(f, mimetype='application/octet-stream') rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'application/octet-stream' rv.close() class PyStringIO(object): def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name) f = PyStringIO('Test') f.name = 'test.txt' rv = flask.send_file(f, attachment_filename=f.name) rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'text/plain' rv.close() f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'text/plain' rv.close() app.use_x_sendfile = True f = StringIO('Test') rv = flask.send_file(f, mimetype='text/html') assert 'x-sendfile' not in rv.headers rv.close()
def test_exception_logging(self): out = StringIO() app = flask.Flask(__name__) app.config['LOGGER_HANDLER_POLICY'] = 'never' app.logger_name = 'flask_tests/test_exception_logging' app.logger.addHandler(StreamHandler(out)) @app.route('/') def index(): 1 // 0 rv = app.test_client().get('/') assert rv.status_code == 500 assert b'Internal Server Error' in rv.data err = out.getvalue() assert 'Exception on / [GET]' in err assert 'Traceback (most recent call last):' in err assert '1 // 0' in err assert 'ZeroDivisionError:' in err
def test_suppressed_exception_logging(): class SuppressedFlask(flask.Flask): def log_exception(self, exc_info): pass out = StringIO() app = SuppressedFlask(__name__) app.logger_name = 'flask_tests/test_suppressed_exception_logging' app.logger.addHandler(StreamHandler(out)) @app.route('/') def index(): 1 // 0 rv = app.test_client().get('/') assert rv.status_code == 500 assert b'Internal Server Error' in rv.data err = out.getvalue() assert err == ''
def test_exception_logging(self, app, client): out = StringIO() app.config['LOGGER_HANDLER_POLICY'] = 'never' app.logger_name = 'flask_tests/test_exception_logging' app.logger.addHandler(StreamHandler(out)) app.testing = False @app.route('/') def index(): 1 // 0 rv = client.get('/') assert rv.status_code == 500 assert b'Internal Server Error' in rv.data err = out.getvalue() assert 'Exception on / [GET]' in err assert 'Traceback (most recent call last):' in err assert '1 // 0' in err assert 'ZeroDivisionError:' in err
def test_attachment(self, app, req_ctx): app = flask.Flask(__name__) with app.test_request_context(): with open(os.path.join(app.root_path, "static/index.html")) as f: rv = flask.send_file(f, as_attachment=True, attachment_filename="index.html") value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" rv.close() with open(os.path.join(app.root_path, "static/index.html")) as f: rv = flask.send_file(f, as_attachment=True, attachment_filename="index.html") value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" assert options["filename"] == "index.html" assert "filename*" not in rv.headers["Content-Disposition"] rv.close() rv = flask.send_file("static/index.html", as_attachment=True) value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" assert options["filename"] == "index.html" rv.close() rv = flask.send_file( StringIO("Test"), as_attachment=True, attachment_filename="index.txt", add_etags=False, ) assert rv.mimetype == "text/plain" value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" assert options["filename"] == "index.txt" rv.close()
def test_attachment(self, app, req_ctx): app = flask.Flask(__name__) with app.test_request_context(): with open(os.path.join(app.root_path, 'static/index.html')) as f: rv = flask.send_file(f, as_attachment=True, attachment_filename='index.html') value, options = \ parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' rv.close() with open(os.path.join(app.root_path, 'static/index.html')) as f: rv = flask.send_file(f, as_attachment=True, attachment_filename='index.html') value, options = \ parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' assert 'filename*' not in rv.headers['Content-Disposition'] rv.close() rv = flask.send_file('static/index.html', as_attachment=True) value, options = parse_options_header( rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' rv.close() rv = flask.send_file(StringIO('Test'), as_attachment=True, attachment_filename='index.txt', add_etags=False) assert rv.mimetype == 'text/plain' value, options = parse_options_header( rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.txt' rv.close()
class TestSendfile(object): def test_send_file_regular(self, app, req_ctx): rv = flask.send_file("static/index.html") assert rv.direct_passthrough assert rv.mimetype == "text/html" with app.open_resource("static/index.html") as f: rv.direct_passthrough = False assert rv.data == f.read() rv.close() def test_send_file_xsendfile(self, app, req_ctx): app.use_x_sendfile = True rv = flask.send_file("static/index.html") assert rv.direct_passthrough assert "x-sendfile" in rv.headers assert rv.headers["x-sendfile"] == os.path.join( app.root_path, "static/index.html") assert rv.mimetype == "text/html" rv.close() def test_send_file_last_modified(self, app, client): last_modified = datetime.datetime(1999, 1, 1) @app.route("/") def index(): return flask.send_file( io.BytesIO(b"party like it's"), last_modified=last_modified, mimetype="text/plain", ) rv = client.get("/") assert rv.last_modified == last_modified def test_send_file_object_without_mimetype(self, app, req_ctx): with pytest.raises(ValueError) as excinfo: flask.send_file(io.BytesIO(b"LOL")) assert "Unable to infer MIME-type" in str(excinfo.value) assert "no filename is available" in str(excinfo.value) flask.send_file(io.BytesIO(b"LOL"), attachment_filename="filename") @pytest.mark.parametrize( "opener", [ lambda app: open(os.path.join(app.static_folder, "index.html"), "rb"), lambda app: io.BytesIO(b"Test"), pytest.param( lambda app: StringIO("Test"), marks=pytest.mark.skipif(not PY2, reason="Python 2 only"), ), lambda app: PyStringIO(b"Test"), ], ) @pytest.mark.usefixtures("req_ctx") def test_send_file_object(self, app, opener): file = opener(app) app.use_x_sendfile = True rv = flask.send_file(file, mimetype="text/plain") rv.direct_passthrough = False assert rv.data assert rv.mimetype == "text/plain" assert "x-sendfile" not in rv.headers rv.close() @pytest.mark.parametrize( "opener", [ lambda app: io.StringIO(u"Test"), pytest.param( lambda app: open(os.path.join(app.static_folder, "index.html") ), marks=pytest.mark.skipif(PY2, reason="Python 3 only"), ), ], ) @pytest.mark.usefixtures("req_ctx") def test_send_file_text_fails(self, app, opener): file = opener(app) with pytest.raises(ValueError): flask.send_file(file, mimetype="text/plain") file.close() def test_send_file_pathlike(self, app, req_ctx): rv = flask.send_file(FakePath("static/index.html")) assert rv.direct_passthrough assert rv.mimetype == "text/html" with app.open_resource("static/index.html") as f: rv.direct_passthrough = False assert rv.data == f.read() rv.close() @pytest.mark.skipif( not callable(getattr(Range, "to_content_range_header", None)), reason="not implemented within werkzeug", ) def test_send_file_range_request(self, app, client): @app.route("/") def index(): return flask.send_file("static/index.html", conditional=True) rv = client.get("/", headers={"Range": "bytes=4-15"}) assert rv.status_code == 206 with app.open_resource("static/index.html") as f: assert rv.data == f.read()[4:16] rv.close() rv = client.get("/", headers={"Range": "bytes=4-"}) assert rv.status_code == 206 with app.open_resource("static/index.html") as f: assert rv.data == f.read()[4:] rv.close() rv = client.get("/", headers={"Range": "bytes=4-1000"}) assert rv.status_code == 206 with app.open_resource("static/index.html") as f: assert rv.data == f.read()[4:] rv.close() rv = client.get("/", headers={"Range": "bytes=-10"}) assert rv.status_code == 206 with app.open_resource("static/index.html") as f: assert rv.data == f.read()[-10:] rv.close() rv = client.get("/", headers={"Range": "bytes=1000-"}) assert rv.status_code == 416 rv.close() rv = client.get("/", headers={"Range": "bytes=-"}) assert rv.status_code == 416 rv.close() rv = client.get("/", headers={"Range": "somethingsomething"}) assert rv.status_code == 416 rv.close() last_modified = datetime.datetime.utcfromtimestamp( os.path.getmtime(os.path.join( app.root_path, "static/index.html"))).replace(microsecond=0) rv = client.get("/", headers={ "Range": "bytes=4-15", "If-Range": http_date(last_modified) }) assert rv.status_code == 206 rv.close() rv = client.get( "/", headers={ "Range": "bytes=4-15", "If-Range": http_date(datetime.datetime(1999, 1, 1)), }, ) assert rv.status_code == 200 rv.close() def test_send_file_range_request_bytesio(self, app, client): @app.route("/") def index(): file = io.BytesIO(b"somethingsomething") return flask.send_file(file, attachment_filename="filename", conditional=True) rv = client.get("/", headers={"Range": "bytes=4-15"}) assert rv.status_code == 206 assert rv.data == b"somethingsomething"[4:16] rv.close() def test_send_file_range_request_xsendfile_invalid(self, app, client): # https://github.com/pallets/flask/issues/2526 app.use_x_sendfile = True @app.route("/") def index(): return flask.send_file("static/index.html", conditional=True) rv = client.get("/", headers={"Range": "bytes=1000-"}) assert rv.status_code == 416 rv.close() def test_attachment(self, app, req_ctx): app = flask.Flask(__name__) with app.test_request_context(): with open(os.path.join(app.root_path, "static/index.html"), "rb") as f: rv = flask.send_file(f, as_attachment=True, attachment_filename="index.html") value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" rv.close() with open(os.path.join(app.root_path, "static/index.html"), "rb") as f: rv = flask.send_file(f, as_attachment=True, attachment_filename="index.html") value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" assert options["filename"] == "index.html" assert "filename*" not in rv.headers["Content-Disposition"] rv.close() rv = flask.send_file("static/index.html", as_attachment=True) value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" assert options["filename"] == "index.html" rv.close() rv = flask.send_file( io.BytesIO(b"Test"), as_attachment=True, attachment_filename="index.txt", add_etags=False, ) assert rv.mimetype == "text/plain" value, options = parse_options_header( rv.headers["Content-Disposition"]) assert value == "attachment" assert options["filename"] == "index.txt" rv.close() @pytest.mark.usefixtures("req_ctx") @pytest.mark.parametrize( ("filename", "ascii", "utf8"), ( ("index.html", "index.html", False), ( u"Ñandú/pingüino.txt", '"Nandu/pinguino.txt"', "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt", ), (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"), # Native string not marked as Unicode on Python 2 ("tést.txt", "test.txt", "t%C3%A9st.txt"), # ":/" are not safe in filename* value (u"те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"), ), ) def test_attachment_filename_encoding(self, filename, ascii, utf8): rv = flask.send_file("static/index.html", as_attachment=True, attachment_filename=filename) rv.close() content_disposition = rv.headers["Content-Disposition"] assert "filename=%s" % ascii in content_disposition if utf8: assert "filename*=UTF-8''" + utf8 in content_disposition else: assert "filename*=UTF-8''" not in content_disposition def test_static_file(self, app, req_ctx): # default cache timeout is 12 hours # Test with static file handler. rv = app.send_static_file("index.html") cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 12 * 60 * 60 rv.close() # Test again with direct use of send_file utility. rv = flask.send_file("static/index.html") cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 12 * 60 * 60 rv.close() app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600 # Test with static file handler. rv = app.send_static_file("index.html") cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 3600 rv.close() # Test again with direct use of send_file utility. rv = flask.send_file("static/index.html") cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 3600 rv.close() # Test with static file handler. rv = app.send_static_file(FakePath("index.html")) cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 3600 rv.close() class StaticFileApp(flask.Flask): def get_send_file_max_age(self, filename): return 10 app = StaticFileApp(__name__) with app.test_request_context(): # Test with static file handler. rv = app.send_static_file("index.html") cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 10 rv.close() # Test again with direct use of send_file utility. rv = flask.send_file("static/index.html") cc = parse_cache_control_header(rv.headers["Cache-Control"]) assert cc.max_age == 10 rv.close() def test_send_from_directory(self, app, req_ctx): app.root_path = os.path.join(os.path.dirname(__file__), "test_apps", "subdomaintestmodule") rv = flask.send_from_directory("static", "hello.txt") rv.direct_passthrough = False assert rv.data.strip() == b"Hello Subdomain" rv.close() def test_send_from_directory_pathlike(self, app, req_ctx): app.root_path = os.path.join(os.path.dirname(__file__), "test_apps", "subdomaintestmodule") rv = flask.send_from_directory(FakePath("static"), FakePath("hello.txt")) rv.direct_passthrough = False assert rv.data.strip() == b"Hello Subdomain" rv.close() def test_send_from_directory_null_character(self, app, req_ctx): app.root_path = os.path.join(os.path.dirname(__file__), "test_apps", "subdomaintestmodule") if sys.version_info >= (3, 8): exception = NotFound else: exception = BadRequest with pytest.raises(exception): flask.send_from_directory("static", "bad\x00")
def log_stream(app): stream = StringIO() handler = logging.StreamHandler(stream) app.logger.addHandler(handler) return stream
def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name)
def index(): return flask.send_file(StringIO("party like it's"), last_modified=last_modified)
def index(): return flask.send_file( StringIO("party like it's"), last_modified=last_modified, mimetype="text/plain", )
def test_send_file_object(self): app = flask.Flask(__name__) with catch_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) rv.direct_passthrough = False with app.open_resource('static/index.html') as f: self.assert_equal(rv.data, f.read()) self.assert_equal(rv.mimetype, 'text/html') rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) app.use_x_sendfile = True with catch_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) self.assert_equal(rv.mimetype, 'text/html') self.assert_in('x-sendfile', rv.headers) self.assert_equal( rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) app.use_x_sendfile = False with app.test_request_context(): with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f) rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'application/octet-stream') rv.close() # etags self.assert_equal(len(captured), 1) with catch_warnings() as captured: class PyStringIO(object): def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name) f = PyStringIO('Test') f.name = 'test.txt' rv = flask.send_file(f) rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') rv.close() # attachment_filename and etags self.assert_equal(len(captured), 3) with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') rv.close() # etags self.assert_equal(len(captured), 1) app.use_x_sendfile = True with catch_warnings() as captured: with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) self.assert_not_in('x-sendfile', rv.headers) rv.close() # etags self.assert_equal(len(captured), 1)
def test_send_file_object(self): app = flask.Flask(__name__) with catch_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) rv.direct_passthrough = False with app.open_resource('static/index.html') as f: self.assert_equal(rv.data, f.read()) self.assert_equal(rv.mimetype, 'text/html') rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) app.use_x_sendfile = True with catch_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) self.assert_equal(rv.mimetype, 'text/html') self.assert_in('x-sendfile', rv.headers) self.assert_equal(rv.headers['x-sendfile'], os.path.join(app.root_path, 'static/index.html')) rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) app.use_x_sendfile = False with app.test_request_context(): with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f) rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'application/octet-stream') rv.close() # etags self.assert_equal(len(captured), 1) with catch_warnings() as captured: class PyStringIO(object): def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name) f = PyStringIO('Test') f.name = 'test.txt' rv = flask.send_file(f) rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') rv.close() # attachment_filename and etags self.assert_equal(len(captured), 3) with catch_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') rv.direct_passthrough = False self.assert_equal(rv.data, b'Test') self.assert_equal(rv.mimetype, 'text/plain') rv.close() # etags self.assert_equal(len(captured), 1) app.use_x_sendfile = True with catch_warnings() as captured: with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) self.assert_not_in('x-sendfile', rv.headers) rv.close() # etags self.assert_equal(len(captured), 1)
def test_send_file_object(self, catch_deprecation_warnings): app = flask.Flask(__name__) with catch_deprecation_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb') rv = flask.send_file(f) rv.direct_passthrough = False with app.open_resource('static/index.html') as f: assert rv.data == f.read() assert rv.mimetype == 'text/html' rv.close() # mimetypes + etag assert len(captured) == 2 app.use_x_sendfile = True with catch_deprecation_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) assert rv.mimetype == 'text/html' assert 'x-sendfile' in rv.headers assert rv.headers['x-sendfile'] == \ os.path.join(app.root_path, 'static/index.html') rv.close() # mimetypes + etag assert len(captured) == 2 app.use_x_sendfile = False with app.test_request_context(): with catch_deprecation_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f) rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'application/octet-stream' rv.close() # etags assert len(captured) == 1 with catch_deprecation_warnings() as captured: class PyStringIO(object): def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs) def __getattr__(self, name): return getattr(self._io, name) f = PyStringIO('Test') f.name = 'test.txt' rv = flask.send_file(f) rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'text/plain' rv.close() # attachment_filename and etags assert len(captured) == 3 with catch_deprecation_warnings() as captured: f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') rv.direct_passthrough = False assert rv.data == b'Test' assert rv.mimetype == 'text/plain' rv.close() # etags assert len(captured) == 1 app.use_x_sendfile = True with catch_deprecation_warnings() as captured: with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) assert 'x-sendfile' not in rv.headers rv.close() # etags assert len(captured) == 1
def __init__(self, *args, **kwargs): self._io = StringIO(*args, **kwargs)
rv = flask.send_file(f, as_attachment=True, attachment_filename='index.html') value, options = \ parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' assert 'filename*' not in rv.headers['Content-Disposition'] rv.close() rv = flask.send_file('static/index.html', as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' rv.close() rv = flask.send_file(StringIO('Test'), as_attachment=True, attachment_filename='index.txt', add_etags=False) assert rv.mimetype == 'text/plain' value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.txt' rv.close() def test_attachment_with_utf8_filename(self, app, req_ctx): rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt') content_disposition = set(rv.headers['Content-Disposition'].split('; ')) assert content_disposition == set(( 'attachment', 'filename="Nandu/pinguino.txt"', "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"