1

I have written a test as below:

class TestLoader(TestCase): @pytest.fixture(autouse=True) @patch('loaders.myloader.DSFactory') def _initialize_(self, mock_ds_factory): self.loader = MyLoader() mock_ds = Mock() mock_ds_factory.get_ds_for_env.return_value = mock_ds self.loader.ds = mock_ds def test_load(self): self.loader.ds.read_file.return_value = json.dumps(self.get_data()) self.loader.load("test_s3_key") #####IN THIS LINE I AM GETTING ERROR AS MENTIONED BELOW## @staticmethod def get_data(): return {"key1":"value1","key2":"value2"} 

Associated source is located here: loaders->myloader.py. myloader.py is as follows:

from common.ds_factory import DSFactory class MyLoader: def __init__(self): self.ds = DSFactory.get_ds_for_env() def load(self, file_key): print(f"ds : {self.ds}") print(f"file read is : {self.ds.read_file(S3_BUCKET, file_key)}"} data_dict = json.loads(self.ds.read_file(S3_BUCKET, file_key)) 

But while testing, I am getting error as follows:

ds is :<MagicMock name='DSFactory.get_ds_for_env()' id='140634163567528'> file read is :<MagicMock name='DSFactory.get_ds_for_env().read_file()' id='140635257259568'> E TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock' 

I don't understand why, even after mocking return value of read_file with

self.loader.ds.read_file.return_value = json.dumps(self.get_data()) 

I am getting MagickMock object. I am stuck, not getting any clue how to resolve this.

1 Answer 1

1

Your code: from common.ds_factory import DSFactory

class MyLoader: def __init__(self): self.ds = DSFactory.get_ds_for_env() def load(self, file_key): data_dict = json.loads(self.datastore.read_file(S3_BUCKET, file_key)) 
  1. Issue here i can see is, data-store is not present, it should be self.ds.read_file
  2. Please print self.datastore.read_file(S3_BUCKET, file_key) and verify the output.
  3. This is the error coming from AWS_S3 bucket Json structure. It seems its not sending the Json value in string format rather than in Magic Mock format.

To more about Magic Mock format, please visit here: https://medium.com/ryans-dev-notes/python-mock-and-magicmock-b3295c2cc7eb

Sign up to request clarification or add additional context in comments.

2 Comments

my bad, it was a typo in question.
No worries Joy. Did my answer helps?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.