#encoding=utf-8
import unittest
from __builtin__ import str
import random
class MyClass(object):
@classmethod
def sum(cls,a,b):
return a+b
@classmethod
def div(cls,a,b):
return a/b
@classmethod
def return_None(cls):
return None
class MyTestCase(unittest.TestCase):
#验证a+b=sum
def test_assertEqual(self):
try:
a,b = 1,2
sum = 13
self.assertEqual(a + b,sum,'断言失败,%s + %s != %s'%(a,b,sum))
except AssertionError,e:
print e
#验证a-b!=res
def test_assertNotEqual(self):
try:
a,b = 5,2
res = 3
self.assertNotEqual(a - b,res,'断言失败,%s - %s = %s'%(a,b,res))
except AssertionError,e:
print e
#雅正a==b为真
def test_assertTrue(self):
try:
a,b = 1,2
self.assertTrue(a == b, '断言失败,%s != %s'%(a,b))
except AssertionError,e:
print e
#验证a==b为假
def test_assertFalse(self):
try:
a,b = 1,1
self.assertFalse(a == b,'断言失败,%s == %s'%(a,b))
except AssertionError,e:
print e
#验证a,b为同一对象
def test_assertIs(self):
try:
a = 1
b = 2
self.assertIs(a,b,'断言失败,%s与%s不属于同一对象'%(a,b))
except AssertionError,e:
print e
#验证a,b为不同对象
def test_assertIsNot(self):
try:
a = 1
b = a
self.assertIsNot(a,b,'断言失败,%s与%s属于同一对象'%(a,b))
except AssertionError,e:
print e
#判断表达式结果不为None
def test_assertIsNotNone(self):
try:
result = MyClass.return_None()
self.assertIsNotNone(result,'Is None')
except AssertionError,e:
print e
#判断表达式结果为None
def test_assertIsNone(self):
try:
result = MyClass.sum(1, 2)
self.assertIsNone(result,'断言失败,Not is None')
except AssertionError,e:
print e
#判断b in a
def test_assertIn(self):
try:
a = 'this is a test'
b = 'python'
self.assertIn(b,a,'断言失败,%s not in %s'%(b,a))
except AssertionError,e:
print e
#判断b not in a
def test_assertNotIn(self):
try:
a = 'this is a test'
b = 'is'
self.assertNotIn(b,a,'断言失败,%s in %s'%(b,a))
except AssertionError,e:
print e
#判断测试对象不为指定的类型
def test_assertNotIsInstance(self):
try:
x = MyClass
y = object
self.assertNotIsInstance(x,y,'%s 的类型是 %s'%(x,y))
except AssertionError,e:
print e
#判断测试对象为指定类型
def test_assertIsInstance(self):
try:
a = 123
b = str
self.assertIsInstance(a,b,'断言失败,%s 的类型不是%s'%(a,b))
except AssertionError,e:
print e
print 'a 的类型为',type(a)
def test_assertRaise(self):
#测试抛出指定的异常类型
with self.assertRaises(ValueError) as cm:
random.sample([1,2,3,4,5],'j')
print "==",cm.exception
try:
self.assertRaises(ZeroDivisionError, MyClass.div,3,0)
except AssertionError,e:
print e
#测试抛出的指定异常类型,并用正则表达式具体验证
def test_assertRaiseRegexp(self):
with self.assertRaisesRegexp(ValueError,'literal') as ar:
int('xyz')
print ar.exception
print ar.expected_regexp
try:
self.assertRaisesRegexp(ValueError, "invalid literal for. *XYZ'$", int,'XYZ')
except AssertionError,e:
print e
if __name__ == "__main__":
unittest.main()