[py-dev] Advanced monkeypatching?

Virgil Dupras hsoft at hardcoded.net
Mon Dec 20 09:22:27 CET 2010

On 2010-12-19, at 3:38 PM, Floris Bruynooghe wrote:

> Hello
> On 18 December 2010 14:51, Virgil Dupras <hsoft at hardcoded.net> wrote:
>> Hi there,
>> Monkeypatching is great and all, but some type of patching is a little bit more complex to do, such as patching the system time and patching os.stat for specific filenames. I have my own "homebrewed" solution for this, but I was wondering if such solution had their place in the monkeypatch module of pytest itself. Does it? Or should a "pytest-monkeypatch++" package be created?
>> The "homebrewed" code I'm talking about is at https://bitbucket.org/hsoft/hsutil/src/43014954c6a8/hsutil/testutil.py#cl-83 ( patch_osstat() and patch_today() ).
> Looking at the patch_osstat() it seems to me that it just fakes
> os.stat() for one specific path but uses the original in place
> otherwise.  This sounds like it could be just a specialised object
> used to patch with.  I can imagine the monkeypatch plugin to provide a
> funcarg which provides this functionality, e.g.:
> def test_foo(monkeypatch, monkey_osstat):
>    monkeypatch.setattr(monkey_ossstat('/tmp/some_file'))
>    ...
> Though probably with better names ;-).
> I'm not sure I understand the use case for patch_today() so won't
> comment on that part.
> Regards
> Floris
> -- 
> Debian GNU/Linux -- The Power of Freedom
> www.debian.org | www.gnu.org | www.kernel.org

This would kind of work, but it would become complicated to patch os.stat() for two or more files, wouldn't it?

As for patch_today(), I created it because when you want to patch the date for a test, you can't just patch datetime because there might be a function somewhere using time.time(), so you'll have inconsistent date patching. However, to patch time.time() to a datetime of your choice, you have to do some arithmetics, hence the patch_today() helper.

My question is: Does such helpers have their place in the official pytest package or should it be an external plugin?

Virgil Dupras

More information about the Pytest-dev mailing list