title: How to use logging, pytest fixture and capsys?
body: <p>I am trying to unit-test some algorithm that uses logging library.</p>
  
  <p>I have a fixture that creates a logger.</p>
  
  <p>In my <strong>1st test case</strong>, I do not use this fixture and uses a print to log to stdout. This test case <strong>passes</strong>.</p>
  
  <p>In my <strong>2nd test case</strong>, I use this fixture, but not as documented in pytest doc. I just call the associated function in my test to get the logger. Then I use the logger to log to stdout. This test case <strong>passes</strong>.</p>
  
  <p>In my <strong>3rd test case</strong>, I use this fixture as documented in pytest doc. The fixture is passed as an argument to the test function. Then I use the logger to log to stdout. This test case <strong>fails</strong>! It does not find anything in stdout. But in the error message, it says that my log is in the captured stdout call.</p>
  
  <p>What am I doing wrong?</p>
  
  <pre><code>import pytest
  
  import logging
  import sys
  
  @pytest.fixture()
  def logger():
  
      logger = logging.getLogger('Some.Logger')
      logger.setLevel(logging.INFO)
      stdout = logging.StreamHandler(sys.stdout)
      logger.addHandler(stdout)
  
      return logger
  
  def test_print(capsys):
  
      print 'Bouyaka!'
  
      stdout, stderr = capsys.readouterr()
      assert 'Bouyaka!' in stdout
  
      # passes
  
  def test_logger_without_fixture(capsys):
  
      logger().info('Bouyaka!')
  
      stdout, stderr = capsys.readouterr()
      assert 'Bouyaka!' in stdout
  
      # passes
  
  def test_logger_with_fixture(logger, capsys):
  
      logger.info('Bouyaka!')
  
      stdout, stderr = capsys.readouterr()
      assert 'Bouyaka!' in stdout
  
      # fails with this error:
      # &gt;       assert 'Bouyaka!' in stdout
      # E       assert 'Bouyaka!' in ''
      #
      # tests/test_logging.py:21: AssertionError
      # ---- Captured stdout call ----
      # Bouyaka!
  </code></pre>
  
  <p>There is no change if I reorder the test cases by the way.</p>