| 1 |
import sys |
| 2 |
|
| 3 |
sys.path.append("src") |
| 4 |
import flask # noqa E402 |
| 5 |
import flask_session # noqa E402 |
| 6 |
import pytest # noqa E402 |
| 7 |
|
| 8 |
|
| 9 |
@pytest.fixture(scope="function") |
| 10 |
def app_utils(): |
| 11 |
class Utils: |
| 12 |
def create_app(self, config_dict=None): |
| 13 |
app = flask.Flask(__name__) |
| 14 |
if config_dict: |
| 15 |
app.config.update(config_dict) |
| 16 |
app.config["SESSION_SERIALIZATION_FORMAT"] = "json" |
| 17 |
app.config["SESSION_PERMANENT"] = False |
| 18 |
|
| 19 |
@app.route("/", methods=["GET"]) |
| 20 |
def app_hello(): |
| 21 |
return "hello world" |
| 22 |
|
| 23 |
@app.route("/set", methods=["POST"]) |
| 24 |
def app_set(): |
| 25 |
flask.session["value"] = flask.request.form["value"] |
| 26 |
return "value set" |
| 27 |
|
| 28 |
@app.route("/modify", methods=["POST"]) |
| 29 |
def app_modify(): |
| 30 |
flask.session["value"] = flask.request.form["value"] |
| 31 |
return "value set" |
| 32 |
|
| 33 |
@app.route("/delete", methods=["POST"]) |
| 34 |
def app_del(): |
| 35 |
del flask.session["value"] |
| 36 |
return "value deleted" |
| 37 |
|
| 38 |
@app.route("/get") |
| 39 |
def app_get(): |
| 40 |
return flask.session.get("value", "no value set") |
| 41 |
|
| 42 |
flask_session.Session(app) |
| 43 |
return app |
| 44 |
|
| 45 |
def test_session(self, app): |
| 46 |
client = app.test_client() |
| 47 |
|
| 48 |
# Check no value is set from previous tests |
| 49 |
assert client.get("/get").data not in [b"42", b"43", b"44"] |
| 50 |
|
| 51 |
# Check if the Vary header is not set |
| 52 |
rv = client.get("/") |
| 53 |
assert "Vary" not in rv.headers |
| 54 |
|
| 55 |
# Set a value and check it |
| 56 |
assert client.post("/set", data={"value": "42"}).data == b"value set" |
| 57 |
assert client.get("/get").data == b"42" |
| 58 |
|
| 59 |
# Check if the Vary header is set |
| 60 |
rv = client.get("/get") |
| 61 |
assert rv.headers["Vary"] == "Cookie" |
| 62 |
|
| 63 |
# Modify and delete the value |
| 64 |
assert client.post("/modify", data={"value": "43"}).data == b"value set" |
| 65 |
assert client.get("/get").data == b"43" |
| 66 |
assert client.post("/delete").data == b"value deleted" |
| 67 |
assert client.get("/get").data == b"no value set" |
| 68 |
|
| 69 |
def test_session_with_cookie(self, app): |
| 70 |
client = app.test_client() |
| 71 |
|
| 72 |
# Access cookies from the response to cross check with the stored session |
| 73 |
response = client.post("/set", data={"value": "44"}) |
| 74 |
session_cookie = None |
| 75 |
for cookie in response.headers.getlist("Set-Cookie"): |
| 76 |
if "session=" in cookie: |
| 77 |
session_cookie = cookie |
| 78 |
break |
| 79 |
assert session_cookie is not None, "Session cookie was not set." |
| 80 |
return session_cookie |
| 81 |
|
| 82 |
return Utils() |