class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def tearDown(self): del self.stack def test_push_pop_peek(self): values = [10, 20, 30, 40, 50] for value in values: self.stack.push(value) self.assertEqual(len(values), self.stack.size()) values.reverse() for value in values: self.assertEqual(value, self.stack.peek()) self.assertEqual(value, self.stack.pop()) def test_pop(self): self.stack.push(10) self.assertEqual(1, self.stack.size()) self.assertEqual(10, self.stack.pop()) self.assertEqual(0, self.stack.size()) def test_peek(self): self.stack.push(10) self.assertEqual(1, self.stack.size()) self.assertEqual(10, self.stack.peek()) self.assertEqual(1, self.stack.size()) def test_pop_empty(self): self.assertIsNone(self.stack.pop()) def test_peek_empty(self): self.assertIsNone(self.stack.peek())
def test(): s = Stack() assert s.is_empty() is True s.push(4) assert s.items == [4] s.push("dog") assert s.items == [4, "dog"] assert s.peek() == "dog" s.push(True) assert s.items == [4, "dog", True] assert s.size() == 3 assert s.is_empty() is False s.push(8.4) assert s.items == [4, "dog", True, 8.4] assert s.pop() == 8.4 assert s.pop() is True assert s.size() == 2
class CalculatorTest(unittest.TestCase): """unitetestモジュールの簡単な実行例その2。""" @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): self._stack = Stack() def tearDown(self): pass def test_is_empty(self): self.assertTrue(self._stack.is_empty()) self._stack.push(1) self.assertFalse(self._stack.is_empty()) def test_size(self): self.assertEqual(0, self._stack.size()) self._stack.push(1) self.assertEqual(1, self._stack.size()) def test_push(self): self._stack.push(1) self.assertEqual(1, self._stack.top()) def test_pop(self): self._stack.push(1) self.assertEqual(1, self._stack.pop()) self.assertEqual(0, self._stack.size()) with self.assertRaises(IndexError): self._stack.pop() def test_top(self): self._stack.push(1) self.assertEqual(1, self._stack.top()) self.assertEqual(1, self._stack.size()) self._stack.pop() with self.assertRaises(IndexError): self._stack.top()
def test_size(self): # test if the size is being enforced stack = Stack(size=10) for num in range(1000): stack.push(num) assert stack.size() == 10 assert stack.stack == [_ for _ in range(10)]
def validate_brackets(sentence): brackets = Stack() for char in sentence: if char == '(': brackets.push(True) elif char == ')': if brackets.pop() is not True: return False return brackets.size() == 0
def test_stack_exceptions(self): with self.assertRaises(ValueError): s = Stack("A") with self.assertRaises(ValueError): s = Stack(10) s.size = "A" with self.assertRaises(ValueError): s = Stack(10) s.top = "A"