Question on self.subtest

Hello, I have a quick question on the usage of unittests, specifically, the subtest method.

in the Sam’s surf shop exercise project (, step 10 tells us to parameterize a previous test.

# Write your code below:
import surfshop
import unittest

class SurfTest(unittest.TestCase):
  def setUp(self):
    self.cart = surfshop.ShoppingCart()

  def test_add_surfboards(self):
    for i in range(2,5):
      with self.subTest(i=i):
        test = self.cart.add_surfboards(i)
        self.assertEqual(test, f'Successfully added {i} surfboards to cart!')
        self.cart = surfshop.ShoppingCart()

  def test_add_surfboards_duo(self):
    test = self.cart.add_surfboards(2)
    self.assertEqual(test, 'Successfully added 2 surfboards to cart!')
  def test_TooManyBoardsError(self):
    test = surfshop.TooManyBoardsError
    self.assertRaises(test, self.cart.add_surfboards, 5)
  def test_discount(self):
    test = self.cart.apply_locals_discount()

The last line on the test_add_surfboard function, it seems that if I don’t have it, the tests returns errors. Why is declaring:
self.cart = surfshop.ShoppingCart()

…a requirement for the test?


I think we need to create a new instance of surfshop.ShoppingCart() in each subtest, because the setUp method is only executed before the test_* methods, but not before the subTest. So unless you create a new instance of ShoppingCart after completing the subtest, the number of surfboards in the cart will increase with each subtest, and you will get unexpected results.


So essentially, we don’t declare surfshop.ShoppingCart() for the other tests because those only iterates through the function once, meanwhile self.subTest() iterates through the function multiple times.

I’m just confused because I thought thats why we declared the setUp() method, because unittest.main() automatically refreshes each test so that the test environment is the same each time?