I am trying to test different authorization scenarios, one that simulates success, and another that simulates failure. I am trying to do this without creating independent test files for success and failure.
def mock_failed_authorization(instance_id=None,
crn=None,
f_instance=None,
resource_group_id=None,
f_resource_group=None):
def decorator(f):
@wraps(f)
def g(*args, **kwargs):
if crn:
pass
if instance_id:
pass
if f_instance:
pass
if resource_group_id:
pass
if f_resource_group:
pass
return 'Role not found', 403
return g
return decorator
def mock_successful_authorization(
instance_id=None,
crn=None,
f_instance=None,
resource_group_id=None,
f_resource_group=None):
def decorator(f):
@wraps(f)
def g(*args, **kwargs):
if crn:
pass
if instance_id:
pass
if f_instance:
pass
if resource_group_id:
pass
if f_resource_group:
pass
return f(*args, **kwargs)
return g
return decorator
@pytest.fixture
def patched_authorization_failure(mocker):
Patch the authorization function to simulate failure behavior
mocker.patch(
'some_module.middleware.bar.func',
mocker.MagicMock(side_effect=mock_failed_authorization),
)
@pytest.fixture
def patched_authorization_success(mocker):
Patch the authorization function to simulate success behavior
mocker.patch(
'some_module.middleware.bar.func',
mocker.MagicMock(side_effect=mock_successfu`l_authorization),
)
@pytest.mark.usefixtures('patched_authorization_success')
@responses.activate
def func_1():
//logic
assert resp.status_int == 200
@pytest.mark.usefixtures("patched_authorization_failure")
@responses.activate
def func_2():
//logic
assert resp.status_int == 403`
Here, when I run this test file, func_1 asserts correctly(200==200), but patched_authorization_failure fails to override the patch created by patched_authorization success, and func_2 asserts 200==403.
I have tried resetting the mock after each test, and also used a temporary variable to store some_module.middleware.bar.func and attempt to reset it after the test, but nothing seems to resolve this issue.
Similarly, when I place func_2 above func_1, func_1 fails to assert(403==200). Is there a way to undo this patch? I have tried using unittest.mock.patch as well, but to no avail.