Skip to content

Avoid using code only for testing purposes #66

@fmigneault

Description

@fmigneault

I believe that the following code should be simplified to only do what it is supposed to do.

def add_tm_session(request):
""" Request method that returns a SQLAlchemy session for a request.
The SQLAlchemy session is managed by a Zope transaction, unless the request has been generated from a
webtest.TestApp instance for functional testing. In this case:
- Inspect request.environ dictionary for the SQLAlchemy session referenced by key db.session. Remove the
session from the request's environment dictionary and return the session.
- Use the session factory to generate and return a new SQLAlchemy session if there is no entry for db.session
in the request environment dictionary.
The webtest.TestApp instance should configure the environment dictionary as follows:
`testapp = webtest.TestApp(app, extra_environ={'db.session': session, 'tm.active': True})`
Setting tm.active to True causes the pyramid_tm tween to bypass generating a transaction for the SQLAlchemy
session on the request.
This code is taken from:
https://groups.google.com/forum/#!topic/pylons-discuss/BZCeM_yejEE
:param request: Pyramid Request instance
:return: SQLAlchemy session.
"""
if 'paste.testing' in request.environ and request.environ['paste.testing'] is True:
if 'db.session' in request.environ: # and 'db.tm' in request.environ:
dbsession = request.environ['db.session']
del request.environ['db.session']
return dbsession
session = get_tm_session(request.registry['dbsession_factory'], request.tm)
return session

For testing, the mock module should be used to do exactly what the docstring says.
I think that creating a decorator function that does this mocking as required would be the best approach, as it would allow to do something like so:

@mock_db
def test_something():
 ... 

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions