david
david

Reputation: 6785

How to assert that an error is not raised with python unittest

So I am trying to import a module, and test methods from a class in that module.

Here is an example of a method.

def production_warning(self, targetenv):
    if targetenv == 'prdv':
        prodwarning1 = raw_input("WARNING: You are deploying to the production environment.  Are you sure you want to do this?   Y/N:  ").upper()
        if prodwarning1 == "N":
            sys.exit()
        prodwarning2 = raw_input("DEPLOYING TO PRDV, ARE YOU REALLY, REALLY SURE?  Y/N:  ").upper()
        if prodwarning2 == "N":
            sys.exit()
    else:
        return True

Here is an example of a test I am trying to write.

def production_warning():
    try:
        assert test.production_warning('prdv') is not errors
        assert test.validate_params('fakeenv') is errors
        print "Test Passed {0}/5: validate_params".format(counter)
        test_db_refresh()
    except:
        print "Test Failed {0}/5: validate_params".format(counter)
        test_db_refresh()

def db_refresh_prompt():
    # assert test.db_refresh_prompt() is not errors
    global counter
    counter += 1
    print "Test Passed {0}/5: db_refresh_prompt".format(counter)

production_warning()
db_refresh_prompt()
etc()

How do I check if an error is raised? At the end of the day I'm trying to run through all of these tests and for each function, if no exceptions are raised, print "Success". If an exception is raised, move on to the next test. People seem to keep pointing me in the direction of "calling your function will automatically raise an exception if there is one", but this will stop my test whenever an exception is thrown and I don't want that, I want to continue on to the next test.

I can work around this by doing:

def validate_params():
try:
    assert test.validate_params('hackenv-re', 'test.username') is not errors
    assert test.validate_params('fakeenv', 'test.username') is errors
    assert test.validate_params('hackevn-re', 'vagrant') is errors
    global counter
    counter += 1
    print "Test Passed {0}/5: validate_params".format(counter)
    test_db_refresh()
except:
    print "Test Failed {0}/5: validate_params".format(counter)
    test_db_refresh()

but it seems like that defeats the purpose of using unittest in the first place? I thought with unittest I can just assert if an exception is raised and it returns a T/F that I can do whatever I want with.

Hope that is enough information.

Based on many of the answers given, I'm assuming there is nothing built in to unittest where I can do assertRaise (I believe this is used in Django)

Upvotes: 2

Views: 11675

Answers (1)

Stop harming Monica
Stop harming Monica

Reputation: 12610

Asserting that the tested code does not raise exceptions comes for free, you don't need to write code for that.

Upvotes: 8

Related Questions