1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
|
import inspect
import sys
import pytest
from makefun.main import is_identifier
try: # python 3.3+
from inspect import signature, Signature, Parameter
except ImportError:
from funcsigs import signature, Signature, Parameter
from makefun import wraps, with_signature, partial, create_function
def test_wraps_varpositional_issue_34():
""" test for https://github.com/smarie/python-makefun/issues/34 """
def f(a, *args):
return a, args
@wraps(f)
def foo(*args, **kwargs):
return f(*args, **kwargs)
assert foo('hello', 12) == ("hello", (12,))
def test_varpositional2():
""" test for https://github.com/smarie/python-makefun/issues/38 """
@with_signature("(a, *args)")
def foo(a, *args):
assert a == 'hello'
assert args == (12, )
foo('hello', 12)
def test_invalid_signature_str():
"""Test for https://github.com/smarie/python-makefun/issues/36"""
sig = "(a):"
@with_signature(sig)
def foo(a):
pass
@pytest.mark.skipif(sys.version_info < (3, 0), reason="type hints are not allowed with this syntax in python 2")
def test_invalid_signature_str_py3():
"""Test for https://github.com/smarie/python-makefun/issues/36"""
sig = "(a) -> int:"
@with_signature(sig)
def foo(a):
pass
def test_return_annotation_in_py2():
"""Test for https://github.com/smarie/python-makefun/issues/39"""
def f():
pass
f.__annotations__ = {'return': None}
@wraps(f)
def b():
pass
b()
def test_init_replaced():
class Foo(object):
@with_signature("(self, a)")
def __init__(self, *args, **kwargs):
pass
f = Foo(1)
class Bar(Foo):
def __init__(self, *args, **kwargs):
super(Bar, self).__init__(*args, **kwargs)
b = Bar(2)
def test_issue_55():
"""Tests that no syntax error appears when no arguments are provided in the signature (name change scenario)"""
# full name change including stack trace
@with_signature('bar()')
def foo():
return 'a'
assert "bar at" in repr(foo)
assert foo.__name__ == 'bar'
assert foo() == 'a'
# only metadata change
@with_signature(None, func_name='bar')
def foo():
return 'a'
if sys.version_info >= (3, 0):
assert "foo at" in repr(foo)
assert foo.__name__ == 'bar'
assert foo() == 'a'
def test_partial_noargs():
""" Fixes https://github.com/smarie/python-makefun/issues/59 """
def foo():
pass
foo._mark = True
g = partial(foo)
assert g._mark is True
def test_wraps_dict():
"""Checks that @wraps correctly propagates the __dict__"""
def foo():
pass
foo._mark = True
@wraps(foo)
def g():
pass
assert g._mark is True
def test_issue_62():
"""https://github.com/smarie/python-makefun/issues/62"""
def f(a, b):
return a+b
fp = partial(f, 0)
assert fp(-1) == -1
def test_issue_63():
"""https://github.com/smarie/python-makefun/issues/63"""
def a(foo=float("inf")):
pass
@with_signature(signature(a))
def test(*args, **kwargs):
return a(*args, **kwargs)
def test_issue_66():
"""Chain of @wraps with sig mod https://github.com/smarie/python-makefun/issues/66"""
def a(foo):
return foo + 1
assert a(1) == 2
# create a first wrapper that is signature-preserving
@wraps(a)
def wrapper(foo):
return a(foo) - 1
assert wrapper(1) == 1
# the __wrapped__ attr is here:
assert wrapper.__wrapped__ is a
# create a second wrapper that is not signature-preserving
@wraps(wrapper, append_args="bar")
def second_wrapper(foo, bar):
return wrapper(foo) + bar
assert second_wrapper.__wrapped__ is wrapper
assert "bar" in signature(second_wrapper).parameters
assert second_wrapper(1, -1) == 0
def test_issue_pr_67():
"""Test handcrafted for https://github.com/smarie/python-makefun/pull/67"""
class CustomException(Exception):
pass
class Foo(object):
def __init__(self, a=None):
if a is None:
raise CustomException()
def __repr__(self):
# this is a valid string but calling eval on it will raise an
return "Foo()"
f = Foo(a=1)
# (1) The object can be represented but for some reason its repr can not be evaluated
with pytest.raises(CustomException):
eval(repr(f))
# (2) Lets check that this problem does not impact `makefun`
def foo(a=Foo(a=1)):
pass
@wraps(foo, prepend_args="r")
def bar(*args, **kwargs):
pass
bar(1)
def test_issue_76():
def f(a):
return a + 1
f2 = create_function("zoo(a)", f, func=f)
assert f2(3) == 4
@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires python 3.6 or higher (async generator)")
def test_issue_77_async_generator_wraps():
import asyncio
from ._test_py36 import make_async_generator, make_async_generator_wrapper
f = make_async_generator()
wrapper = wraps(f)(make_async_generator_wrapper(f))
assert inspect.isasyncgenfunction(f)
assert inspect.isasyncgenfunction(wrapper)
assert asyncio.get_event_loop().run_until_complete(asyncio.ensure_future(wrapper(1).__anext__())) == 1
@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires python 3.6 or higher (async generator)")
def test_issue_77_async_generator_partial():
import asyncio
from ._test_py36 import make_async_generator
f = make_async_generator()
f_partial = partial(f, v=1)
assert inspect.isasyncgenfunction(f)
assert inspect.isasyncgenfunction(f_partial)
assert asyncio.get_event_loop().run_until_complete(asyncio.ensure_future(f_partial().__anext__())) == 1
@pytest.mark.skipif(sys.version_info < (3, 7, 6), reason="The __wrapped__ behavior in get_type_hints being tested was not added until python 3.7.6.")
def test_issue_85_wrapped_forwardref_annotation():
import typing
from . import _issue_85_module
@wraps(_issue_85_module.forwardref_method, remove_args=["bar"])
def wrapper(**kwargs):
kwargs["bar"] = "x" # python 2 syntax to prevent syntax error.
return _issue_85_module.forwardref_method(**kwargs)
# Make sure the wrapper function works as expected
assert wrapper(_issue_85_module.ForwardRef()).x == "defaultx"
# Check that the type hints of the wrapper are ok with the forward reference correctly resolved
expected_annotations = {
"foo": _issue_85_module.ForwardRef,
"return": _issue_85_module.ForwardRef,
}
assert typing.get_type_hints(wrapper) == expected_annotations
def test_issue_91():
"""This test should work also in python 2 ! """
assert is_identifier("_results_bag")
assert is_identifier("hello__bag")
def test_issue_98():
class A(str):
def __str__(self):
return 'custom str'
def __repr__(self):
return 'custom repr'
def foo(a=A()):
pass
@wraps(foo)
def test(*args, **kwargs):
return foo(*args, **kwargs)
|