Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid using code only for testing purposes #66

Open
fmigneault opened this issue May 13, 2019 · 0 comments
Open

Avoid using code only for testing purposes #66

fmigneault opened this issue May 13, 2019 · 0 comments

Comments

@fmigneault
Copy link
Contributor

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():
 ... 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants