Skip to content

Instantly share code, notes, and snippets.

@matin
Created August 25, 2010 21:21
Show Gist options
  • Save matin/550319 to your computer and use it in GitHub Desktop.
Save matin/550319 to your computer and use it in GitHub Desktop.
import unittest
import copy
from sqlalchemy import create_engine, Column, Integer, PickleType
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from mechanize import Browser
from mechanize._clientcookie import CookieJar
engine = create_engine('sqlite:///:memory:', echo=False)
Session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base(bind=engine)
def memoize(function):
cache = {}
def decorated_function(*args):
if args in cache:
return cache[args]
else:
val = function(*args)
cache[args] = val
return val
return decorated_function
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
cookiejar = Column(PickleType, default=CookieJar(), nullable=False)
@property
@memoize
def opener(self):
br = Browser()
br.set_cookiejar(self.cookiejar)
return br
class SACookieJarTest(unittest.TestCase):
def setUp(self):
Base.metadata.create_all()
def tearDown(self):
Session.expunge_all()
Session.rollback()
Session.remove()
Base.metadata.drop_all()
# Currently fails
def test_no_change(self):
user = User()
Session.add(user)
Session.commit()
str(user.cookiejar) # access
self.assertFalse(Session.is_modified(user), 'SQLAlchemy incorrectly '
'thinks the instance was modified')
def test_change(self):
user = User()
Session.add(user)
Session.commit()
old_cookiejar = copy.deepcopy(user.cookiejar)
user.opener.open('http://google.com')
self.assertNotEqual(user.cookiejar, old_cookiejar)
self.assertTrue(Session.is_modified(user))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment