Issue
Python 3.7. I'm trying to unit test the function below:
def is_json_clean():
# function for is_json_clean here, returns bool
def json_function(blob, raw_bucket, lake_bucket):
data_string = blob.download_as_bytes()
data = json.loads(data_string)
if is_json_clean(data) is True:
raw_bucket.copy_blob(blob, lake_bucket)
I'm pretty new to mock patches, and could use an example here! How could I use mock.patch or something similar to get that if statement with my is_json_clean()
function to return True so that I can assert that the copy_blob function was called? I thought I could make a patch like:
@mock.patch.object(imported_module, "is_json_clean", return_value=True)
def test_json_function(mock):
# rest of the test function
# including assert statement for the copy_blob function
but how then would I insert this into my test to assert my copy_blob function? I know that quite a few unit test-related questions are out there, but I haven't found exactly the answer to my question yet (like I said, I'm pretty new). Any help is appreciated. Thank you!
Solution
Your mocking looks correct, but I don't see the blob, raw_bucket, or lake_bucket args being passed in within your test case. Here's how I would write it, mocking all 3 of those args.
import unittest
from unittest import mock
import imported_module
class MyTest(unittest.TestCase):
@mock.patch.object(imported_module, "is_json_clean", return_value=True)
def test_json_function(self, mock_is_json_clean):
json_blob = '{"mykey": "myvalue"}'
mock_blob = mock.Mock()
mock_blob.download_as_bytes.return_value = json_blob
mock_raw_bucket = mock.Mock()
mock_lake_bucket = mock.Mock()
imported_module.json_function(mock_blob, mock_raw_bucket, mock_lake_bucket)
mock_raw_bucket.copy_blob.assert_called_once_with(mock_blob, mock_lake_bucket)
if __name__ == "__main__":
unittest.main()
You can see that I pass in a mock_blob and mock the return value of download_as_bytes
, as well as passing in the two buckets. From there, I'm able to do an assert on the mock_raw_bucket.copy_blob
call. I was able to get this code running and passing here: https://replit.com/@WesH1/TautLiveTelephone#main.py
Answered By - wholevinski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.