Sams's Surf Shop

Hi,
Does anyone know why the ‘self.cart = surfshop.ShoppingCart()’ must be placed in the last row of subTest? I thought we always have to assign variable in the beginning of a function but kept getting error message in this case until looking at the solution. :frowning:

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

Hi, welcome to the forums.

It’d be worth linking the lesson and pointing out what task/instruction you’re working on, you’ll have a much better chance at getting an answer if other users know what you’re referring to. If you’re posting snippets of code to the forums, How do I format code in my posts? is also very helpful as the indentation gets lost otherwise which is less than ideal for most languages and terrible for Python.

As for the question I’m assuming self.cart has already been assigned before this function is called. Is the additional statement simply a quick attempt to remove/reset the contents of self.cart so as to undo any changes you made in the previous test?

Hi,

It was my first time posting a question, thank you for the feedback. :slight_smile:

Step 4 and 5 ask that we create test for each input and then step 10 using subTest. Either way, I noticed ‘self.cart = surfshop.ShoppingCart()’ have to be placed in the end of the ’ def test_add_surfboards’. If I placed the code in the beginning, it gives an error.

Here’s the code and the link:

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

Learn Intermediate Python 3 | Codecademy

1 Like

Ah, this is under the context of limiting the number of surfboards purchased, is that right? A subTest is really for minor changes, each subTest won’t be affected by the setUp (it’s run once for the test function only) so after a couple of iterations self.cart.num_surfboards == ?

If you don’t want to create entirely new instances you could carefully undo your changes in adding surfboards (but managing state for tests can be a pain).