8.56. unittest 模块 API 文档
8.56.1. API
8.56.1.1. class TestResult:
def __init__(self):...
def wasSuccessful(self):...
def __str__(self):...
8.56.1.2. class TestCase:
def assertEqual(self,x,y):...
def assertNotEqual(self,x,y):...
def assertLessEqual(self,x,y):...
def assertGreaterEqual(self,x,y):...
def assertTrue(self,x):...
def assertFalse(self,x):...
def assertIs(self,x,y):...
def assertIsNot(self,x,y):...
def assertIsNone(self,x):...
def assertIsNotNone(self,x):...
def assertIn(self,x,y):...
def assertNotIn(self,x,y):...
def do_run(self,suite_name,name):...
def run(self,result:TestResult,suite_name,stop_on_error=False):...
8.56.1.3. class TestSuite:
def __init__(self,name):...
def addTest(self,case):...
def run(self,result:TestResult,stop_on_error=False):...
8.56.1.4. class TextTestRunner:
def run(self,suite:TestSuite,stop_on_error=False):...
8.56.2. Examples
8.56.2.1. test2.py
import unittest
class TestUnittestAssertions(unittest.TestCase):
def testEqual(self):
print("in testEqual...")
self.assertEqual(0, 0)
def testTrue(self):
print("in testTrue...")
self.assertTrue(True)
def testFalse(self):
print("in testFalse...")
self.assertFalse(False)
def testFalse2(self):
print("in testFalse2...")
self.assertFalse(True)
suit = unittest.TestSuite("test1")
suit.addTest(TestUnittestAssertions())
runner = unittest.TextTestRunner()
res = runner.run(suit)
8.56.2.2. test1.py
import unittest
class TestUnittestAssertions(unittest.TestCase):
def testEqual(self):
print("in testEqual...")
self.assertEqual(0, 0)
def testTrue(self):
print("in testTrue...")
self.assertTrue(True)
def testFalse(self):
print("in testFalse...")
self.assertFalse(False)
suit = unittest.TestSuite("test1")
suit.addTest(TestUnittestAssertions())
runner = unittest.TextTestRunner()
res = runner.run(suit)
8.56.2.3. test3.py
import socket
import random
import unittest
class TestUnittestAssertions(unittest.TestCase):
def testSocket(self):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9999 + random.randint(0, 1000) + 1
print("port:", port)
server.bind((host, port))
server.listen(5)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
accept, addr = server.accept()
self.assertEqual(addr, "127.0.0.1")
print("recv from client: %s" % str(addr))
client.send("send test from client".encode())
print("server recv:", accept.recv(1024).decode())
accept.send("send test from server".encode())
print("client recv:", client.recv(1024).decode())
accept.close()
client.close()
server.close()
suit = unittest.TestSuite("test1")
suit.addTest(TestUnittestAssertions())
runner = unittest.TextTestRunner()
res = runner.run(suit)