Skip to content

Instantly share code, notes, and snippets.

@gmanfunky
Created February 7, 2018 17:34
Show Gist options
  • Save gmanfunky/7b9368a2c2b58a70adfb2302a5742cf6 to your computer and use it in GitHub Desktop.
Save gmanfunky/7b9368a2c2b58a70adfb2302a5742cf6 to your computer and use it in GitHub Desktop.
Python unit test - Mocking out a decorator that has a parameter
# Great answer by Danila Ganchar at https://stackoverflow.com/questions/47900727/mock-authentication-decorator-in-unittesting
# mock out check_auth decorator
from functools import wraps
from unittest.mock import patch
def mock_decorator(*args):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
return f(*args, **kwargs)
return decorated_function
return decorator
patch('myflask_app.views.check_auth', mock_decorator).start()
# alternatively, instead of using patch, you /could/ just monkey patch
#from myflask_app import views
#views.check_auth = mock_decorator
#... BELOW this is where you import the views using the decorator. Must mock it BEFORE they are first encountered.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment