mercredi 4 mai 2016

Python Mocking for unit testing using Py.Test

class TestHBVbs3(object):
      @patch.object(Hbvbs3, 'GetConfigClass')
      def test_get_grower_list(self, config_data, mock_requests_get):
          # Arrange
          config_data.return_value = ConfigMock()
          post_response = {'1st_key': '1st_value', '2nd_key': '2nd_Value'}
          mock_requests_get.return_value = MagicMock(status_code=200, post_response=post_response)

          # Act
          sut = Hbvbs3()
          the_response = sut.get_growers_list()

          # Assert
          assert_equals(the_response.response["1st_key"], mock_requests_get.return_value.response["1st_key"])
          assert_equals(the_response.response["2nd_key"], mock_requests_get.return_value.response["2nd_key"])
          assert_equals(the_response.response, mock_requests_get.return_value.response)
          assert_equals(the_response.status_code, mock_requests_get.return_value.status_code)

Actual code in hbvbs3.py:
class Hbvbs3(object):
        _logger = log.logging.getLogger("Hbvbs3")

    def get_growers_list(self):
            dbconfig = GetConfigClass()

My Issue: I could not figure out how to successfully use the annotation to mock this: @patch.object(Hbvbs3, 'GetConfigClass') # This piece of code does NOT work. I had to eventually just put the GetConfigClass instantiation into a utility method and mock that call, but was hoping that I could get help with actually mocking this specific instantiation in the method itself: "get_growers_list(self):" ... - How does one successfully mock this sort of instantiation inside an instance method of my class Hbvbs3 using the mock annotations? I tried all sorts of combinations in the annotation such as:

@patch('Hbvbs3.GetConfigClass')
@patch.object(Hbvbs3, '__main__.GetConfigClass')
@patchHbvbs3('_get_growers_list.GetConfigClass')

None of these worked, so is there a way to simply Mock this sort of instantiation using annotations in python? This doesn't seem that hard, but I'll be danged if I can find the right combination to the annotation. Please let me know where I'm going wrong? Thanks!

Aucun commentaire:

Enregistrer un commentaire