1、第一题,使用pytest编写测试类
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
return None
return self.items.pop()
def peek(self):
if self.is_empty():
return None
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
答案:
import pytest
from python1.review.stack import Stack
@pytest.fixture
def empty_stack():
return Stack()
@pytest.fixture
def stack_with_items():
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
return stack
def test_push(empty_stack):
empty_stack.push(1)
assert empty_stack.peek() == 1
def test_pop(stack_with_items):
assert stack_with_items.pop() == 3
assert stack_with_items.pop() == 2
def test_peek(stack_with_items):
assert stack_with_items.peek() == 3
def test_is_empty(empty_stack):
assert empty_stack.is_empty() == True
empty_stack.push(1)
assert empty_stack.is_empty() == False
if __name__ == '__main__':
pytest.main()
或:
import pytest
from review.stack import Stack
def test_push():
s = Stack()
assert s.push(None) == s.pop()
def test_pop():
s = Stack()
s.push(1)
assert s.pop() == 1
s.push(2)
assert s.pop() == 2
s.push(3)
assert s.pop() == 3
def test_peek():
s = Stack()
s.push(3)
assert s.peek() == 3
def test_is_empty():
s = Stack()
assert s.is_empty() == True
s.push(5)
assert s.is_empty() == False
if __name__ == '__main__':
pytest.main()
# import pytest
#
# from review.stack import Stack
#
#
# @pytest.fixture
# def empty_stack():
# return Stack()
#
# @pytest.fixture
# def stack_with_items():
# stack = Stack()
# stack.push(1)
# stack.push(2)
# stack.push(3)
# return stack
#
# def test_push(empty_stack):
# empty_stack.push(1)
# assert empty_stack.peek() == 1
#
# def test_pop(stack_with_items):
# assert stack_with_items.pop() == 3
# assert stack_with_items.pop() == 2
#
# def test_peek(stack_with_items):
# assert stack_with_items.peek() == 3
#
# def test_is_empty(empty_stack):
# assert empty_stack.is_empty() == True
# empty_stack.push(1)
# assert empty_stack.is_empty() == False
#
# if __name__ == '__main__':
# pytest.main()