diff --git a/cachecontrol/streaming_cache.py b/cachecontrol/streaming_cache.py index a4a34ac1..5056c271 100644 --- a/cachecontrol/streaming_cache.py +++ b/cachecontrol/streaming_cache.py @@ -51,6 +51,34 @@ def close(self): # to make it easier to use. +CACHE = [] + + +class ExampleCache: + class WriteHandle: + def write(self, b): + global CACHE + CACHE.append(b) + + def commit(self): + pass + + def close(self): + pass + + def open_read(self, key): + return io.BytesIO(CACHE.pop(0)) + + def open_write(self, key, expires=None): + return self.WriteHandle() + + def delete(self, key): + pass + + def close(self): + '''Cleanup any temporary files, database connections etc.''' + pass +''' # An example to use while prototyping class ExampleCache: # Why is ExampleCache.data not a dict[str, io.BytesIO]? @@ -88,3 +116,4 @@ def delete(self, key): def close(self): pass +''' diff --git a/tests/test_streaming_cache.py b/tests/test_streaming_cache.py new file mode 100644 index 00000000..12b386cd --- /dev/null +++ b/tests/test_streaming_cache.py @@ -0,0 +1,30 @@ +from contextlib import closing +from cachecontrol.streaming_cache import ExampleCache +import pytest + + +@pytest.mark.parametrize('v', [b'fizz', b'buzz']) +def test_read_returns_what_you_wrote(v): + with closing(ExampleCache()) as cache: + with closing(cache.open_write('foo')) as w: + w.write(v) + w.commit() + with closing(cache.open_read('foo')) as r: + got = r.read() + assert got == v + + +def test_cache_remembers_more_than_one_value(): + with closing(ExampleCache()) as cache: + with closing(cache.open_write('foo')) as w: + w.write(b'one') + w.commit() + with closing(cache.open_write('bar')) as w: + w.write(b'two') + w.commit() + with closing(cache.open_read('foo')) as r: + got = r.read() + assert got == b'one' + with closing(cache.open_read('bar')) as r: + got = r.read() + assert got == b'two'