Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a few problems.</p> <p>First of all, the way you're using <code>mock.patch</code> isn't quite right. When used as a decorator, it replaces the given function/class (in this case, <code>datetime.date.today</code>) with a <code>Mock</code> object <em>only within the decorated function</em>. So, only within your <code>today()</code> will <code>datetime.date.today</code> be a different function, which doesn't appear to be what you want.</p> <p>What you really want seems to be more like this:</p> <pre><code>@mock.patch('datetime.date.today') def test(): datetime.date.today.return_value = date(2010, 1, 1) print datetime.date.today() </code></pre> <p>Unfortunately, this won't work:</p> <pre><code>&gt;&gt;&gt; test() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "build/bdist.macosx-10.6-universal/egg/mock.py", line 557, in patched File "build/bdist.macosx-10.6-universal/egg/mock.py", line 620, in __enter__ TypeError: can't set attributes of built-in/extension type 'datetime.date' </code></pre> <p>This fails because Python built-in types are immutable - see <a href="https://stackoverflow.com/questions/192649/can-you-monkey-patch-methods-on-core-types-in-python/192857#192857">this answer</a> for more details.</p> <p>In this case, I would subclass datetime.date myself and create the right function:</p> <pre><code>import datetime class NewDate(datetime.date): @classmethod def today(cls): return cls(2010, 1, 1) datetime.date = NewDate </code></pre> <p>And now you could do:</p> <pre><code>&gt;&gt;&gt; datetime.date.today() NewDate(2010, 1, 1) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload