Skip to content

Commit

Permalink
better tests for bytecode versioning
Browse files Browse the repository at this point in the history
this time comparing original code objects on the raw functions
  • Loading branch information
tkaemming committed Apr 20, 2012
1 parent be20060 commit b47e505
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions tests.py
Expand Up @@ -34,11 +34,11 @@ def test_backend():
"""
Test basic cache backend interface compatibility.
"""
@autocache.cached(backend=cache)
def foo(x):
def original_foo(x):
foo.counter += 1
return x ** x

foo = autocache.cached(backend=cache)(original_foo)
foo.counter = 0

# The cache should be empty.
Expand All @@ -65,11 +65,11 @@ def foo(x):
assert len(cache.values) == 2
assert foo.counter == 2

@autocache.cached(backend=cache)
def bar(x):
def original_bar(x):
bar.counter += 1
return x ** (x + 1)

bar = autocache.cached(backend=cache)(original_bar)
bar.counter = 0

bar(1)
Expand All @@ -80,6 +80,30 @@ def bar(x):
assert len(cache.values) == 4
assert bar.counter == 2

# Now, define a function that will compile to the same bytecode as `foo`...

def original_baz(x):
baz.counter += 1
return x ** x

baz = autocache.cached(backend=cache)(original_baz)
baz.counter = 0

assert original_baz.func_code.co_code == original_foo.func_code.co_code
assert original_baz.func_code.co_code != original_bar.func_code.co_code

# The cache will not grow, since the method signature and the bytecode are
# identical, and it will actually use the cached value from `foo`!

# This also demonstrates that the function really should have no side
# effects if you're going to be caching the result value, and that the
# function should also not be dependent on external state to calculate it's
# result.

baz(1)
assert baz.counter == 0
assert len(cache.values) == 4


@with_setup(cache.clear)
def test_bytecode_versioning():
Expand Down

0 comments on commit b47e505

Please sign in to comment.