简体   繁体   中英

How to run exception Unit test for one function that calls another function inside of it

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM