title: ResourceWarning: unclosed file <_io.BufferedReader name=4>
body: <p>Consider the following program:</p>
  
  <pre><code>import tempfile
  import unittest
  import subprocess
  
  def my_fn(f):
      p = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=f)
      yield p.stdout.readline()
      p.kill()
      p.wait()
  
  def my_test():
      with tempfile.TemporaryFile() as f:
          l = list(my_fn(f))
  
  class BuggyTestCase(unittest.TestCase):
      def test_my_fn(self):
          my_test()
  
  my_test()
  unittest.main()
  </code></pre>
  
  <p>Running it results in the following output:</p>
  
  <pre><code>a.py:13: ResourceWarning: unclosed file &lt;_io.BufferedReader name=4&gt;
    l = list(my_fn(f))
  ResourceWarning: Enable tracemalloc to get the object allocation traceback
  .
  ----------------------------------------------------------------------
  Ran 1 test in 0.005s
  
  OK
  </code></pre>
  
  <p>What is the actual cause of the warning and how to fix it? Note that if I comment out <code>unittest.main()</code> the problem disappears, which means that it's specific to subprocess+unittest+tempfile.</p>