Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception statement not covered by self.assertRaises in python unit test cases

This is my function:

def get_value(request, param):
  s = get_string(request, param)
  value = re.search('(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)', s)
  if not value:
    print 'match not found!'  
    raise Exception('incorrect format: %s' % param)

test function:

def test_get_value(self):
    m = test_mocks.HttpRequestMock(REQUEST = {'start_date': '2011.07.31'})
    print '*************************'
    print 'date format changed'
    self.assertRaises(Exception, get_value, (m, 'start_date'))
    print '*********************

get_value doesn't print: match not found!

like image 347
Prashant Kumar Avatar asked Oct 15 '12 04:10

Prashant Kumar


People also ask

How do you assert no exception is thrown in Python?

And here's how you assert no exception is raised. Solution: Enclose your code in a try/except block and and if the code raises, you can catch it and print a nice message. pytest is smart enough to make the test fail even if you don't catch it but having a message makes your test cleaner.

Which item in Python will stop a unit test abruptly assertion failures?

Python testing framework uses Python's built-in assert() function which tests a particular condition. If the assertion fails, an AssertionError will be raised. The testing framework will then identify the test as Failure. Other exceptions are treated as Error.

Which unittest Testcase assert function can be used to check whether the correct exception is raised by your code?

The crux of each test is a call to assertEqual() to check for an expected result; assertTrue() or assertFalse() to verify a condition; or assertRaises() to verify that a specific exception gets raised.


1 Answers

It seems there is some issue with your python version. I guess you are using python below version 2.6. Try passing function parameters as other arguments to function i.e. do not put them inside tuple. Try this.

self.assertRaises(Exception, helpers.get_value, m, 'start_date')
like image 98
asandeep Avatar answered Oct 08 '22 20:10

asandeep