Stack.py
class Stack:
def __init__(self, size = 10):
self._content = [] #使用列表存放栈的元素
self._size = size #初始栈大小
self._current = 0 #栈中元素个数初始化为0 def empty(self):
self._content = []
self._current = 0 def isEmpty(self):
if not self._content:
return True
else:
return False def setSize(self, size):
#如果缩小栈空间,则删除指定大小之后的已有元素
if size < self._current:
for i in range(size, self._current)[::-1]:
del self._content[i]
self._current = size
self._size = size def isFull(self):
if self._current == self._size:
return True
else:
return False def push(self, v):
if len(self._content) < self._size:
self._content.append(v)
self._current = self._current+1 #栈中元素个数加1
else:
print('Stack Full!') def pop(self):
if self._content:
self._current = self._current-1 #栈中元素个数减1
return self._content.pop()
else:
print('Stack is empty!') def show(self):
print(self._content) def showRemainderSpace(self):
print('Stack can still PUSH ', self._size-self._current, ' elements.') if __name__ == '__main__':
print('Please use me as a module.')
单元测试:pTest.py
'''Python单元测试
*
1.软件测试对于保证软件质量非常重要,尤其是系统升级过程中对代码的改动不影响原有功能,是未来重构代码的信心保证。
2.几乎所有软件公司都有专门的测试团队来保证软件质量,但作为程序员,首先应该保证自己编写的代码准确无误地实现了预定功能,单元测试是保证模块质量的重要手段之一
**从软件工程角度来讲
3.白盒测试主要通过阅读程序代码来判断是否符合功能要求,对于复杂的业务逻辑白盒测试难度非常大,一般以黑盒测试为主,白盒测试为辅
4.黑盒测试不关系模块的内部实现方式,只关心其功能是否正确,通过精心设计一些测试用例检验模块的输入和输出是否正确来判断是否符合预定的功能需求
'''
#导入要测试的模块
import Stack
#Python单元测试标准库
import unittest
class TestStack(unittest.TestCase):
def setUp(self):
self.fp = open('sample.txt','a+') def tearDown(self):
self.fp.close() def test_isEmpty(self):
try:
s=Stack.Stack()
#确保函数返回结果为True
self.assertTrue(s.isEmpty())
self.fp.write('isEmpty passed\n')
except Exception as e:
self.fp.write('isEmpty failed\n') def test_isFull(self):
try:
s = Stack.Stack(3)
s.push(1)
s.push(2)
s.push(3)
self.assertTrue(s.isFull())
self.fp.write('isFull passed\n')
except Exception as e:
self.fp.write('isFull failed\n') def test_pushpop(self):
try:
s = Stack.Stack()
s.push(3)
#确保入栈后立刻出栈得到原来的元素
self.assertEqual(s.pop(),3)
s.push('a')
self.assertEqual(s.pop(),'a')
self.fp.write('push and pop passed\n')
except Exception as e:
self.fp.write('push or pop failed\n') def test_setSize(self):
try:
s = Stack.Stack(8)
for i in range(8):
s.push(i)
self.assertTrue(s.isFull())
#测试扩大栈空间是否正常工作
s.setSize(9)
s.push(8)
self.assertTrue(s.isFull())
self.assertEqual(s.pop(),3)
#测试缩小空间是否正常工作
s.setSize(4)
self.assertEqual(s.pop(),3)
self.fp.write('setSize passed\n')
except Exception as e:
self.fp.write('setSize failed\n')
if __name__ == '__main__':
unittest.main()
'''
输出
....
----------------------------------------------------------------------
Ran 4 tests in 0.023s OK
'''