How to use get_function method in Testify

Best Python code snippet using Testify_python

test_stub.py

Source:test_stub.py Github

copy

Full Screen

1from pytest import raises2from io import StringIO3from pygenstub import get_stub4_INDENT = " " * 45def get_function(6 name, desc="Do foo.", params=None, ptypes=None, rtype=None, decorators=None, body="pass"7):8 code = StringIO()9 if decorators is not None:10 code.write("\n".join(decorators) + "\n")11 pstr = ", ".join(params) if params is not None else ""12 code.write("def %(name)s(%(p)s):\n" % {"name": name, "p": pstr})13 if desc:14 code.write(_INDENT + '"""%(desc)s\n\n' % {"desc": desc})15 tstr = ", ".join(ptypes) if ptypes is not None else ""16 if rtype is not None:17 code.write(_INDENT + ":sig: (%(t)s) -> %(rtype)s\n" % {"t": tstr, "rtype": rtype})18 code.write(_INDENT + '"""\n')19 code.write(_INDENT + body + "\n")20 return code.getvalue()21def get_class(name, bases=None, desc="A foo.", sig=None, methods=None, classvars=None):22 code = StringIO()23 bstr = ("(" + ", ".join(bases) + ")") if bases is not None else ""24 code.write("class %(name)s%(bases)s:\n" % {"name": name, "bases": bstr})25 if desc is not None:26 code.write(_INDENT + '"""%(desc)s\n\n' % {"desc": desc})27 if sig is not None:28 code.write("\n" + _INDENT + ":sig: %(sig)s\n" % {"sig": sig})29 code.write(_INDENT + '"""\n')30 if classvars is not None:31 for classvar in classvars:32 code.write(_INDENT + classvar + "\n")33 if methods is not None:34 for method in methods:35 for line in method.splitlines():36 code.write(_INDENT + line + "\n")37 else:38 code.write(_INDENT + "pass\n")39 return code.getvalue()40def test_if_no_docstring_then_stub_should_be_empty():41 code = get_function("f", desc="")42 assert get_stub(code) == ""43def test_if_no_sig_then_stub_should_be_empty():44 code = get_function("f")45 assert get_stub(code) == ""46def test_if_returns_none_then_stub_should_return_none():47 code = get_function("f", rtype="None")48 assert get_stub(code) == "def f() -> None: ...\n"49def test_if_returns_builtin_then_stub_should_return_builtin():50 code = get_function("f", rtype="int")51 assert get_stub(code) == "def f() -> int: ...\n"52def test_if_returns_from_imported_then_stub_should_include_import():53 code = "from x import A\n"54 code += "\n\n" + get_function("f", rtype="A")55 assert get_stub(code) == "from x import A\n\ndef f() -> A: ...\n"56def test_if_returns_from_as_imported_then_stub_should_include_import():57 code = "from x import A as B\n"58 code += "\n\n" + get_function("f", rtype="B")59 assert get_stub(code) == "from x import A as B\n\ndef f() -> B: ...\n"60def test_stub_should_exclude_unused_import():61 code = "from x import A, B\n"62 code += "\n\n" + get_function("f", rtype="A")63 assert get_stub(code) == "from x import A\n\ndef f() -> A: ...\n"64def test_if_returns_imported_qualified_then_stub_should_include_import():65 code = "import x\n"66 code += "\n\n" + get_function("f", rtype="x.A")67 assert get_stub(code) == "import x\n\ndef f() -> x.A: ...\n"68def test_if_returns_as_imported_qualified_then_stub_should_include_import():69 code = "import x as y\n"70 code += "\n\n" + get_function("f", rtype="y.A")71 assert get_stub(code) == "import x as y\n\ndef f() -> y.A: ...\n"72def test_if_returns_from_imported_qualified_then_stub_should_include_import():73 code = "from x import y\n"74 code += "\n\n" + get_function("f", rtype="y.A")75 assert get_stub(code) == "from x import y\n\ndef f() -> y.A: ...\n"76def test_if_returns_relative_imported_qualified_then_stub_should_include_import():77 code = "from . import x\n"78 code += "\n\n" + get_function("f", rtype="x.A")79 assert get_stub(code) == "from . import x\n\ndef f() -> x.A: ...\n"80def test_if_returns_unimported_qualified_then_stub_should_generate_import():81 code = get_function("f", rtype="x.y.A")82 assert get_stub(code) == "import x.y\n\ndef f() -> x.y.A: ...\n"83def test_if_returns_imported_typing_then_stub_should_include_import():84 code = "from typing import List\n"85 code += "\n\n" + get_function("f", rtype="List")86 assert get_stub(code) == "from typing import List\n\ndef f() -> List: ...\n"87def test_if_returns_unimported_typing_then_stub_should_generate_import():88 code = get_function("f", rtype="List")89 assert get_stub(code) == "from typing import List\n\ndef f() -> List: ...\n"90def test_if_returns_qualified_typing_then_stub_should_return_qualified_typing():91 code = get_function("f", rtype="List[str]")92 assert get_stub(code) == "from typing import List\n\ndef f() -> List[str]: ...\n"93def test_if_returns_multiple_typing_then_stub_should_generate_multiple_import():94 code = get_function("f", rtype="Dict[str, Any]")95 assert get_stub(code) == "from typing import Any, Dict\n\ndef f() -> Dict[str, Any]: ...\n"96def test_if_returns_unknown_type_should_raise_error():97 code = get_function("f", rtype="Foo")98 with raises(ValueError) as e:99 get_stub(code)100 assert "unresolved types: Foo" in str(e)101def test_if_one_param_then_stub_should_have_one_param():102 code = get_function("f", params=["i"], ptypes=["int"], rtype="None")103 assert get_stub(code) == "def f(i: int) -> None: ...\n"104def test_if_multiple_params_then_stub_should_have_multiple_params():105 code = get_function("f", params=["i", "s"], ptypes=["int", "str"], rtype="None")106 assert get_stub(code) == "def f(i: int, s: str) -> None: ...\n"107def test_if_param_type_imported_then_stub_should_include_import():108 code = "from x import A\n"109 code += "\n\n" + get_function("f", params=["a"], ptypes=["A"], rtype="None")110 assert get_stub(code) == "from x import A\n\ndef f(a: A) -> None: ...\n"111def test_if_param_type_from_imported_then_stub_should_include_import():112 code = "from x import A\n"113 code += "\n\n" + get_function("f", params=["a"], ptypes=["A"], rtype="None")114 assert get_stub(code) == "from x import A\n\ndef f(a: A) -> None: ...\n"115def test_if_param_type_imported_qualified_then_stub_should_include_import():116 code = "import x\n"117 code += "\n\n" + get_function("f", params=["a"], ptypes=["x.A"], rtype="None")118 assert get_stub(code) == "import x\n\ndef f(a: x.A) -> None: ...\n"119def test_if_param_type_from_imported_qualified_then_stub_should_include_import():120 code = "from x import y\n"121 code += get_function("f", params=["a"], ptypes=["y.A"], rtype="None")122 assert get_stub(code) == "from x import y\n\ndef f(a: y.A) -> None: ...\n"123def test_if_param_type_relative_imported_qualified_then_stub_should_include_import():124 code = "from . import x\n"125 code += "\n\n" + get_function("f", params=["a"], ptypes=["x.A"], rtype="None")126 assert get_stub(code) == "from . import x\n\ndef f(a: x.A) -> None: ...\n"127def test_if_param_type_unimported_qualified_then_stub_should_generate_import():128 code = get_function("f", params=["a"], ptypes=["x.y.A"], rtype="None")129 assert get_stub(code) == "import x.y\n\ndef f(a: x.y.A) -> None: ...\n"130def test_if_param_type_imported_typing_then_stub_should_include_import():131 code = "from typing import List\n"132 code += "\n\n" + get_function("f", params=["l"], ptypes=["List"], rtype="None")133 assert get_stub(code) == "from typing import List\n\ndef f(l: List) -> None: ...\n"134def test_if_param_type_unimported_typing_then_stub_should_include_import():135 code = get_function("f", params=["l"], ptypes=["List"], rtype="None")136 assert get_stub(code) == "from typing import List\n\ndef f(l: List) -> None: ...\n"137def test_if_param_type_qualified_typing_then_stub_should_include_qualified_typing():138 code = get_function("f", params=["ls"], ptypes=["List[str]"], rtype="None")139 assert get_stub(code) == "from typing import List\n\ndef f(ls: List[str]) -> None: ...\n"140def test_if_param_type_multiple_typing_then_stub_should_include_multiple_import():141 code = get_function("f", params=["d"], ptypes=["Dict[str, Any]"], rtype="None")142 assert (143 get_stub(code)144 == "from typing import Any, Dict\n\ndef f(d: Dict[str, Any]) -> None: ...\n"145 )146def test_if_param_type_unknown_should_raise_error():147 code = get_function("f", params=["i"], ptypes=["Foo"], rtype="None")148 with raises(ValueError) as e:149 get_stub(code)150 assert "unresolved types: Foo" in str(e)151def test_if_param_has_default_then_stub_should_include_ellipses():152 code = get_function("f", params=["i=0"], ptypes=["Optional[int]"], rtype="None")153 assert (154 get_stub(code)155 == "from typing import Optional\n\ndef f(i: Optional[int] = ...) -> None: ...\n"156 )157def test_stub_should_ignore_varargs_type():158 code = get_function("f", params=["i", "*args"], ptypes=["int"], rtype="None")159 assert get_stub(code) == "def f(i: int, *args) -> None: ...\n"160def test_stub_should_ignore_kwargs_type():161 code = get_function("f", params=["i", "**kwargs"], ptypes=["int"], rtype="None")162 assert get_stub(code) == "def f(i: int, **kwargs) -> None: ...\n"163def test_stub_should_ignore_vararg_and_kwargs_types():164 code = get_function("f", params=["i", "*args", "**kwargs"], ptypes=["int"], rtype="None")165 assert get_stub(code) == "def f(i: int, *args, **kwargs) -> None: ...\n"166def test_stub_should_honor_kwonly_args():167 code = get_function("f", params=["i", "*", "j"], ptypes=["int", "int"], rtype="None")168 assert get_stub(code) == "def f(i: int, *, j: int) -> None: ...\n"169def test_stub_should_honor_kwonly_args_with_default():170 code = get_function(171 "f", params=["i", "*", "j=0"], ptypes=["int", "Optional[int]"], rtype="None"172 )173 assert (174 get_stub(code)175 == "from typing import Optional\n\ndef f(i: int, *, j: Optional[int] = ...) -> None: ...\n" # noqa: E501176 )177def test_missing_types_should_raise_error():178 code = get_function("f", params=["i", "j"], ptypes=["int"], rtype="None")179 with raises(ValueError) as e:180 get_stub(code)181 assert "Parameter names and types don't match: " in str(e)182def test_extra_types_should_raise_error():183 code = get_function("f", params=["i"], ptypes=["int", "int"], rtype="None")184 with raises(ValueError) as e:185 get_stub(code)186 assert "Parameter names and types don't match: " in str(e)187def test_if_function_decorated_unknown_then_stub_should_ignore():188 code = get_function("f", rtype="None", decorators=["@foo"])189 assert get_stub(code) == "def f() -> None: ...\n"190def test_if_function_decorated_callable_unknown_then_stub_should_ignore():191 code = get_function("f", rtype="None", decorators=["@foo()"])192 assert get_stub(code) == "def f() -> None: ...\n"193def test_stub_should_include_empty_class():194 code = get_class("C")195 assert get_stub(code) == "class C: ...\n"196def test_method_stub_should_include_self():197 method = get_function("m", params=["self"], rtype="None")198 code = get_class("C", methods=[method])199 assert get_stub(code) == "class C:\n def m(self) -> None: ...\n"200def test_method_stub_should_include_params():201 method = get_function("m", params=["self", "i"], ptypes=["int"], rtype="None")202 code = get_class("C", methods=[method])203 assert get_stub(code) == "class C:\n def m(self, i: int) -> None: ...\n"204def test_if_base_builtin_then_stub_should_include_base():205 code = get_class("C", bases=["dict"])206 assert get_stub(code) == "class C(dict): ...\n"207def test_if_base_from_imported_then_stub_should_include_import():208 code = "from x import A\n"209 code += "\n\n" + get_class("C", bases=["A"])210 assert get_stub(code) == "from x import A\n\nclass C(A): ...\n"211def test_if_base_imported_qualified_then_stub_should_include_import():212 code = "import x\n"213 code += "\n\n" + get_class("C", bases=["x.A"])214 assert get_stub(code) == "import x\n\nclass C(x.A): ...\n"215def test_if_base_from_imported_qualified_then_stub_should_include_import():216 code = "from x import y\n"217 code += "\n\n" + get_class("C", bases=["y.A"])218 assert get_stub(code) == "from x import y\n\nclass C(y.A): ...\n"219def test_if_base_unimported_qualified_then_stub_should_generate_import():220 code = get_class("C", bases=["x.y.A"])221 assert get_stub(code) == "import x.y\n\nclass C(x.y.A): ...\n"222def test_if_base_relative_imported_qualified_then_stub_should_include_import():223 code = "from . import x\n"224 code += "\n\n" + get_class("C", bases=["x.A"])225 assert get_stub(code) == "from . import x\n\nclass C(x.A): ...\n"226def test_class_sig_should_be_moved_to_init_method():227 method = get_function("__init__", params=["self", "x"], rtype=None)228 code = get_class("C", sig="(str) -> int", methods=[method])229 assert get_stub(code) == "class C:\n def __init__(self, x: str) -> int: ...\n"230def test_class_sig_should_not_overwrite_existing_init_sig():231 method = get_function("__init__", params=["self", "x"], ptypes=["int"], rtype="None")232 code = get_class("C", sig="(str) -> int", methods=[method])233 assert get_stub(code) == "class C:\n def __init__(self, x: int) -> None: ...\n"234def test_if_method_decorated_unknown_then_stub_should_ignore():235 method = get_function("m", params=["self"], rtype="None", decorators=["@foo"])236 code = get_class("C", methods=[method])237 assert get_stub(code) == "class C:\n def m(self) -> None: ...\n"238def test_if_method_decorated_callable_unknown_then_stub_should_ignore():239 method = get_function("m", params=["self"], rtype="None", decorators=["@foo()"])240 code = get_class("C", methods=[method])241 assert get_stub(code) == "class C:\n def m(self) -> None: ...\n"242def test_if_method_decorated_staticmethod_then_stub_should_include_decorator():243 method = get_function("m", rtype="None", decorators=["@staticmethod"])244 code = get_class("C", methods=[method])245 assert get_stub(code) == "class C:\n @staticmethod\n def m() -> None: ...\n"246def test_if_method_decorated_classmethod_then_stub_should_include_decorator():247 method = get_function("m", params=["cls"], rtype="None", decorators=["@classmethod"])248 code = get_class("C", methods=[method])249 assert get_stub(code) == "class C:\n @classmethod\n def m(cls) -> None: ...\n"250def test_if_method_decorated_property_then_stub_should_include_decorator():251 method = get_function("m", params=["self"], rtype="None", decorators=["@property"])252 code = get_class("C", methods=[method])253 assert get_stub(code) == "class C:\n @property\n def m(self) -> None: ...\n"254def test_if_method_decorated_property_setter_then_stub_should_include_decorator():255 method = get_function("m", params=["self"], rtype="None", decorators=["@x.setter"])256 code = get_class("C", methods=[method])257 assert get_stub(code) == "class C:\n @x.setter\n def m(self) -> None: ...\n"258def test_module_variable_type_comment_builtin_should_not_be_ellipsized():259 code = "n = 42 # sig: int\n"260 assert get_stub(code) == "n: int\n"261def test_module_variable_type_comment_from_imported_should_include_import():262 code = "from x import A\n\nn = 42 # sig: A\n" ""263 assert get_stub(code) == "from x import A\n\nn: A\n"264def test_module_variable_type_comment_imported_qualified_should_include_import():265 code = "import x\n\nn = 42 # sig: x.A\n" ""266 assert get_stub(code) == "import x\n\nn: x.A\n"267def test_module_variable_type_comment_relative_qualified_should_include_import():268 code = "from . import x\n\nn = 42 # sig: x.A\n" ""269 assert get_stub(code) == "from . import x\n\nn: x.A\n"270def test_module_variable_type_comment_unimported_qualified_should_include_import():271 code = "n = 42 # sig: x.y.A\n" ""272 assert get_stub(code) == "import x.y\n\nn: x.y.A\n"273def test_get_stub_comment_class_variable():274 code = get_class("C", classvars=["a = 42 # sig: int"])275 assert get_stub(code) == "class C:\n a: int\n"276def test_get_stub_comment_instance_variable():277 method = get_function("m", params=["self"], rtype="None", body="self.a = 42 # sig: int")278 code = get_class("C", methods=[method])279 assert get_stub(code) == "class C:\n a: int\n def m(self) -> None: ...\n"280def test_stub_should_use_alias_comment():281 code = "# sigalias: B = int\n\nn = 42 # sig: B\n" ""282 assert get_stub(code) == "B = int\n\nn: B\n"283def test_stub_should_exclude_function_without_sig():284 code = get_function("f", rtype="None")285 code += "\n\n" + get_function("g", desc="")286 assert get_stub(code) == "def f() -> None: ...\n"287def test_get_stub_typing_import_should_come_first():288 code = "from x import A\n"289 code += "\n\n" + get_function("f", params=["a", "l"], ptypes=["A", "List"], rtype="None")290 assert (291 get_stub(code)292 == "from typing import List\n\nfrom x import A\n\ndef f(a: A, l: List) -> None: ...\n"...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

2from operator import add, gt3from core import *4def test_binary_function():5 expr = "(def (fun x y) (add x y))"6 fun = get_function(expr, "fun")7 assert fun(4, 3) == 78def test_multiline_function():9 expr = "(def (fun x y) (def a (add y x)) (add a 1))"10 fun = get_function(expr, "fun")11 assert fun(4, 3) == 812def test_multiple_function():13 expr = """(def (fun1 x y) (add x y))14 (def (fun2 x) (add x x))"""15 fun1 = get_function(expr, "fun1")16 fun2 = get_function(expr, "fun2")17 assert fun1(4, 3) == 718 assert fun2(5) == 1019def test_if_else():20 expr = "(def (fun x y) (if (gt x y) x y))"21 fun = get_function(expr, "fun")22 assert fun(4, 3) == 423 assert fun(8, 10) == 1024def test_grad_add():25 expr = """(def (f x y) (pow x y))26 (def df (grad f 0))"""27 df = get_function(expr, "df")28 assert np.allclose(df(3.0, 4), 108.0)29def test_grad_sin():30 expr = """(def (f x) (np.sin x))31 (def df (grad f 0))"""32 df = get_function(expr, "df")33 assert np.allclose(df(np.pi/3), 0.5)34def test_grad_fanout():35 expr = """(def (f x) (add (np.sin x) (np.sin x)))36 (def df (grad f 0))"""37 df = get_function(expr, "df")38 assert np.allclose(df(np.pi/3), 1.0)39def test_grad_const():40 expr = """(def (f x) 1)41 (def df (grad f 0))"""42 df = get_function(expr, "df")43 assert np.allclose(df(2.0), 0.0)44def test_grad_exp():45 expr = """(def (f x) (np.exp x))46 (def df (grad f 0))"""47 df = get_function(expr, "df")48 assert np.allclose(df(2.0), np.exp(2.0))49def test_double_grad_exp():50 expr = """(def (f x) (np.exp x))51 (def df (grad f 0))52 (def ddf (grad df 0))"""53 ddf = get_function(expr, "ddf")54 assert np.allclose(ddf(2.0), np.exp(2.0))55def test_grad_identity():56 expr = """(def (f x) x)57 (def df (grad f 0))"""58 df = get_function(expr, "df")59 assert np.allclose(df(2.0), 1.0)60def test_double_grad_identity():61 expr = """(def (f x) x)62 (def df (grad f 0))63 (def ddf (grad df 0))"""64 ddf = get_function(expr, "ddf")65 print ddf(2.0)66 assert np.allclose(ddf(2.0), 0.0)67def test_double_grad_sin():68 expr = """(def (f x) (np.sin x))69 (def df (grad f 0))70 (def ddf (grad df 0))"""71 ddf = get_function(expr, "ddf")72 print ddf(np.pi/6)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful