title: Avoid repetition in tests when using Python's unittest subTest?
body: <p>I'm having trouble trying to come up with a elegant solution for this situation.</p>
  
  <p>Let's say I have a unittest in Python that will test several elements from an iterable. Since this iterable is costly to build in memory, I want to build it only once trough the <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.setUpClass" rel="nofollow noreferrer"><code>setUpClass</code></a> method. Then, in each test, I want to sequentially pass each element in the iterable to the test, which I can to using the <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.subTest" rel="nofollow noreferrer">context manager and the <code>subTest</code> method</a>. This is all fine.</p>
  
  <p>The following code is an example of a mock test case doing exactly what I've described:</p>
  
  <pre><code>import unittest
  
  class NumberTest(unittest.TestCase):
  
      @classmethod
      def setUpClass(cls):
          cls.numbers = []
          for x in range(1000):
              cls.numbers.append(x)
  
      @classmethod
      def tearDownClass(cls):
          del cls.numbers
  
      def test_number_is_even(self):
          for n in self.numbers:
              with self.subTest(current_number=n):
                  self.assertEqual(n % 2, 0)
  
      def test_number_is_odd(self):
          for n in self.numbers:
              with self.subTest(current_number=n):
                  self.assertEqual(n % 2, 1)
  
      def test_number_is_positive(self):
          for n in self.numbers:
              with self.subTest(current_number=n):
                  self.assertTrue(n &gt; 0)
  
      def test_number_is_negative(self):
          for n in self.numbers:
              with self.subTest(current_number=n):
                  self.assertTrue(n &lt; 0)
  
  
  if __name__ == '__main__':
      unittest.main()
  </code></pre>
  
  <p>What bugs me here is that the lines <code>for n in self.numbers: with self.subTest(current_number=n): . . .</code> are repeated for each test method. Is there any way to avoid this? I know I could simply clump all <code>self.assert</code> statements together in a single method, but this defeats the purpose of having different tests for different aspects in the first place.</p>
  
  <p>In my mind the "ideal" solution would be to, somehow, <code>yield</code> the values from the iterable (maybe through the <code>setUp</code> method? No clue) and pass these values to each test method before yielding the next one. but I have no idea how to actually do this, especially since it involves a context manager... Has anyone got any other solutions, or are there simply no workarounds for this? </p>