0

I am trying to do exception unit test for check_name() function but create_list() is also called. Is there any way I can mock the output of create_list() instead of executing it?

def create_list(token):
   return service_list


def check_name(token, name):

   response = create_list(token)
   existed_list = [app.name for app in response.details]

   if name in existed_list:
      raise NameExists()

I tried this but it still called create_list()

def test_exception_existed_name(self):
    existed_list = [ "p", "r", "g", "x"]
    with pytest.raises(NameExists):
        check_name(token,  "g")

check_name() and create_list() in sp.py

project 
│
└───src
│   └───sp_api
│           └───api
│               sp.py
│   
└───tests
       test_sp.py
Duc Vu
  • 71
  • 6

1 Answers1

0

You didn't mock create_list; you just created a variable named existed_list in a scope that check_name wouldn't look in even if existed_list weren't defined. You need to use something like unittest.mock.patch

def test_exception_existed_name(self):
    with pytest.raises(NameExists):
        with unittest.mock.patch('create_list', return_value=["p", "r", "g", "x"]):
             check_name(token, "g")

(Depending on where your test is actually defined, you may need to adjust the name you are patching; see https://docs.python.org/3/library/unittest.mock.html#where-to-patch)

(I believe pytest itself also provides facilities for patching things without using unittest.mock.patch directly, but I am not familiar with them.)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I want to clarify that the output of `create_list()` is a json response and `existed_list` is obtained from a json file. Is there any way I can get the list after mocking the `create_list` ? – Duc Vu Jun 17 '22 at 20:42
  • Fixed the call to `patch` to make `create_list` something that *returns* a specific value when called, rather than making `create_list` the returned value itself. That was just a dumb mistake on my part. – chepner Jun 17 '22 at 20:48
  • I still got the error `TypeError: Need a valid target to patch. You supplied: 'create_list'` – Duc Vu Jun 17 '22 at 20:58
  • That's why I referred you to the "where to patch" page. There is not enough information in your question to determine the correct name to patch. – chepner Jun 17 '22 at 21:03
  • I changed to `with unittest.mock.patch('sp.create_list', return_value=["p", "r", "g", "x"])` but it `ModuleNotFoundError: No module named 'sp'` – Duc Vu Jun 17 '22 at 21:22