title: Python mock Patch os.environ and return value
body: <p>Unit testing conn() using mock:</p>
  <p>app.py</p>
  <pre class="lang-py prettyprint-override"><code>import mysql.connector
  import os, urlparse
  
  
  def conn():
      if &quot;DATABASE_URL&quot; in os.environ:
          url = urlparse(os.environ[&quot;DATABASE_URL&quot;])
          g.db = mysql.connector.connect(
              user=url.username,
              password=url.password,
              host=url.hostname,
              database=url.path[1:],
          )
      else:
          return &quot;Error&quot;
  
  </code></pre>
  <p>test.py</p>
  <pre class="lang-py prettyprint-override"><code>def test_conn(self):
      with patch(app.mysql.connector) as mock_mysql:
          with patch(app.os.environ) as mock_environ:
              con()
              mock_mysql.connect.assert_callled_with(&quot;credentials&quot;)
  </code></pre>
  <p>Error: <em>Assertion</em> <code>mock_mysql.connect.assert_called_with</code> is not called.</p>
  <p>which I believe it is because 'Database_url' is not in my patched <code>os.environ</code> and because of that test call is not made to mysql_mock.connect.</p>
  <p>Questions:</p>
  <ol>
  <li><p>What changes do I need to make this test code work?</p>
  </li>
  <li><p>Do I also have to patch <code>urlparse</code>?</p>
  </li>
  </ol>