简体   繁体   中英

How to test exception from imported function using Python pytest?

How can I test exception from imported function by using pytest ? For example, in main file.py I have :

def function():
  if 3 != 3:
    raise Exception("Error")

in testfile.py I have :

import sys
import os
sys.path.insert(0, '..//main/')
import file

def test_exception():
    file.function()
   # need to test exception here

You can use pytest.raises like so:

def test_exception():
    with pytest.raises(SomeExceptionClass) as e:
        file.function()
    assert "Some informative error message" in str(e.value)

Where SomeExceptionClass would be the specific error you expect to occur. This will raise an assertion error if the function does not raise an error (or if it raises a different error type).

you can do in this way:

import sys
import os

def function():
  raise Exception("Error")




def test_exception():
  try:
    function()
  except Exception as e:
    print(e)

test_exception()

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