0

This is a very simple example:

# my_func.py

from google.cloud import storage

storage_client = storage.Client()

def one():
    return 1



# my_func_test.py

import unittest
from my_func import one, storage
from unittest import mock

class TestOne(unittest.TestCase):
    @ mock.patch('my_func.storage')
    def test_assert(self, mock_storage):
        mock_bucket = mock.Mock()
        mock_storage.Client.return_value = mock_bucket
        result = one()
        self.assertEqual(result, 1)

unittest.main()

Why running this test it returns "Project was not passed and could not be determined from the environment". But if I put the storage_client inside one(), it will pass all OK

Nacho
  • 21
  • 3
  • `storage_client` is defined as soon as you import `my_func`; it's too late to mock `storage` to influence its value by then. – chepner Mar 10 '23 at 18:02
  • 1
    Given that `one` has nothing to do with `storage_client`, I'm not sure what any of this patching is supposed to accomplish. – chepner Mar 10 '23 at 18:04
  • It will be used inside, but I wanted to solve this problem first and have a simple code so it's easy to read. Do I have then to define it inside the function? Is there any way to mock it and keep it outside as it is? Thanks @chepner – Nacho Mar 10 '23 at 18:49
  • If it's outside the function, it gets executed while the module is defined, which means you would need to mock `storage` *before* you import `my_func`. – chepner Mar 10 '23 at 18:55
  • Thanks chepner, I've just done that and it works! I followed the code in this other issue https://stackoverflow.com/questions/59394471/mock-global-function-call-while-importing – Nacho Mar 13 '23 at 09:38

0 Answers0