YnkDK
YnkDK

Reputation: 741

Unittest Flask flask.g

When I unittest, I want to be able to set and access flask.g.

flask.g['test'] = {'test': '123'}
test_dict = flask.g['test']

produces this error:

Error
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 346, in __setitem__
    self._get_current_object()[key] = value
TypeError: '_AppCtxGlobals' object does not support item assignment

However, when I run it in production, everything works. If I use the setattr and getattr, the unittesting works, but breaks in production, I get the following error

Error
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 268, in error_router
    return self.handle_error(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 477, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 587, in dispatch_request
resp = meth(*args, **kwargs)
    args = getattr(flask.g, 'test')
AttributeError: 'dict' object has no attribute 'test'

I run the unittest in app_context(). The goal is to have unittests that actually represent production. How can I achive this?

Upvotes: 3

Views: 3105

Answers (1)

Barlog951
Barlog951

Reputation: 80

These two usages are now equivalent

user = getattr(flask.g, 'user', None)
user = flask.g.get('user', None)

example of usage

def get_user():
    user = getattr(g, 'user', None)
    if user is None:
        user = fetch_current_user_from_database()
        g.user = user
    return user

more in official documentation or testing documentation

Upvotes: 6

Related Questions