Skip to content

Commit

Permalink
Better session and many small pep8 improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
mdipierro committed May 27, 2024
1 parent 30a558f commit 326b0df
Show file tree
Hide file tree
Showing 12 changed files with 351 additions and 256 deletions.
516 changes: 303 additions & 213 deletions py4web/core.py

Large diffs are not rendered by default.

36 changes: 25 additions & 11 deletions tests/test_action.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# pylint: disable=assignment-from-none
import copy
import multiprocessing
import os
import threading
import time
import unittest
import uuid
Expand All @@ -9,7 +11,7 @@
import requests

from py4web import DAL, HTTP, Cache, Condition, Field, Session, abort, action
from py4web.core import Fixture, MetaLocal, bottle, error404, request
from py4web.core import Fixture, bottle, error404, request

os.environ["PY4WEB_APPS_FOLDER"] = os.path.sep.join(
os.path.normpath(__file__).split(os.path.sep)[:-2]
Expand All @@ -29,14 +31,12 @@
@action.uses(db, session)
@action.uses(Condition(lambda: True))
def index():
db.thing.insert(name="test")
new_id = db.thing.insert(name="test")
session["number"] = session.get("number", 0) + 1

# test copying Field ThreadSafe attr
db.thing.name.default = "test_clone"
field_clone = copy.copy(db.thing.name)
clone_ok = 1 if field_clone.default == db.thing.name.default == "test_clone" else 0
return "ok %s %s %s" % (session["number"], db(db.thing).count(), clone_ok)
return "ok %s %s %s" % (session["number"], db(db.thing).count(), new_id)


def fail():
Expand Down Expand Up @@ -84,6 +84,20 @@ def run_server():
bottle.run(host="localhost", port=8001)


class FieldTest(unittest.TestCase):
"""Check that we chat we can safely clone Field(s)"""

def test_fiel_clone(self):
def test():
db.thing.name.default = "test"
field_clone = copy.copy(db.thing.name)
assert field_clone.default == db.thing.name.default == "test"

thread = threading.Thread(target=test)
thread.start()
thread.join()


class CacheAction(unittest.TestCase):
def setUp(self):
self.server = multiprocessing.Process(target=run_server)
Expand All @@ -104,23 +118,23 @@ def test_action(self):
time.sleep(2)

res = self.browser.open("http://127.0.0.1:8001/tests/index")
self.assertEqual(res.read(), b"ok 2 2 1")
self.assertEqual(res.read(), b"ok 2 2 2")

def test_error(self):
res = requests.get("http://127.0.0.1:8001/tests/conditional")
res = requests.get("http://127.0.0.1:8001/tests/conditional", timeout=5)
self.assertEqual(res.status_code, 404)

res = requests.get("http://127.0.0.1:8001/tests/raise300")
res = requests.get("http://127.0.0.1:8001/tests/raise300", timeout=5)
self.assertEqual(res.status_code, 300)

res = requests.get("http://127.0.0.1:8001/tests/abort")
res = requests.get("http://127.0.0.1:8001/tests/abort", timeout=5)
self.assertEqual(res.status_code, 400)

res = requests.get("http://127.0.0.1:8001/tests/abort_caught")
res = requests.get("http://127.0.0.1:8001/tests/abort_caught", timeout=5)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.content, b"caught")

res = requests.get("http://127.0.0.1:8001/tests/bottle_httpresponse")
res = requests.get("http://127.0.0.1:8001/tests/bottle_httpresponse", timeout=5)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.content, b"ok")

Expand Down
14 changes: 7 additions & 7 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import unittest
import uuid

from py4web.core import DAL, HTTP, Field, MetaLocal, Session, bottle, request, safely
from py4web.core import DAL, HTTP, Field, Fixture, Session, bottle, request, safely
from py4web.utils.auth import Auth, AuthAPI

SECRET = str(uuid.uuid4())
Expand All @@ -23,7 +23,7 @@ def setUp(self):

def tearDown(self):
# this is normally done by @action
safely(lambda: MetaLocal.local_delete(self.session))
safely(lambda: Fixture.local_delete(self.session))
bottle.app.router.remove("/*")

def action(self, name, method, query, data):
Expand All @@ -34,18 +34,18 @@ def action(self, name, method, query, data):
# we break a symmetry below. should fix in auth.py
if name.startswith("api/"):
return getattr(AuthAPI, name[4:])(self.auth)
else:
return getattr(self.auth.form_source, name)()
return getattr(self.auth.form_source, name)()

def on_request(self, context={}, keep_session=False):
def on_request(self, context=None, keep_session=False):
# store the current session
context = context or {}
try:
storage = self.session.local.__dict__
except RuntimeError:
storage = None
# reinitialize everything
safely(lambda: MetaLocal.local_delete(self.session))
safely(lambda: MetaLocal.local_delete(self.auth.flash))
safely(lambda: Fixture.local_delete(self.session))
safely(lambda: Fixture.local_delete(self.auth.flash))
self.session.on_request(context)
self.auth.flash.on_request(context)
self.auth.on_request(context)
Expand Down
12 changes: 7 additions & 5 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def test_logic(self):
def test_different_keys(self):
cache = py4web.Cache()
results = set()
for k in range(100):
for _ in range(100):
results.add(cache.get("a", random.random))
results.add(cache.get("b", random.random))
results.add(cache.get("c", random.random))
Expand All @@ -29,7 +29,9 @@ def test_change_detection(self):
results = set()
for k in range(30):
results.add(
cache.get("a", random.random, expiration=0, monitor=lambda: int(k / 10))
cache.get(
"a", random.random, expiration=0, monitor=lambda k=k: int(k / 10)
)
)
self.assertEqual(len(results), 3)
time.sleep(0.02)
Expand All @@ -42,7 +44,7 @@ def test_timing(self):
for k in range(M):
cache.get(k, random.random)
t0 = time.time()
for k in range(N):
for _ in range(N):
cache.get("new", random.random)
self.assertTrue((time.time() - t0) / N, 1 - 5)
self.assertTrue(cache.free == 0)
Expand All @@ -55,11 +57,11 @@ def f(x):
return x + random.random()

results = set()
for k in range(10):
for _ in range(10):
results.add(f(1))
results.add(f(2))
time.sleep(0.2)
for k in range(10):
for _ in range(10):
results.add(f(1))
results.add(f(2))
self.assertEqual(len(results), 4)
12 changes: 5 additions & 7 deletions tests/test_fixture.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import threading
from types import SimpleNamespace

import pytest

from py4web.core import Fixture, MetaLocal
from py4web.core import Fixture


def run_thread(func, *a):
t = threading.Thread(target=func, args=a)
return t


class Foo(Fixture, MetaLocal):
class Foo(Fixture):
def on_request(self, context):
MetaFixture.local_initialize(self)
Fixture.local_initialize(self)

@property
def bar(self):
Expand All @@ -31,12 +29,12 @@ def bar(self, a):
@pytest.fixture
def init_foo():
def init(key, a, evnt_done=None, evnt_play=None):
MetaLocal.local_initialize(foo)
Fixture.local_initialize(foo)
foo.bar = a
evnt_done and evnt_done.set()
evnt_play and evnt_play.wait()
results[key] = foo.bar
MetaLocal.local_delete(foo)
Fixture.local_delete(foo)
return foo

return init
Expand Down
1 change: 0 additions & 1 deletion tests/test_form.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import io
import os
import unittest
import uuid

Expand Down
1 change: 0 additions & 1 deletion tests/test_get_error_snapshot.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import unittest

from py4web.core import get_error_snapshot
Expand Down
2 changes: 1 addition & 1 deletion tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class TestJson(unittest.TestCase):
def test_objectify(self):
"""Check if we can serialize objects, generators, and dates"""

class A(object):
class A:
def __init__(self, x):
self.x = x

Expand Down
3 changes: 0 additions & 3 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ def run_cli():

class MainTest(unittest.TestCase):
def test_main(self):
class MyException(Exception):
pass

def handler(signum, frame):
raise KeyboardInterrupt

Expand Down
6 changes: 2 additions & 4 deletions tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import pytest

from py4web import DAL, Session, request, response
from py4web.core import MetaLocal
from py4web.core import Fixture
from py4web.utils.dbstore import DBStore


Expand All @@ -33,7 +33,7 @@ def request_context(session, context={}):
session.on_success(context)
finally:
session.on_error(context)
MetaLocal.local_delete(session)
Fixture.local_delete(session)


class TestSession(unittest.TestCase):
Expand All @@ -44,7 +44,6 @@ def test_session(self):
with request_context(session):
session["key"] = "value"
assert "key" in session.local.data
cookie_name = session.local.session_cookie_name

a, b = str(response._cookies)[len("Set-Cookie: ") :].split(";")[0].split("=", 1)
b = unquote(b)
Expand All @@ -67,7 +66,6 @@ def test_session_as_attributes(self):
with request_context(session):
session.key = "value"
assert "key" in session.local.data
cookie_name = session.local.session_cookie_name

a, b = str(response._cookies)[len("Set-Cookie: ") :].split(";")[0].split("=", 1)
b = unquote(b)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_template.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import unittest

from py4web.core import Template, request
from py4web.core import Template

PATH = os.path.join(os.path.dirname(__file__), "templates")

Expand Down
2 changes: 0 additions & 2 deletions tests/test_url.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import random
import time
import unittest

from py4web import URL, request
Expand Down

0 comments on commit 326b0df

Please sign in to comment.