In the test interface, there will be such a scenario, input illegal parameters, check the return error code and error content
The usual practice is to send a request, the wrong return result is taken out, and then the comparison match; but there is a problem that requires a further write error to return the parse function, which cannot be shared with the previously requested function.
At this time, we can use the assertraises, Assertraisesregexp;python 2.7 in UnitTest called Assertraises,nose.tools called Assert_raises, Assert_ Raises_regexp
First, the assertraises in UnitTest
Let's see the official note:
The above two methods can be used to assert exceptions and alarms.
Let's look at an example:
ImportUnitTestdefmode (dividend,divisor): Remainder= Dividend%Divisor quotient= (Dividend-remainder)/DividendreturnQuotient,remainderclassraisetest ():deftest_raise (self): self.assertraise (zerodivisionerror, mode,7, 0)defTest_raise_regexp (self): Self.assertraiseregexp (Zerodivisionerror, R'.*? Zero', mode,7, 0)if __name__=='__main__': Unittest.main ()
Note: The reference function inside is not with (), directly is mode
The exception name is also unquoted, if a custom exception is to be introduced first
Second, the assertraises in nose
Or the above code, instead of the nose way
#Coding:utf-8" "Created on January 4, 2018 @author:hu" " fromNose.toolsImportAssert_raises,assert_raises_regexpdefmode (dividend,divisor): Remainder= Dividend%Divisor quotient= (Dividend-remainder)/DividendreturnQuotient,remainderclassraisetest ():deftest_raise (self): assert_raises (zerodivisionerror, mode,7, 0)defTest_raise_regexp (self): Assert_raises_regexp (Zerodivisionerror, R'.*? Zero', mode,7,0)
The results of the implementation are consistent.
Three: Common usage in interface testing
Based on the above assertion, we can write directly in the underlying request encapsulation in the interface test like this:
def show_xxxxx (self, id): """ view Xxxx,id as a parameter """ "xxxx/%s"% str (volume_id) = Self.get (URL) = json.loads (body) self.expected_success (resp.status) return body
Where Expected_success is their own package, which encapsulates the wrong, here is not an example of
And then, when the anomaly is actually measured, it can be written like this.
def test_get_invalid_xxxxx_id (self): # Negative:should not being able to get xxxxx with invalid ID self.assertraises (your own definition of the error type ,'#$%%&^&^')
or use Assertraiseregexp to determine what's wrong.
This way, you can write a lot less code
The Python Nose test Framework provides a comprehensive overview of the assertion of illegal parameters in eight---interface tests