Best Python code snippet using pyresttest_python
magic.py
Source:magic.py
1# Copyright 2021 Google LLC2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# https://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""Types and functions defining Picatrix integration with IPython magics."""15import argparse16import shlex17from dataclasses import dataclass, field18from enum import Enum, auto19from inspect import getfullargspec20from typing import (21 Any,22 Callable,23 Dict,24 Iterable,25 List,26 NoReturn,27 Optional,28 Text,29 Type,30 Union,31)32from docstring_parser import parse33from .error import Error34from .utils import ipython_bind_global35class MagicError(Error):36 """Generic Picatrix error related to IPython magics."""37class MagicParsingError(MagicError, ValueError):38 """Raised when invalid function is provided to magic framework."""39class MagicArgParsingError(MagicError, ValueError):40 """Raised when invalid arguments where provided to magic."""41class MagicType(Enum):42 """Enum indicating a type of the IPython magic."""43 CELL = auto()44 LINE = auto()45_MagicArgValues = [bool, int, float, str]46MagicArgValue = Union[bool, int, float, str]47_MagicArgValueType = Union[Type[bool], Type[int], Type[float], Type[str]]48def _validate_arg_value(arg: Text, v: Any) -> MagicArgValue:49 for typ in _MagicArgValues:50 if isinstance(v, typ):51 return typ(v)52 raise MagicArgParsingError(53 f"{arg}=\"{v}\" is of invalid type; has to be {MagicArgValue}")54@dataclass(frozen=True)55class MagicArgs:56 """Arguments parsed out of IPython magic invocation."""57 bind_variable: Text = field(default="_")58 kwargs: Dict[Text, MagicArgValue] = field(default_factory=dict)59 def __post_init__(self):60 if not self.bind_variable.isidentifier(): # pylint: disable=no-member61 raise MagicArgParsingError(62 f"\"{self.bind_variable}\" isn't valid Python "63 "identifier, see: "64 "https://docs.python.org/3/reference/"65 "lexical_analysis.html#identifiers")66class ArgParserNonZeroStatus(Exception):67 """Raised when the argument parser has exited with non-zero status."""68class MagicArgumentParser(argparse.ArgumentParser):69 """Argument parser for Picatrix magics."""70 def exit(self, status: int = 0, message: Optional[Text] = None) -> NoReturn:71 """Exiting method for argument parser.72 Args:73 status (int): exit status of the parser.74 message (str): the error message.75 Raises:76 MagicArgParsingError: when the parser is unable to parse the arguments.77 ArgParserNonZeroStatus: when the parser has successfully completed.78 """79 if not status:80 raise ArgParserNonZeroStatus()81 if message:82 raise MagicArgParsingError(message.strip())83 raise MagicArgParsingError("Wrong usage.")84 def parse_magic_args(85 self, line: Text, cell: Optional[Text] = None) -> MagicArgs:86 """Parse arguments out of line and cell content as provided by IPython."""87 line = line.strip()88 kwargs: Dict[Text, MagicArgValue] = {}89 if cell:90 kwargs["cell"] = cell91 if line and "-- " not in line:92 return MagicArgs(bind_variable=line, kwargs=kwargs)93 if line.endswith("--"):94 return MagicArgs(bind_variable=line.rstrip("--"), kwargs=kwargs)95 if not line:96 bind_variable = "_"97 raw = line98 elif line.startswith("-- "):99 bind_variable = "_"100 raw = line[3:]101 else:102 bind_variable, raw = line.split(" -- ", maxsplit=1)103 for arg, value in self.parse_args(shlex.split(raw)).__dict__.items():104 kwargs[str(arg)] = _validate_arg_value(arg, value)105 return MagicArgs(bind_variable, kwargs)106def _usage_string(107 mtyp: MagicType, args: Iterable[Text], kwargs: Iterable[Text]) -> Text:108 arguments = (109 " ".join(f"[--{key} {key.upper()}]" for key in kwargs) + " " +110 " ".join(args))111 if mtyp == MagicType.LINE:112 return f"\n```%%%(prog)s [bind_variable] -- [-h] {arguments}```"113 else:114 return f"\n```\n%%%%%(prog)s [bind_variable] -- [-h] {arguments}\ncell\n```"115@dataclass(frozen=True)116class _MagicSpec:117 """Magic function specification for argument parsing purposes."""118 name: Text119 docstring: Text120 typ: MagicType121 args_with_no_defaults: List[Text] = field(default_factory=list)122 args_with_defaults: Dict[Text, Text] = field(default_factory=dict)123 args_descriptions: Dict[Text, Text] = field(default_factory=dict)124 args_types: Dict[Text, _MagicArgValueType] = field(default_factory=dict)125 def __post_init__(self):126 if (self.args_with_no_defaults or127 self.args_with_defaults) and not self.args_descriptions:128 raise MagicParsingError(129 "Magics have to have docstring section describing their arguments.")130 # pylint: disable=unsupported-membership-test131 for arg, typ in self.args_types.items():132 if typ == bool and arg in self.args_with_no_defaults:133 raise MagicParsingError(134 "Arguments of type bool have to have a default value specified.")135 for arg in list(self.args_with_no_defaults) + list(self.args_with_defaults):136 if arg not in self.args_descriptions:137 raise MagicParsingError(138 "Magics have to have docstring section describing all of their "139 f"arguments; docstring missing for `{arg}`")140 if self.typ == MagicType.CELL and "cell" not in self.args_with_no_defaults:141 raise MagicParsingError(142 "Cell magics have to have positional argument called `cell`")143 # pylint: enable=unsupported-membership-test144 @classmethod145 def from_function(146 cls,147 typ: MagicType,148 func: Callable[..., Any],149 name: Optional[Text] = None) -> "_MagicSpec":150 """Creates _MagicSpec from compatible function."""151 name = name if name else func.__name__152 if not name.isidentifier():153 raise MagicParsingError(154 f"\"{name}\" isn't valid Python identifier, see: "155 "https://docs.python.org/3/reference/"156 "lexical_analysis.html#identifiers")157 if not func.__doc__:158 raise MagicParsingError("Magics have to have docstring.")159 spec = getfullargspec(func)160 if spec.varargs or spec.varkw:161 raise MagicParsingError(162 "Magics can't have explicit variadic arguments, "163 "i.e. `*args` or `**kwargs`")164 if spec.kwonlyargs and not spec.kwonlydefaults:165 raise MagicParsingError(166 "Magics can't have keyword-only arguments without default value.")167 args: List[Text] = spec.args168 args_with_defaults: Dict[Text, Text] = {}169 args_types: Dict[Text, _MagicArgValueType] = {}170 if spec.annotations:171 for arg, typ_ in spec.annotations.items():172 if arg == "return" or typ_ in _MagicArgValues:173 args_types[arg] = typ_174 else:175 raise MagicParsingError(176 f"Magics can only have arguments of type {MagicArgValue}; "177 f"got {arg}: {typ_}")178 if spec.defaults:179 for default in reversed(spec.defaults):180 args_with_defaults[args.pop()] = default181 if spec.kwonlydefaults:182 for arg, default in spec.kwonlydefaults.items():183 args_with_defaults[arg] = default184 docstring = func.__doc__ if func.__doc__ else ""185 args_descriptions: Dict[Text, Text] = {186 param.arg_name: param.description # type: ignore187 for param in parse(docstring).params188 }189 return cls(190 name, docstring, typ, args, args_with_defaults, args_descriptions,191 args_types)192 def to_parser(self) -> MagicArgumentParser:193 """Create an argument parser out of _MagicSpec."""194 desc, *_ = self.docstring.split('\n')195 visible_args = self.args_with_no_defaults196 if self.typ == MagicType.CELL:197 visible_args = [a for a in self.args_with_no_defaults if a != "cell"]198 parser = MagicArgumentParser(199 prog=self.name,200 description=desc,201 usage=_usage_string(202 self.typ, visible_args, self.args_with_defaults.keys())) # pylint: disable=no-member203 for arg in self.args_with_no_defaults: # pylint: disable=not-an-iterable204 if self.typ == MagicType.CELL and arg == "cell":205 continue206 typ = self.args_types.get(arg, str)207 parser.add_argument(208 arg,209 type=typ, # type: ignore210 action="store",211 help=self.args_descriptions[arg])212 for arg, default in self.args_with_defaults.items(): # pylint: disable=no-member213 typ = self.args_types.get(arg, str)214 if typ == bool:215 parser.add_argument(216 f"--{arg}",217 dest=arg,218 action="store_false" if default else "store_true",219 help=self.args_descriptions[arg],220 default=default)221 else:222 parser.add_argument(223 f"--{arg}",224 dest=arg,225 type=typ, # type: ignore226 action="store",227 help=self.args_descriptions[arg],228 default=default)229 return parser230@dataclass(frozen=True)231class Magic:232 """Wrapper for IPython magic."""233 _spec: _MagicSpec234 _parser: MagicArgumentParser235 func: Callable[..., Any]236 __doc__: Text237 @classmethod238 def wrap(239 cls,240 typ: MagicType,241 func: Callable[..., Any],242 name: Optional[Text] = None) -> "Magic":243 """Wrap wraps a function to make it an IPython magic."""244 spec = _MagicSpec.from_function(typ, func, name=name)245 return cls(spec, spec.to_parser(), func, func.__doc__ or cls.__doc__)246 def __call__(self, line: Text, cell: Optional[Text] = None) -> Any:247 try:248 args = self._parser.parse_magic_args(line, cell)249 res = self.func(**args.kwargs)250 ipython_bind_global(args.bind_variable, res)251 return res252 except ArgParserNonZeroStatus:...
magic_test.py
Source:magic_test.py
1# Copyright 2021 Google LLC2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# https://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# type: ignore15# pylint: disable=W021216# pylint: disable=unused-argument17"""Test for Picatrix integration with IPython magics."""18from typing import Text19import pytest20from .magic import (21 MagicArgParsingError,22 MagicArgs,23 MagicParsingError,24 MagicType,25 _MagicSpec,26)27# Test functions28def magic(29 a: Text,30 b: Text,31):32 """Example function.33 Args:34 a: first argument35 b: second argument36 """37def test_magicspec_valid():38 """Test if _MagicSpec parses simple function."""39 want = _MagicSpec(40 name="magic",41 docstring=magic.__doc__,42 typ=MagicType.LINE,43 args_with_no_defaults=["a", "b"],44 args_descriptions={45 "a": "first argument",46 "b": "second argument",47 },48 args_types={49 "a": str,50 "b": str,51 })52 got = _MagicSpec.from_function(MagicType.LINE, magic)53 assert want == got54def magic_with_defaults(55 a: Text,56 b: Text = "dog",57 c: Text = "cat",58):59 """Example function.60 Args:61 a: first argument62 b: second argument63 c: third argument64 """65def test_magicspec_valid_with_defaults():66 """Test if _MagicSpec parses simple function with default value."""67 want = _MagicSpec(68 name="magic_with_defaults",69 docstring=magic_with_defaults.__doc__,70 typ=MagicType.LINE,71 args_with_no_defaults=["a"],72 args_with_defaults={73 "b": "dog",74 "c": "cat",75 },76 args_descriptions={77 "a": "first argument",78 "b": "second argument",79 "c": "third argument",80 },81 args_types={82 "a": str,83 "b": str,84 "c": str,85 })86 got = _MagicSpec.from_function(MagicType.LINE, magic_with_defaults)87 assert want == got88# pylint: disable=missing-function-docstring89def magic_no_docstring(90 a: Text,91 b: Text = "dog",92):93 pass94# pylint: enable=missing-function-docstring95def test_magicspec_no_docstring():96 """Test if _MagicSpec errors on function with no docstring."""97 with pytest.raises(MagicParsingError):98 _MagicSpec.from_function(MagicType.LINE, magic_no_docstring)99def magic_bad_docstring(100 a: Text,101 b: Text = "dog",102):103 """Example function.104 Args:105 a: first argument106 """107def test_magicspec_bad_docstring():108 """Test if _MagicSpec errors on function with no docstring for all args."""109 with pytest.raises(MagicParsingError):110 _MagicSpec.from_function(MagicType.LINE, magic_bad_docstring)111def magic_notstring(112 a: int,113 b: Text = "dog",114 c: float = 1.11,115):116 """Example function.117 Args:118 a: first argument119 b: second argument120 c: third argument121 """122def test_magicspec_nonstring():123 """Test if _MagicSpec errors on non-string parameter."""124 want = _MagicSpec(125 name="magic_notstring",126 docstring=magic_notstring.__doc__,127 typ=MagicType.LINE,128 args_with_no_defaults=["a"],129 args_with_defaults={130 "b": "dog",131 "c": 1.11,132 },133 args_descriptions={134 "a": "first argument",135 "b": "second argument",136 "c": "third argument",137 },138 args_types={139 "a": int,140 "b": str,141 "c": float,142 })143 got = _MagicSpec.from_function(MagicType.LINE, magic_notstring)144 assert want == got145def magic_variadic(146 a: Text,147 *args: Text,148) -> Text:149 """Example function.150 Args:151 a: first argument152 *args: all other arguments153 """154def test_magicspec_variadic():155 """Test if _MagicSpec errors on functions with variadic params."""156 with pytest.raises(MagicParsingError):157 _MagicSpec.from_function(MagicType.LINE, magic_variadic)158def magic_kwvariadic(159 a: Text,160 **kwargs: Text,161) -> Text:162 """Example function.163 Args:164 a: first argument165 **kwargs: all other arguments166 """167def test_magicspec_kwvariadic():168 """Test if _MagicSpec errors on functions with keyword variadic params."""169 with pytest.raises(MagicParsingError):170 _MagicSpec.from_function(MagicType.LINE, magic_kwvariadic)171def magic_with_all_defaults(172 a: Text = "dog",173 b: Text = "cat",174):175 """Example function.176 Args:177 a: first argument178 b: second argument179 """180def test_magicsargsparser_empty():181 """Test parsing of empty string."""182 spec = _MagicSpec.from_function(MagicType.LINE, magic_with_all_defaults)183 parser = spec.to_parser()184 line = ""185 want = MagicArgs(186 bind_variable="_", kwargs={187 "a": "dog",188 "b": "cat",189 })190 got = parser.parse_magic_args(line, None)191 assert want == got192def test_magicsargsparser_positional():193 """Test parsing of a signal positional argument."""194 spec = _MagicSpec.from_function(MagicType.LINE, magic_with_defaults)195 parser = spec.to_parser()196 line = "v -- horse"197 want = MagicArgs(198 bind_variable="v", kwargs={199 "a": "horse",200 "b": "dog",201 "c": "cat",202 })203 got = parser.parse_magic_args(line, None)204 assert want == got205def test_magicsargsparser_mixed():206 """Test parsing of a mix of positional and keyword arguments."""207 spec = _MagicSpec.from_function(MagicType.LINE, magic_with_defaults)208 parser = spec.to_parser()209 line = "-- --b=boar horse"210 want = MagicArgs(211 bind_variable="_", kwargs={212 "a": "horse",213 "b": "boar",214 "c": "cat",215 })216 got = parser.parse_magic_args(line, None)217 assert want == got218def test_magicsargsparser_notstring():219 """Test parsing of non-string arguments."""220 spec = _MagicSpec.from_function(MagicType.LINE, magic_notstring)221 parser = spec.to_parser()222 line = "-- --b=boar --c=2.22 10"223 want = MagicArgs(224 bind_variable="_", kwargs={225 "a": 10,226 "b": "boar",227 "c": 2.22,228 })229 got = parser.parse_magic_args(line, None)230 assert want == got231def magic_bool_true(a: bool = True):232 """Example function.233 Args:234 a: first argument235 """236def test_magicsargsparser_bool_true():237 """Test parsing of boolean argument with default equal to true."""238 spec = _MagicSpec.from_function(MagicType.LINE, magic_bool_true)239 parser = spec.to_parser()240 line = "-- --a"241 want = MagicArgs(bind_variable="_", kwargs={"a": False})242 got = parser.parse_magic_args(line, None)243 assert want == got244 line = ""245 want = MagicArgs(bind_variable="_", kwargs={"a": True})246 got = parser.parse_magic_args(line, None)247 assert want == got248def magic_bool_false(a: bool = False):249 """Example function.250 Args:251 a: first argument252 """253def test_magicsargsparser_bool_false():254 """Test parsing of boolean argument with default equal to false."""255 spec = _MagicSpec.from_function(MagicType.LINE, magic_bool_false)256 parser = spec.to_parser()257 line = "-- --a"258 want = MagicArgs(bind_variable="_", kwargs={"a": True})259 got = parser.parse_magic_args(line, None)260 assert want == got261 line = ""262 want = MagicArgs(bind_variable="_", kwargs={"a": False})263 got = parser.parse_magic_args(line, None)264 assert want == got265@pytest.mark.parametrize("line", ["--", " -- ", "-- --b=cat", "11 -- cat"])266def test_magicsargsparser_error(line):267 """Test parsing behavior for errornous inputs."""268 spec = _MagicSpec.from_function(MagicType.LINE, magic_with_defaults)269 parser = spec.to_parser()270 with pytest.raises(MagicArgParsingError):...
utility.py
Source:utility.py
1#!/usr/bin/python2import sqlite3 as db3import sys4def query_db(query,bind_variable=None):5 con = db.connect('chinook.db')6 cur = db.Cursor(con)7 try:8 if bind_variable==None:9 cur.execute(query)10 else:11 cur.execute(query,bind_variable)12 result = cur.fetchall()13 return result14 except:15 print("Oops!",sys.exc_info()[0],"occured.")16 finally:17 cur.close()18 con.commit()19 con.close() ...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!