diff --git a/README.md b/README.md index 76fbaeb..cad24fe 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ This should work with Python 2.6 and 2.7, and [pypy](http://pypy.org). Currently I've only tested this with urllib2, urllib3, and requests. It's known to *NOT WORK* with urllib. -##How to use it +##Usage ```python import vcr import urllib2 @@ -40,6 +40,17 @@ pass, even if you are offline, or iana.org goes down for maintenance) and accurate (the response will contain the same headers and body you get from a real request). +You can also use VCR.py as a decorator. The same request above would look like this: + +``` +@vcr.use_cassette('fixtures/vcr_cassettes/synopsis.yaml'): +def test_iana(): + response = urllib2.urlopen('http://www.iana.org/domains/reserved').read() + assert 'Example domains' in response +``` + +All of the parameters and configuration works the same for the decorator version. + ## Configuration If you don't like VCR's defaults, you can set options by instantiating a diff --git a/setup.py b/setup.py index 697a6af..eb7bb41 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ setup(name='vcrpy', 'vcr.compat': 'vcr/compat', 'vcr.persisters': 'vcr/persisters', }, - install_requires=['PyYAML'], + install_requires=['PyYAML','contextdecorator'], license='MIT', tests_require=['pytest','mock'], cmdclass={'test': PyTest}, diff --git a/tests/integration/test_urllib2.py b/tests/integration/test_urllib2.py index d0e66c0..5db1b63 100644 --- a/tests/integration/test_urllib2.py +++ b/tests/integration/test_urllib2.py @@ -114,3 +114,17 @@ def test_cross_scheme(tmpdir): urllib2.urlopen('http://httpbin.org/') assert len(cass) == 2 assert cass.play_count == 0 + +def test_decorator(scheme, tmpdir): + '''Test the decorator version of VCR.py''' + url = scheme + '://httpbin.org/' + + @vcr.use_cassette(str(tmpdir.join('atts.yaml'))) + def inner1(): + return urllib2.urlopen(url).getcode() + + @vcr.use_cassette(str(tmpdir.join('atts.yaml'))) + def inner2(): + return urllib2.urlopen(url).getcode() + + assert inner1() == inner2() diff --git a/vcr/cassette.py b/vcr/cassette.py index e478082..37dedfb 100644 --- a/vcr/cassette.py +++ b/vcr/cassette.py @@ -6,6 +6,8 @@ except ImportError: from .compat.counter import Counter from .compat.ordereddict import OrderedDict +from contextdecorator import ContextDecorator + # Internal imports from .patch import install, reset from .persist import load_cassette, save_cassette @@ -13,7 +15,7 @@ from .serializers import yamlserializer from .matchers import requests_match, url, method -class Cassette(object): +class Cassette(ContextDecorator): '''A container for recorded requests and responses''' @classmethod