0

We have a test fixture which patches two classes like below.

@pytest.fixture
def license_fixture(mocker):
    
    mocker.patch('api.license_api.UserLicense')
    mocker.patch('api.license_api.UserLicense.userrole', return_value = 'admin') # doesn't work.
    l_mock = mocker.patch('api.license_api.LicenseContent')
    yield l_mock

LicenseContent serves the api calls for license contents and uses UserLicense.

UserLicense is a third party imported class check for the license user has (using crypto) and serves three puposes.

  1. All the crypto methods to check for license verification.
  2. if the user has a valid license via method isvalid()
  3. to set the correct authorization of user via method userrole()

With patching UserLicense I can test the isvalid, but when I try to patch the method to get user role it does not set the return value of method to the admin and the tests fails.

What is the correct way to patch the method?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rohit Srivastava
  • 278
  • 4
  • 17

1 Answers1

0

You could patch return_value of the mocked object:

@pytest.fixture
def license_fixture(mocker):
    
    user_license = mocker.patch('api.license_api.UserLicense')
    user_license.return_value.userrole.return_value = 'admin'
    l_mock = mocker.patch('api.license_api.LicenseContent')
    yield l_mock

userrole is an instance method, so it is called on an instance of UserLicense, not the class itself. An instance is a return value from calling a class. So you need to bear that in mind when you patch.

Taken from this answer

Similar questions:

israteneda
  • 705
  • 1
  • 14
  • 26