
Fill in
Fresh Shop Every Time
setUp: a fresh fixture for every test
If several tests need the same starting objects, build them in a
method named exactly setUp. unittest calls it before each test
method, so every test gets a brand-new copy. One test can't
break another by changing shared data. (tearDown runs after each
test, for cleanup.)
class TestBag(unittest.TestCase):
def setUp(self):
self.bag = ["rope"]
def test_add(self):
self.bag.append("oil")
self.assertEqual(len(self.bag), 2)
subTest: many cases, one test
Checking a table of inputs in a loop? Wrap each case in
with self.subTest(...). Without it, the first failing case stops
the loop. With it, every case runs and each failure is reported
separately, labelled with the values you passed:
for qty, expected in [(1, 4), (2, 8)]:
with self.subTest(qty=qty):
self.assertEqual(price(qty), expected)
Assignment
Replace each ___ so that:
- Each test gets a fresh
Shopfrom the fixture method. - After buying one rope (from 3), the stock check expects the right number.
- Each price case runs in its own sub-test.
Replace each ___ so that:
- Each test gets a fresh
Shopfrom the fixture method. - After buying one rope (from 3), the stock check expects the right number.
- Each price case runs in its own sub-test.
main.py Python sleeping
Press Run to try your code, then Check to test it.