-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Labels
Description
I believe that the following code should be simplified to only do what it is supposed to do.
twitcher/twitcher/models/__init__.py
Lines 53 to 82 in fe51e8f
| 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():
...