最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

mocking - Overriding patch in pytest - Stack Overflow

programmeradmin4浏览0评论

`

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 'Role Found', 200
        
        return g
    return decorator

@pytest.fixture

def patched_authorization_failure(mocker):

mocker.patch('some_module.middleware.bar.func',

mocker.MagicMock(side_effect=mock_failed_authorization),)

@pytest.fixture

def patched_authorization_success(mocker):

mocker.patch('some_module.middleware.bar.func',

mocker.MagicMock(side_effect=mock_successful_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, 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 with mock.patch() as well to no avail.

发布评论

评论列表(0)

  1. 暂无评论