code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
import dataclasses
import sys
from dataclasses import dataclass
from enum import Enum, unique
from pathlib import Path
from typing import IO, Any, AnyStr, Callable, Iterable, Optional, Sequence, TypeVar, Union, cast
import click
import pluggy
import tomli_w
from robotcode.core.dataclasses import as_dict, as_json
__all__ = [
"hookimpl",
"CommonConfig",
"pass_application",
"Application",
"UnknownError",
"OutputFormat",
"ColoredOutput",
]
F = TypeVar("F", bound=Callable[..., Any])
hookimpl = cast(Callable[[F], F], pluggy.HookimplMarker("robotcode"))
class UnknownError(click.ClickException):
"""An unknown error occurred."""
exit_code = 255
@unique
class ColoredOutput(str, Enum):
AUTO = "auto"
YES = "yes"
NO = "no"
@unique
class OutputFormat(str, Enum):
TOML = "toml"
JSON = "json"
JSON_INDENT = "json-indent"
TEXT = "text"
def __str__(self) -> str:
return self.value
@dataclass
class CommonConfig:
config_files: Optional[Sequence[Path]] = None
profiles: Optional[Sequence[str]] = None
dry: bool = False
verbose: bool = False
colored_output: ColoredOutput = ColoredOutput.AUTO
default_paths: Optional[Sequence[str]] = None
launcher_script: Optional[str] = None
output_format: Optional[OutputFormat] = None
pager: Optional[bool] = None
class Application:
def __init__(self) -> None:
self.config = CommonConfig()
@property
def colored(self) -> bool:
return self.config.colored_output in [ColoredOutput.AUTO, ColoredOutput.YES]
def verbose(
self,
message: Union[str, Callable[[], Any], None],
file: Optional[IO[AnyStr]] = None,
nl: bool = True,
err: bool = True,
) -> None:
if self.config.verbose:
click.secho(
message() if callable(message) else message,
file=file,
nl=nl,
err=err,
color=self.colored,
fg="bright_black",
)
def warning(
self,
message: Union[str, Callable[[], Any], None],
file: Optional[IO[AnyStr]] = None,
nl: bool = True,
err: bool = False,
) -> None:
click.secho(
f"WARNING: {message() if callable(message) else message}",
file=file,
nl=nl,
err=err,
color=self.colored,
fg="bright_yellow",
)
def print_data(
self, data: Any, remove_defaults: bool = True, default_output_format: Optional[OutputFormat] = None
) -> None:
format = self.config.output_format or default_output_format or OutputFormat.TEXT
text = None
if format == OutputFormat.TOML:
text = tomli_w.dumps(
as_dict(data, remove_defaults=remove_defaults)
if dataclasses.is_dataclass(data)
else data
if isinstance(data, dict)
else {data: data}
)
if text is None:
if format in [OutputFormat.JSON, OutputFormat.JSON_INDENT]:
text = as_json(data, indent=format == OutputFormat.JSON_INDENT, compact=format == OutputFormat.TEXT)
else:
text = str(data)
if not text:
return
if self.colored and format != OutputFormat.TEXT:
try:
from rich.console import Console
from rich.syntax import Syntax
if format == OutputFormat.JSON_INDENT:
format = OutputFormat.JSON
console = Console(soft_wrap=True)
if self.config.pager:
with console.pager(styles=True, links=True):
console.print(Syntax(text, format, background_color="default"))
else:
console.print(Syntax(text, format, background_color="default"))
return
except ImportError:
if self.config.colored_output == ColoredOutput.YES:
self.warning('Package "rich" is required to use colored output.')
if self.config.pager:
self.echo_via_pager(text)
else:
self.echo(text)
return
def echo(
self,
message: Union[str, Callable[[], Any], None],
file: Optional[IO[AnyStr]] = None,
nl: bool = True,
err: bool = False,
) -> None:
click.secho(
message() if callable(message) else message,
file=file,
nl=nl,
color=self.colored,
err=err,
)
def echo_as_markdown(self, text: str) -> None:
if self.colored:
try:
from rich.console import Console, ConsoleOptions, RenderResult
from rich.markdown import Heading, Markdown
from rich.text import Text
class MyHeading(Heading):
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
for result in super().__rich_console__(console, options):
cast(Text, result).justify = "left"
yield result
Markdown.elements["heading_open"] = MyHeading
markdown = Markdown(text, justify="left", code_theme="default")
console = Console()
if self.config.pager:
with console.pager(styles=True, links=True):
console.print(markdown)
else:
console.print(markdown)
return
except ImportError:
if self.config.colored_output == ColoredOutput.YES:
self.warning('Package "rich" is required to use colored output.')
self.echo_via_pager(text)
def echo_via_pager(
self,
text_or_generator: Union[Iterable[str], Callable[[], Iterable[str]], str],
color: Optional[bool] = None,
) -> None:
if not self.config.pager:
text = (
text_or_generator
if isinstance(text_or_generator, str)
else "".join(text_or_generator() if callable(text_or_generator) else text_or_generator)
)
click.echo(text, color=color if color is not None else self.colored)
else:
click.echo_via_pager(text_or_generator, color=color if color is not None else self.colored)
def keyboard_interrupt(self) -> None:
self.verbose("Aborted!", file=sys.stderr)
sys.exit(253)
def exit(self, code: int = 0) -> None:
self.verbose(f"Exit with code {code}")
sys.exit(code)
pass_application = click.make_pass_decorator(Application, ensure=True) | /robotcode_plugin-0.54.3-py3-none-any.whl/robotcode/plugin/__init__.py | 0.698844 | 0.153264 | __init__.py | pypi |
from enum import Enum
from typing import (
Any,
Callable,
Generic,
List,
Mapping,
NamedTuple,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
)
import click
T = TypeVar("T", bound=Enum)
class EnumChoice(click.Choice, Generic[T]):
"""A click.Choice that accepts Enum values."""
def __init__(self, choices: Type[T], case_sensitive: bool = True, excluded: Optional[Set[T]] = None) -> None:
super().__init__(
choices if excluded is None else (set(choices).difference(excluded)), # type: ignore
case_sensitive,
)
FC = Union[Callable[..., Any], click.Command]
def add_options(*options: FC) -> FC:
def _add_options(func: FC) -> FC:
for option in reversed(options):
func = option(func)
return func
return _add_options
class NameParamType(click.types.StringParamType):
name = "name"
def __repr__(self) -> str:
return "NAME"
class AddressParamType(click.types.StringParamType):
name = "address"
def __repr__(self) -> str:
return "ADDRESS"
class PortParamType(click.IntRange):
name = "port"
def __init__(self) -> None:
super().__init__(1, 65535)
def __repr__(self) -> str:
return "PORT"
class AddressesPort(NamedTuple):
addresses: Optional[Sequence[str]] = None
port: Optional[int] = None
class AddressPortParamType(click.ParamType):
name = "[<address>:]<port>"
def convert(self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]) -> Any:
splitted = value.split(":")
if len(splitted) == 1 and splitted[0]:
try:
port = PortParamType().convert(splitted[0], param, ctx)
return AddressesPort(None, port)
except click.BadParameter:
if splitted[0].isdigit():
raise
address = AddressParamType().convert(splitted[0], param, ctx)
return AddressesPort([address], None)
if len(splitted) == 2:
address = AddressParamType().convert(splitted[0], param, ctx)
port = PortParamType().convert(splitted[1], param, ctx)
return AddressesPort([address], port)
raise click.BadParameter(f"{value} is not a valid address or port", ctx=ctx, param=param)
def __repr__(self) -> str:
return "ADDRESS_PORT"
class MutuallyExclusiveOption(click.Option):
def __init__(self, *args: Any, mutually_exclusive: Set[str], **kwargs: Any) -> None:
self.mutually_exclusive = mutually_exclusive
help = kwargs.get("help", "")
if self.mutually_exclusive:
ex_str = ", ".join(self.mutually_exclusive)
kwargs["help"] = help + ("\n*NOTE:* This option is mutually exclusive with options: " + ex_str + ".")
super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)
def handle_parse_result(
self, ctx: click.Context, opts: Mapping[str, Any], args: List[str]
) -> Tuple[Any, List[str]]:
if self.mutually_exclusive.intersection(opts) and self.name in opts:
*first_opts, last_opt = sorted(self.mutually_exclusive)
raise click.UsageError(
f"You can't use the --{self.name} option together"
f" with the --{(', --'.join(first_opts) + ' or the --') if first_opts else ''}{last_opt} option"
)
return super(MutuallyExclusiveOption, self).handle_parse_result(ctx, opts, args) | /robotcode_plugin-0.54.3-py3-none-any.whl/robotcode/plugin/click_helper/types.py | 0.902334 | 0.267357 | types.py | pypi |
from typing import List, Optional, Sequence, Set, Tuple
import click
from robotcode.core.types import ServerMode
from robotcode.plugin import Application
from robotcode.plugin.click_helper.types import (
AddressesPort,
AddressParamType,
AddressPortParamType,
EnumChoice,
MutuallyExclusiveOption,
NameParamType,
PortParamType,
)
from .types import FC
# mypy: disable-error-code="attr-defined"
def server_options(
default_server_mode: ServerMode, default_port: int, allowed_server_modes: Optional[Set[ServerMode]] = None
) -> Sequence[FC]:
result: List[FC] = []
def exclusive(option_name: str, *args: ServerMode) -> Sequence[str]:
return (
[option_name]
if not allowed_server_modes or any(True for arg in args if arg in allowed_server_modes)
else []
)
if not allowed_server_modes or ServerMode.STDIO in allowed_server_modes:
result += [
click.option(
"--stdio",
"stdio",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("bind", ServerMode.TCP, ServerMode.SOCKET),
"mode",
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("port", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("socket", ServerMode.SOCKET),
*exclusive("tcp", ServerMode.TCP),
},
type=bool,
default=False,
is_flag=True,
help="Run in `stdio` mode. (Equivalent to `--mode stdio`)",
show_envvar=True,
)
]
if not allowed_server_modes or ServerMode.TCP in allowed_server_modes:
result += [
click.option(
"--tcp",
"tcp",
cls=MutuallyExclusiveOption,
mutually_exclusive={
"mode",
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("port", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("socket", ServerMode.SOCKET),
*exclusive("stdio", ServerMode.STDIO),
},
type=AddressPortParamType(),
show_default=True,
help="Run in `tcp` server mode and listen at the given port. "
"(Equivalent to `--mode tcp --port <port>`)",
)
]
if not allowed_server_modes or ServerMode.SOCKET in allowed_server_modes:
result += [
click.option(
"--socket",
"socket",
cls=MutuallyExclusiveOption,
mutually_exclusive={
"mode",
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("port", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("stdio", ServerMode.STDIO),
*exclusive("tcp", ServerMode.TCP),
},
type=AddressPortParamType(),
show_default=True,
help="Run in `socket` mode and connect to the given port. "
"(Equivalent to `--mode socket --port <port>`)",
)
]
if not allowed_server_modes or ServerMode.PIPE in allowed_server_modes:
result += [
click.option(
"--pipe",
"pipe",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("bind", ServerMode.TCP, ServerMode.SOCKET),
"mode",
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("port", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("socket", ServerMode.SOCKET),
*exclusive("stdio", ServerMode.STDIO),
*exclusive("tcp", ServerMode.TCP),
},
type=NameParamType(),
help="Run in `pipe` mode and connect to the given pipe name. "
"(Equivalent to `--mode pipe --pipe-name <name>`)",
)
]
if not allowed_server_modes or ServerMode.PIPE_SERVER in allowed_server_modes:
result += [
click.option(
"--pipe-server",
"pipe_server",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("bind", ServerMode.TCP, ServerMode.SOCKET),
"mode",
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
*exclusive("port", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("socket", ServerMode.SOCKET),
*exclusive("stdio", ServerMode.STDIO),
*exclusive("tcp", ServerMode.TCP),
},
type=NameParamType(),
help="Run in `pipe-server` mode and listen at the given pipe name. "
"(Equivalent to `--mode pipe-server --pipe-name <name>`)",
)
]
result += [
click.option(
"--mode",
"mode",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("socket", ServerMode.SOCKET),
*exclusive("stdio", ServerMode.STDIO),
*exclusive("tcp", ServerMode.TCP),
},
type=EnumChoice(
ServerMode,
excluded=None if allowed_server_modes is None else (set(ServerMode).difference(allowed_server_modes)),
),
default=default_server_mode,
show_default=True,
help="The mode to use for the debug launch server.",
show_envvar=True,
)
]
if not allowed_server_modes or ServerMode.TCP in allowed_server_modes or ServerMode.SOCKET in allowed_server_modes:
result += [
click.option(
"--port",
"port",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
},
type=PortParamType(),
default=default_port,
show_default=True,
help="The port to listen on or connect to. (Only valid for `tcp` and `socket mode`)",
show_envvar=True,
),
click.option(
"--bind",
"bind",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("pipe-name", ServerMode.PIPE, ServerMode.PIPE_SERVER),
},
type=AddressParamType(),
default=["127.0.0.1"],
show_default=True,
help="Specify alternate bind address. If no address is specified `localhost` is used. "
"(Only valid for tcp and socket mode)",
show_envvar=True,
multiple=True,
),
]
if (
not allowed_server_modes
or ServerMode.PIPE in allowed_server_modes
or ServerMode.PIPE_SERVER in allowed_server_modes
):
result += [
click.option(
"--pipe-name",
"pipe_name",
cls=MutuallyExclusiveOption,
mutually_exclusive={
*exclusive("bind", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("pipe", ServerMode.PIPE),
*exclusive("pipe-server", ServerMode.PIPE_SERVER),
*exclusive("port", ServerMode.TCP, ServerMode.SOCKET),
*exclusive("socket", ServerMode.SOCKET),
*exclusive("stdio", ServerMode.STDIO),
*exclusive("tcp", ServerMode.TCP),
},
type=NameParamType(),
default=None,
help="The pipe to listen on or connect to. (Only valid in `pipe` and `pipe-server` mode)",
show_envvar=True,
)
]
return result
def resolve_server_options(
ctx: click.Context,
app: Application,
mode: ServerMode,
port: Optional[int],
bind: Optional[Sequence[str]],
pipe_name: Optional[str],
tcp: Optional[AddressesPort],
socket: Optional[AddressesPort],
stdio: Optional[bool],
pipe: Optional[str],
pipe_server: Optional[str],
) -> Tuple[ServerMode, Optional[int], Optional[Sequence[str]], Optional[str]]:
if stdio and ctx.get_parameter_source("stdio") not in [
click.core.ParameterSource.DEFAULT,
click.core.ParameterSource.DEFAULT_MAP,
]:
mode = ServerMode.STDIO
if bind is None:
bind = []
if tcp is not None and ctx.get_parameter_source("tcp") not in [
click.core.ParameterSource.DEFAULT,
click.core.ParameterSource.DEFAULT_MAP,
]:
mode = ServerMode.TCP
if tcp.port is not None:
port = tcp.port
if tcp.addresses is not None:
bind = [*bind, *tcp.addresses]
if socket is not None and ctx.get_parameter_source("socket") not in [
click.core.ParameterSource.DEFAULT,
click.core.ParameterSource.DEFAULT_MAP,
]:
mode = ServerMode.SOCKET
if socket.port is not None:
port = socket.port
if socket.addresses is not None:
bind = [*bind, *socket.addresses]
if pipe is not None and ctx.get_parameter_source("pipe") not in [
click.core.ParameterSource.DEFAULT,
click.core.ParameterSource.DEFAULT_MAP,
]:
mode = ServerMode.PIPE
pipe_name = pipe
if pipe_server is not None and ctx.get_parameter_source("pipe_server") not in [
click.core.ParameterSource.DEFAULT,
click.core.ParameterSource.DEFAULT_MAP,
]:
mode = ServerMode.PIPE_SERVER
pipe_name = pipe_server
app.verbose(lambda: f"Mode: {mode}")
app.verbose(lambda: f"Port: {port}")
if bind:
app.verbose(lambda: f"Addresses: {bind}")
if pipe_name:
app.verbose(lambda: f"Pipe Name: {pipe_name}")
if app.config.launcher_script:
app.verbose(lambda: f"Launcher Script: {app.config.launcher_script}")
return mode, port, bind, pipe_name | /robotcode_plugin-0.54.3-py3-none-any.whl/robotcode/plugin/click_helper/options.py | 0.767429 | 0.153962 | options.py | pypi |
import sys
from enum import Enum
from pathlib import Path
from typing import Any, Optional, Sequence, Tuple, Union
from robotcode.core.dataclasses import from_dict
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
from .model import RobotConfig
PYPROJECT_TOML = "pyproject.toml"
ROBOT_TOML = "robot.toml"
LOCAL_ROBOT_TOML = ".robot.toml"
USER_DEFAULT_CONFIG_TOML = "default config"
class DiscoverdBy(str, Enum):
GIT = ".git directory"
HG = "hg"
PYPROJECT_TOML = "pyproject.toml (project file))"
ROBOT_TOML = "robot.toml (project file)"
LOCAL_ROBOT_TOML = ".robot.toml (local file)"
USER_DEFAULT_CONFIG_TOML = "robot.toml (user default config)"
NOT_FOUND = "not found"
class ConfigType(str, Enum):
PYPROJECT_TOML = "pyproject.toml (project file))"
ROBOT_TOML = "robot.toml (project file)"
LOCAL_ROBOT_TOML = ".robot.toml (local file)"
USER_DEFAULT_CONFIG_TOML = "robot.toml (user default config)"
CUSTOM_TOML = ".toml (custom file)"
class ConfigValueError(ValueError):
def __init__(self, path: Path, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.path = path
class ConfigTypeError(TypeError):
def __init__(self, path: Path, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.path = path
def loads_config_from_robot_toml(__s: str) -> RobotConfig:
dict_data = tomllib.loads(__s)
return from_dict(dict_data, RobotConfig)
def loads_config_from_pyproject_toml(__s: str) -> RobotConfig:
dict_data = tomllib.loads(__s)
return from_dict(dict_data.get("tool", {}).get("robot", {}), RobotConfig)
def _load_config_data_from_path(__path: Path) -> RobotConfig:
try:
if __path.name == PYPROJECT_TOML:
return loads_config_from_pyproject_toml(__path.read_text("utf-8"))
if __path.name == ROBOT_TOML or __path.name == LOCAL_ROBOT_TOML or __path.suffix == ".toml":
return loads_config_from_robot_toml(__path.read_text("utf-8"))
raise TypeError("Unknown config file type.")
except ValueError as e:
raise ConfigValueError(__path, f'Parsing "{__path}" failed: {e}') from e
except TypeError as e:
raise ConfigTypeError(__path, f'Parsing "{__path}" failed: {e}') from e
def get_default_config() -> RobotConfig:
result = RobotConfig()
result.output_dir = "results"
result.python_path = ["./lib", "./resources"]
return result
def load_config_from_path(*__paths: Union[Path, Tuple[Path, ConfigType]]) -> RobotConfig:
result = RobotConfig()
for __path in __paths:
result.add_options(_load_config_data_from_path(__path if isinstance(__path, Path) else __path[0]))
return result
def find_project_root(*sources: Union[str, Path]) -> Tuple[Optional[Path], DiscoverdBy]:
if not sources:
sources = (str(Path.cwd().resolve()),)
path_srcs = [Path(Path.cwd(), src).resolve() for src in sources]
src_parents = [list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs]
common_base = max(
set.intersection(*(set(parents) for parents in src_parents)),
key=lambda path: path.parts,
)
for directory in (common_base, *common_base.parents):
if (directory / LOCAL_ROBOT_TOML).is_file():
return directory, DiscoverdBy.LOCAL_ROBOT_TOML
if (directory / ROBOT_TOML).is_file():
return directory, DiscoverdBy.ROBOT_TOML
if (directory / PYPROJECT_TOML).is_file():
return directory, DiscoverdBy.PYPROJECT_TOML
if (directory / ".git").exists():
return directory, DiscoverdBy.GIT
if (directory / ".hg").is_dir():
return directory, DiscoverdBy.HG
return None, DiscoverdBy.NOT_FOUND
def get_config_files_from_folder(folder: Path) -> Sequence[Tuple[Path, ConfigType]]:
result = []
pyproject_toml = folder / PYPROJECT_TOML
if pyproject_toml.is_file():
result.append((pyproject_toml, ConfigType.PYPROJECT_TOML))
robot_toml = folder / ROBOT_TOML
if robot_toml.is_file():
result.append((robot_toml, ConfigType.ROBOT_TOML))
local_robot_toml = folder / LOCAL_ROBOT_TOML
if local_robot_toml.is_file():
result.append((local_robot_toml, ConfigType.LOCAL_ROBOT_TOML))
return result | /robotcode_robot-0.54.3-py3-none-any.whl/robotcode/robot/config/loader.py | 0.498291 | 0.157752 | loader.py | pypi |
import dataclasses
import datetime
import fnmatch
import os
import platform
import re
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Tuple,
Union,
get_type_hints,
)
import tomli_w
from robotcode.core.dataclasses import TypeValidationError, ValidateMixin, as_dict, validate_types
from robotcode.core.utils.safe_eval import safe_eval
from typing_extensions import Self
class Flag(str, Enum):
ON = "on"
OFF = "off"
DEFAULT = "default"
def __str__(self) -> str:
return self.value
def __bool__(self) -> bool:
if self == Flag.ON:
return True
return False
def field(
*args: Any,
description: Optional[str] = None,
robot_name: Optional[str] = None,
robot_short_name: Optional[str] = None,
robot_is_flag: Optional[bool] = None,
robot_flag_default: Optional[bool] = None,
robot_priority: Optional[int] = None,
alias: Optional[str] = None,
convert: Optional[Callable[[Any, Any], Any]] = None,
no_default: bool = False,
**kwargs: Any,
) -> Any:
metadata = kwargs.get("metadata", {})
if description:
metadata["description"] = "\n".join(line.strip() for line in description.splitlines())
if convert is not None:
metadata["convert"] = convert
if robot_name is not None:
metadata["robot_name"] = robot_name
if robot_short_name is not None:
metadata["robot_short_name"] = robot_short_name
if robot_is_flag is not None:
metadata["robot_is_flag"] = robot_is_flag
if robot_flag_default is not None:
metadata["robot_flag_default"] = robot_flag_default
if robot_priority is not None:
metadata["robot_priority"] = robot_priority
if alias is not None:
metadata["alias"] = alias
metadata["_apischema_alias"] = alias
if metadata:
kwargs["metadata"] = metadata
if "default_factory" not in kwargs and not no_default:
kwargs["default"] = None
return dataclasses.field(*args, **kwargs)
class EvaluationError(Exception):
"""Evaluation error."""
def __init__(self, expression: str, message: str):
super().__init__(f"Evaluation of {expression!r} failed: {message}")
self.expr = expression
SAFE_GLOBALS = {
"environ": os.environ,
"re": re,
"platform": platform,
"datetime": datetime.datetime,
"date": datetime.date,
"time": datetime.time,
"timedelta": datetime.timedelta,
"timezone": datetime.timezone,
}
@dataclass
class Expression:
"""Expression to evaluate."""
expr: str = field(
description="""\
Condition to evaluate. This must be a Python "eval" expression.
For security reasons, only certain expressions and functions are allowed.
Examples:
```toml
if = "re.match(r'^\\d+$', environ.get('TEST_VAR', ''))"
if = "platform.system() == 'Linux'"
```
""",
no_default=True,
)
def evaluate(self) -> Any:
try:
return safe_eval(self.expr, SAFE_GLOBALS)
except Exception as e:
raise EvaluationError(self.expr, str(e)) from e
@dataclass
class StringExpression(Expression):
"""Expression to evaluate to a string."""
def evaluate(self) -> str:
return str(super().evaluate())
def __str__(self) -> str:
return self.evaluate()
@dataclass
class Condition:
"""Condition to evaluate."""
if_: str = field(
description="""\
Condition to evaluate. This must be a Python "eval" expression.
For security reasons, only certain expressions and functions are allowed.
Examples:
```toml
if = "re.match(r'^\\d+$', environ.get('TEST_VAR', ''))"
if = "platform.system() == 'Linux'"
```
""",
alias="if",
no_default=True,
)
def evaluate(self) -> bool:
try:
return bool(safe_eval(self.if_, SAFE_GLOBALS))
except Exception as e:
raise EvaluationError(self.if_, str(e)) from e
@dataclass()
class NamePattern(ValidateMixin):
"""Name pattern to match."""
name: str = field(
description="""\
Name pattern to match. This is a glob pattern, where ``*`` matches any number of characters
""",
no_default=True,
)
def __str__(self) -> str:
return f"name:{self.name}"
@dataclass()
class TagPattern(ValidateMixin):
"""Tag pattern to match."""
tag: str = field(
description="""\
Tag pattern to match. This is a glob pattern, where ``*`` matches any number of characters
""",
no_default=True,
)
def __str__(self) -> str:
return f"tag:{self.tag}"
@dataclass
class BaseOptions(ValidateMixin):
@classmethod
def _encode_case(cls, s: str) -> str:
return s.replace("_", "-")
@classmethod
def _decode_case(cls, s: str) -> str:
return s.replace("-", "_")
"""Base class for all options."""
def build_command_line(self) -> List[str]:
"""Build the arguments to pass to Robot Framework."""
result = []
sorted_fields = sorted(
(f for f in dataclasses.fields(self) if f.metadata.get("robot_priority", -1) > -1),
key=lambda f: f.metadata.get("robot_priority", 0),
)
def append_name(field: "dataclasses.Field[Any]", add_flag: Optional[str] = None) -> None:
if "robot_short_name" in field.metadata:
result.append(f"-{field.metadata['robot_short_name']}")
elif "robot_name" in field.metadata:
result.append(f"--{'no' if add_flag else ''}{field.metadata['robot_name']}")
for field in sorted_fields:
try:
value = getattr(self, field.name)
if value is None:
continue
if field.metadata.get("robot_is_flag", False):
if value is None or value == Flag.DEFAULT:
continue
append_name(field, bool(value) != field.metadata.get("robot_flag_default", True))
continue
if isinstance(value, list):
for item in value:
append_name(field)
if isinstance(item, dict):
for k, v in item.items():
result.append(f"{k}:{v}")
else:
result.append(str(item))
elif isinstance(value, dict):
for key, item in value.items():
append_name(field)
if isinstance(item, list):
separator = ";" if any(True for s in item if ":" in s) else ":"
result.append(f"{key}{separator if item else ''}{separator.join(item)}")
else:
result.append(f"{key}:{item}")
else:
append_name(field)
result.append(str(value))
except EvaluationError as e:
raise ValueError(f"Evaluation of '{field.name}' failed: {e!s}") from e
return result
@staticmethod
def _verified_value(name: str, value: Any, types: Union[type, Tuple[type, ...]], target: Any) -> Any:
errors = validate_types(types, value)
if errors:
raise TypeValidationError("Dataclass Type Validation Error", target=target, errors={name: errors})
return value
def add_options(self, config: "BaseOptions", combine_extras: bool = False) -> None:
type_hints = get_type_hints(type(self))
base_field_names = [f.name for f in dataclasses.fields(self)]
for f in dataclasses.fields(config):
if f.name.startswith("extra_"):
if f.name not in base_field_names:
continue
new = self._verified_value(f.name, getattr(config, f.name), type_hints[f.name[6:]], config)
if new is None:
continue
old_field_name = f.name if combine_extras else f.name[6:]
old = getattr(self, old_field_name)
if old is None:
setattr(self, old_field_name, new)
else:
if isinstance(old, dict):
if any(True for e in new.values() if isinstance(e, BaseOptions)):
for key, value in new.items():
if isinstance(value, BaseOptions) and key in old:
old[key].add_options(value, True)
else:
old[key] = value
else:
setattr(self, old_field_name, {**old, **new})
elif isinstance(old, list):
setattr(self, old_field_name, [*old, *new])
elif isinstance(old, tuple):
setattr(self, old_field_name, (*old, *new))
else:
setattr(self, old_field_name, new)
continue
if f.name not in base_field_names:
continue
if combine_extras:
if "extra_" + f.name in base_field_names and getattr(config, f.name, None) is not None:
setattr(self, "extra_" + f.name, None)
if getattr(config, f"extra_{f.name}", None) is not None and not combine_extras:
continue
new = self._verified_value(f.name, getattr(config, f.name), type_hints[f.name], config)
if new is not None:
setattr(self, f.name, new)
def evaluated(self) -> Self:
result = dataclasses.replace(self)
for f in dataclasses.fields(result):
try:
if isinstance(getattr(result, f.name), Expression):
setattr(result, f.name, getattr(result, f.name).evaluate())
elif isinstance(getattr(result, f.name), list):
setattr(
result,
f.name,
[e.evaluate() if isinstance(e, Expression) else e for e in getattr(result, f.name)],
)
elif isinstance(getattr(result, f.name), dict):
setattr(
result,
f.name,
{
k: e.evaluate() if isinstance(e, Expression) else e
for k, e in getattr(result, f.name).items()
},
)
except EvaluationError as e:
raise ValueError(f"Evaluation of '{f.name}' failed: {e!s}") from e
return result
# start generated code
@dataclass
class CommonOptions(BaseOptions):
"""Common options for all _robot_ commands."""
console_colors: Optional[Literal["auto", "on", "ansi", "off"]] = field(
description="""\
Use colors on console output or not.
auto: use colors when output not redirected (default)
on: always use colors
ansi: like `on` but use ANSI colors also on Windows
off: disable colors altogether
corresponds to the `-C --consolecolors auto|on|ansi|off` option of _robot_
""",
robot_name="consolecolors",
robot_priority=500,
robot_short_name="C",
)
doc: Optional[Union[str, StringExpression]] = field(
description="""\
Set the documentation of the top level suite.
Simple formatting is supported (e.g. *bold*). If the
documentation contains spaces, it must be quoted.
If the value is path to an existing file, actual
documentation is read from that file.
Examples:
```
--doc "Very *good* example"
--doc doc_from_file.txt
```
corresponds to the `-D --doc documentation` option of _robot_
""",
robot_name="doc",
robot_priority=500,
robot_short_name="D",
)
excludes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Select test cases not to run by tag. These tests are
not run even if included with --include. Tags are
matched using same rules as with --include.
corresponds to the `-e --exclude tag *` option of _robot_
""",
robot_name="exclude",
robot_priority=500,
robot_short_name="e",
)
expand_keywords: Optional[List[Union[str, NamePattern, TagPattern]]] = field(
description="""\
Matching keywords will be automatically expanded in
the log file. Matching against keyword name or tags
work using same rules as with --removekeywords.
Examples:
```
--expandkeywords name:BuiltIn.Log
--expandkeywords tag:expand
```
corresponds to the `--expandkeywords name:<pattern>|tag:<pattern> *` option of _robot_
""",
robot_name="expandkeywords",
robot_priority=500,
)
flatten_keywords: Optional[List[Union[str, Literal["for", "while", "iteration"], NamePattern, TagPattern]]] = field(
description="""\
Flattens matching keywords in the generated log file.
Matching keywords get all log messages from their
child keywords and children are discarded otherwise.
for: flatten FOR loops fully
while: flatten WHILE loops fully
iteration: flatten FOR/WHILE loop iterations
foritem: deprecated alias for `iteration`
name:<pattern>: flatten matched keywords using same
matching rules as with
`--removekeywords name:<pattern>`
tag:<pattern>: flatten matched keywords using same
matching rules as with
`--removekeywords tag:<pattern>`
corresponds to the `--flattenkeywords for|while|iteration|name:<pattern>|tag:<pattern> *` option of _robot_
""",
robot_name="flattenkeywords",
robot_priority=500,
)
includes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Select tests by tag. Similarly as name with --test,
tag is case and space insensitive and it is possible
to use patterns with `*`, `?` and `[]` as wildcards.
Tags and patterns can also be combined together with
`AND`, `OR`, and `NOT` operators.
Examples:
```
--include foo --include bar*
--include fooANDbar*
```
corresponds to the `-i --include tag *` option of _robot_
""",
robot_name="include",
robot_priority=500,
robot_short_name="i",
)
log: Optional[Union[str, StringExpression]] = field(
description="""\
HTML log file. Can be disabled by giving a special
value `NONE`. Default: log.html
Examples:
```
`--log mylog.html`, `-l NONE`
```
corresponds to the `-l --log file` option of _robot_
""",
robot_name="log",
robot_priority=500,
robot_short_name="l",
)
log_title: Optional[Union[str, StringExpression]] = field(
description="""\
Title for the generated log file. The default title
is `<SuiteName> Log`.
corresponds to the `--logtitle title` option of _robot_
""",
robot_name="logtitle",
robot_priority=500,
)
metadata: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Set metadata of the top level suite. Value can
contain formatting and be read from a file similarly
as --doc. Example: --metadata Version:1.2
corresponds to the `-M --metadata name:value *` option of _robot_
""",
robot_name="metadata",
robot_priority=500,
robot_short_name="M",
)
name: Optional[Union[str, StringExpression]] = field(
description="""\
Set the name of the top level suite. By default the
name is created based on the executed file or
directory.
corresponds to the `-N --name name` option of _robot_
""",
robot_name="name",
robot_priority=500,
robot_short_name="N",
)
no_status_rc: Union[bool, Flag, None] = field(
description="""\
Sets the return code to zero regardless of failures
in test cases. Error codes are returned normally.
corresponds to the `--nostatusrc` option of _robot_
""",
robot_name="statusrc",
robot_priority=500,
robot_is_flag=True,
robot_flag_default=False,
)
output_dir: Optional[Union[str, StringExpression]] = field(
description="""\
Where to create output files. The default is the
directory where tests are run from and the given path
is considered relative to that unless it is absolute.
corresponds to the `-d --outputdir dir` option of _robot_
""",
robot_name="outputdir",
robot_priority=500,
robot_short_name="d",
)
parse_include: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Parse only files matching `pattern`. It can be:
- a file name or pattern like `example.robot` or
`*.robot` to parse all files matching that name,
- a file path like `path/to/example.robot`, or
- a directory path like `path/to/example` to parse
all files in that directory, recursively.
corresponds to the `-I --parseinclude pattern *` option of _robot_
""",
robot_name="parseinclude",
robot_priority=500,
robot_short_name="I",
)
pre_rebot_modifiers: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Class to programmatically modify the result
model before creating reports and logs. Accepts
arguments the same way as with --listener.
corresponds to the `--prerebotmodifier modifier *` option of _robot_
""",
robot_name="prerebotmodifier",
robot_priority=500,
)
python_path: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Additional locations (directories, ZIPs) where to
search libraries and other extensions when they are
imported. Multiple paths can be given by separating
them with a colon (`:`) or by using this option
several times. Given path can also be a glob pattern
matching multiple paths.
Examples:
```
--pythonpath libs/
--pythonpath /opt/libs:libraries.zip
```
corresponds to the `-P --pythonpath path *` option of _robot_
""",
robot_name="pythonpath",
robot_priority=500,
robot_short_name="P",
)
remove_keywords: Optional[
List[Union[str, Literal["all", "passed", "for", "wuks"], NamePattern, TagPattern]]
] = field(
description="""\
Remove keyword data from the generated log file.
Keywords containing warnings are not removed except
in the `all` mode.
all: remove data from all keywords
passed: remove data only from keywords in passed
test cases and suites
for: remove passed iterations from for loops
while: remove passed iterations from while loops
wuks: remove all but the last failing keyword
inside `BuiltIn.Wait Until Keyword Succeeds`
name:<pattern>: remove data from keywords that match
the given pattern. The pattern is matched
against the full name of the keyword (e.g.
'MyLib.Keyword', 'resource.Second Keyword'),
is case, space, and underscore insensitive,
and may contain `*`, `?` and `[]` wildcards.
Examples:
```
--removekeywords name:Lib.HugeKw
--removekeywords name:myresource.*
```
tag:<pattern>: remove data from keywords that match
the given pattern. Tags are case and space
insensitive and patterns can contain `*`,
`?` and `[]` wildcards. Tags and patterns
can also be combined together with `AND`,
`OR`, and `NOT` operators.
Examples:
```
--removekeywords foo
--removekeywords fooANDbar*
```
corresponds to the `--removekeywords all|passed|for|wuks|name:<pattern>|tag:<pattern> *` option of _robot_
""",
robot_name="removekeywords",
robot_priority=500,
)
report: Optional[Union[str, StringExpression]] = field(
description="""\
HTML report file. Can be disabled with `NONE`
similarly as --log. Default: report.html
corresponds to the `-r --report file` option of _robot_
""",
robot_name="report",
robot_priority=500,
robot_short_name="r",
)
report_background: Optional[Union[str, StringExpression]] = field(
description="""\
Background colors to use in the report file.
Given in format `passed:failed:skipped` where the
`:skipped` part can be omitted. Both color names and
codes work.
Examples:
```
--reportbackground green:red:yellow
--reportbackground #00E:#E00
```
corresponds to the `--reportbackground colors` option of _robot_
""",
robot_name="reportbackground",
robot_priority=500,
)
report_title: Optional[Union[str, StringExpression]] = field(
description="""\
Title for the generated report file. The default
title is `<SuiteName> Report`.
corresponds to the `--reporttitle title` option of _robot_
""",
robot_name="reporttitle",
robot_priority=500,
)
rpa: Union[bool, Flag, None] = field(
description="""\
Turn on the generic automation mode. Mainly affects
terminology so that "test" is replaced with "task"
in logs and reports. By default the mode is got
from test/task header in data files.
corresponds to the `--rpa` option of _robot_
""",
robot_name="rpa",
robot_priority=500,
robot_is_flag=True,
)
set_tag: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Sets given tag(s) to all executed tests.
corresponds to the `-G --settag tag *` option of _robot_
""",
robot_name="settag",
robot_priority=500,
robot_short_name="G",
)
split_log: Union[bool, Flag, None] = field(
description="""\
Split the log file into smaller pieces that open in
browsers transparently.
corresponds to the `--splitlog` option of _robot_
""",
robot_name="splitlog",
robot_priority=500,
robot_is_flag=True,
)
suites: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Select suites by name. When this option is used with
--test, --include or --exclude, only tests in
matching suites and also matching other filtering
criteria are selected. Name can be a simple pattern
similarly as with --test and it can contain parent
name separated with a dot. For example, `-s X.Y`
selects suite `Y` only if its parent is `X`.
corresponds to the `-s --suite name *` option of _robot_
""",
robot_name="suite",
robot_priority=500,
robot_short_name="s",
)
suite_stat_level: Optional[int] = field(
description="""\
How many levels to show in `Statistics by Suite`
in log and report. By default all suite levels are
shown. Example: --suitestatlevel 3
corresponds to the `--suitestatlevel level` option of _robot_
""",
robot_name="suitestatlevel",
robot_priority=500,
)
tag_doc: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Add documentation to tags matching the given
pattern. Documentation is shown in `Test Details` and
also as a tooltip in `Statistics by Tag`. Pattern can
use `*`, `?` and `[]` as wildcards like --test.
Documentation can contain formatting like --doc.
Examples:
```
--tagdoc mytag:Example
--tagdoc "owner-*:Original author"
```
corresponds to the `--tagdoc pattern:doc *` option of _robot_
""",
robot_name="tagdoc",
robot_priority=500,
)
tag_stat_combine: Optional[List[Union[str, Dict[str, str]]]] = field(
description="""\
Create combined statistics based on tags.
These statistics are added into `Statistics by Tag`.
If the optional `name` is not given, name of the
combined tag is got from the specified tags. Tags are
matched using the same rules as with --include.
Examples:
```
--tagstatcombine requirement-*
--tagstatcombine tag1ANDtag2:My_name
```
corresponds to the `--tagstatcombine tags:name *` option of _robot_
""",
robot_name="tagstatcombine",
robot_priority=500,
)
tag_stat_exclude: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Exclude matching tags from `Statistics by Tag`.
This option can be used with --tagstatinclude
similarly as --exclude is used with --include.
corresponds to the `--tagstatexclude tag *` option of _robot_
""",
robot_name="tagstatexclude",
robot_priority=500,
)
tag_stat_include: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Include only matching tags in `Statistics by Tag`
in log and report. By default all tags are shown.
Given tag can be a pattern like with --include.
corresponds to the `--tagstatinclude tag *` option of _robot_
""",
robot_name="tagstatinclude",
robot_priority=500,
)
tag_stat_link: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Add external links into `Statistics by
Tag`. Pattern can use `*`, `?` and `[]` as wildcards
like --test. Characters matching to `*` and `?`
wildcards can be used in link and title with syntax
%N, where N is index of the match (starting from 1).
Examples:
```
--tagstatlink mytag:http://my.domain:Title
--tagstatlink "bug-*:http://url/id=%1:Issue Tracker"
```
corresponds to the `--tagstatlink pattern:link:title *` option of _robot_
""",
robot_name="tagstatlink",
robot_priority=500,
)
tasks: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Alias to --test. Especially applicable with --rpa.
corresponds to the `--task name *` option of _robot_
""",
robot_name="task",
robot_priority=500,
)
tests: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Select tests by name or by long name containing also
parent suite name like `Parent.Test`. Name is case
and space insensitive and it can also be a simple
pattern where `*` matches anything, `?` matches any
single character, and `[chars]` matches one character
in brackets.
corresponds to the `-t --test name *` option of _robot_
""",
robot_name="test",
robot_priority=500,
robot_short_name="t",
)
timestamp_outputs: Union[bool, Flag, None] = field(
description="""\
When this option is used, timestamp in a format
`YYYYMMDD-hhmmss` is added to all generated output
files between their basename and extension. For
example `-T -o output.xml -r report.html -l none`
creates files like `output-20070503-154410.xml` and
`report-20070503-154410.html`.
corresponds to the `-T --timestampoutputs` option of _robot_
""",
robot_name="timestampoutputs",
robot_priority=500,
robot_short_name="T",
robot_is_flag=True,
)
xunit: Optional[Union[str, StringExpression]] = field(
description="""\
xUnit compatible result file. Not created unless this
option is specified.
corresponds to the `-x --xunit file` option of _robot_
""",
robot_name="xunit",
robot_priority=500,
robot_short_name="x",
)
@dataclass
class CommonExtraOptions(BaseOptions):
"""Extra common options for all _robot_ commands."""
extra_excludes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --exclude option.
Select test cases not to run by tag. These tests are
not run even if included with --include. Tags are
matched using same rules as with --include.
corresponds to the `-e --exclude tag *` option of _robot_
""",
)
extra_expand_keywords: Optional[List[Union[str, NamePattern, TagPattern]]] = field(
description="""\
Appends entries to the --expandkeywords option.
Matching keywords will be automatically expanded in
the log file. Matching against keyword name or tags
work using same rules as with --removekeywords.
Examples:
```
--expandkeywords name:BuiltIn.Log
--expandkeywords tag:expand
```
corresponds to the `--expandkeywords name:<pattern>|tag:<pattern> *` option of _robot_
""",
)
extra_flatten_keywords: Optional[
List[Union[str, Literal["for", "while", "iteration"], NamePattern, TagPattern]]
] = field(
description="""\
Appends entries to the --flattenkeywords option.
Flattens matching keywords in the generated log file.
Matching keywords get all log messages from their
child keywords and children are discarded otherwise.
for: flatten FOR loops fully
while: flatten WHILE loops fully
iteration: flatten FOR/WHILE loop iterations
foritem: deprecated alias for `iteration`
name:<pattern>: flatten matched keywords using same
matching rules as with
`--removekeywords name:<pattern>`
tag:<pattern>: flatten matched keywords using same
matching rules as with
`--removekeywords tag:<pattern>`
corresponds to the `--flattenkeywords for|while|iteration|name:<pattern>|tag:<pattern> *` option of _robot_
""",
)
extra_includes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --include option.
Select tests by tag. Similarly as name with --test,
tag is case and space insensitive and it is possible
to use patterns with `*`, `?` and `[]` as wildcards.
Tags and patterns can also be combined together with
`AND`, `OR`, and `NOT` operators.
Examples:
```
--include foo --include bar*
--include fooANDbar*
```
corresponds to the `-i --include tag *` option of _robot_
""",
)
extra_metadata: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --metadata option.
Set metadata of the top level suite. Value can
contain formatting and be read from a file similarly
as --doc. Example: --metadata Version:1.2
corresponds to the `-M --metadata name:value *` option of _robot_
""",
)
extra_parse_include: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --parseinclude option.
Parse only files matching `pattern`. It can be:
- a file name or pattern like `example.robot` or
`*.robot` to parse all files matching that name,
- a file path like `path/to/example.robot`, or
- a directory path like `path/to/example` to parse
all files in that directory, recursively.
corresponds to the `-I --parseinclude pattern *` option of _robot_
""",
)
extra_pre_rebot_modifiers: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Appends entries to the --prerebotmodifier option.
Class to programmatically modify the result
model before creating reports and logs. Accepts
arguments the same way as with --listener.
corresponds to the `--prerebotmodifier modifier *` option of _robot_
""",
)
extra_python_path: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --pythonpath option.
Additional locations (directories, ZIPs) where to
search libraries and other extensions when they are
imported. Multiple paths can be given by separating
them with a colon (`:`) or by using this option
several times. Given path can also be a glob pattern
matching multiple paths.
Examples:
```
--pythonpath libs/
--pythonpath /opt/libs:libraries.zip
```
corresponds to the `-P --pythonpath path *` option of _robot_
""",
)
extra_remove_keywords: Optional[
List[Union[str, Literal["all", "passed", "for", "wuks"], NamePattern, TagPattern]]
] = field(
description="""\
Appends entries to the --removekeywords option.
Remove keyword data from the generated log file.
Keywords containing warnings are not removed except
in the `all` mode.
all: remove data from all keywords
passed: remove data only from keywords in passed
test cases and suites
for: remove passed iterations from for loops
while: remove passed iterations from while loops
wuks: remove all but the last failing keyword
inside `BuiltIn.Wait Until Keyword Succeeds`
name:<pattern>: remove data from keywords that match
the given pattern. The pattern is matched
against the full name of the keyword (e.g.
'MyLib.Keyword', 'resource.Second Keyword'),
is case, space, and underscore insensitive,
and may contain `*`, `?` and `[]` wildcards.
Examples:
```
--removekeywords name:Lib.HugeKw
--removekeywords name:myresource.*
```
tag:<pattern>: remove data from keywords that match
the given pattern. Tags are case and space
insensitive and patterns can contain `*`,
`?` and `[]` wildcards. Tags and patterns
can also be combined together with `AND`,
`OR`, and `NOT` operators.
Examples:
```
--removekeywords foo
--removekeywords fooANDbar*
```
corresponds to the `--removekeywords all|passed|for|wuks|name:<pattern>|tag:<pattern> *` option of _robot_
""",
)
extra_set_tag: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --settag option.
Sets given tag(s) to all executed tests.
corresponds to the `-G --settag tag *` option of _robot_
""",
)
extra_suites: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --suite option.
Select suites by name. When this option is used with
--test, --include or --exclude, only tests in
matching suites and also matching other filtering
criteria are selected. Name can be a simple pattern
similarly as with --test and it can contain parent
name separated with a dot. For example, `-s X.Y`
selects suite `Y` only if its parent is `X`.
corresponds to the `-s --suite name *` option of _robot_
""",
)
extra_tag_doc: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --tagdoc option.
Add documentation to tags matching the given
pattern. Documentation is shown in `Test Details` and
also as a tooltip in `Statistics by Tag`. Pattern can
use `*`, `?` and `[]` as wildcards like --test.
Documentation can contain formatting like --doc.
Examples:
```
--tagdoc mytag:Example
--tagdoc "owner-*:Original author"
```
corresponds to the `--tagdoc pattern:doc *` option of _robot_
""",
)
extra_tag_stat_combine: Optional[List[Union[str, Dict[str, str]]]] = field(
description="""\
Appends entries to the --tagstatcombine option.
Create combined statistics based on tags.
These statistics are added into `Statistics by Tag`.
If the optional `name` is not given, name of the
combined tag is got from the specified tags. Tags are
matched using the same rules as with --include.
Examples:
```
--tagstatcombine requirement-*
--tagstatcombine tag1ANDtag2:My_name
```
corresponds to the `--tagstatcombine tags:name *` option of _robot_
""",
)
extra_tag_stat_exclude: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --tagstatexclude option.
Exclude matching tags from `Statistics by Tag`.
This option can be used with --tagstatinclude
similarly as --exclude is used with --include.
corresponds to the `--tagstatexclude tag *` option of _robot_
""",
)
extra_tag_stat_include: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --tagstatinclude option.
Include only matching tags in `Statistics by Tag`
in log and report. By default all tags are shown.
Given tag can be a pattern like with --include.
corresponds to the `--tagstatinclude tag *` option of _robot_
""",
)
extra_tag_stat_link: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --tagstatlink option.
Add external links into `Statistics by
Tag`. Pattern can use `*`, `?` and `[]` as wildcards
like --test. Characters matching to `*` and `?`
wildcards can be used in link and title with syntax
%N, where N is index of the match (starting from 1).
Examples:
```
--tagstatlink mytag:http://my.domain:Title
--tagstatlink "bug-*:http://url/id=%1:Issue Tracker"
```
corresponds to the `--tagstatlink pattern:link:title *` option of _robot_
""",
)
extra_tasks: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --task option.
Alias to --test. Especially applicable with --rpa.
corresponds to the `--task name *` option of _robot_
""",
)
extra_tests: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --test option.
Select tests by name or by long name containing also
parent suite name like `Parent.Test`. Name is case
and space insensitive and it can also be a simple
pattern where `*` matches anything, `?` matches any
single character, and `[chars]` matches one character
in brackets.
corresponds to the `-t --test name *` option of _robot_
""",
)
@dataclass
class RobotOptions(BaseOptions):
"""Options for _robot_ command."""
console: Optional[Literal["verbose", "dotted", "skipped", "quiet", "none"]] = field(
description="""\
How to report execution on the console.
verbose: report every suite and test (default)
dotted: only show `.` for passed test, `s` for
skipped tests, and `F` for failed tests
quiet: no output except for errors and warnings
none: no output whatsoever
corresponds to the `--console type` option of _robot_
""",
robot_name="console",
robot_priority=500,
)
console_markers: Optional[Literal["auto", "on", "off"]] = field(
description="""\
Show markers on the console when top level
keywords in a test case end. Values have same
semantics as with --consolecolors.
corresponds to the `-K --consolemarkers auto|on|off` option of _robot_
""",
robot_name="consolemarkers",
robot_priority=500,
robot_short_name="K",
)
console_width: Optional[int] = field(
description="""\
Width of the console output. Default is 78.
corresponds to the `-W --consolewidth chars` option of _robot_
""",
robot_name="consolewidth",
robot_priority=500,
robot_short_name="W",
)
debug_file: Optional[Union[str, StringExpression]] = field(
description="""\
Debug file written during execution. Not created
unless this option is specified.
corresponds to the `-b --debugfile file` option of _robot_
""",
robot_name="debugfile",
robot_priority=500,
robot_short_name="b",
)
dotted: Union[bool, Flag, None] = field(
description="""\
Shortcut for `--console dotted`.
corresponds to the `-. --dotted` option of _robot_
""",
robot_name="dotted",
robot_priority=500,
robot_short_name=".",
robot_is_flag=True,
)
dry_run: Union[bool, Flag, None] = field(
description="""\
Verifies test data and runs tests so that library
keywords are not executed.
corresponds to the `--dryrun` option of _robot_
""",
robot_name="dryrun",
robot_priority=500,
robot_is_flag=True,
)
exit_on_error: Union[bool, Flag, None] = field(
description="""\
Stops test execution if any error occurs when parsing
test data, importing libraries, and so on.
corresponds to the `--exitonerror` option of _robot_
""",
robot_name="exitonerror",
robot_priority=500,
robot_is_flag=True,
)
exit_on_failure: Union[bool, Flag, None] = field(
description="""\
Stops test execution if any test fails.
corresponds to the `-X --exitonfailure` option of _robot_
""",
robot_name="exitonfailure",
robot_priority=500,
robot_short_name="X",
robot_is_flag=True,
)
extensions: Optional[Union[str, StringExpression]] = field(
description="""\
Parse only files with this extension when executing
a directory. Has no effect when running individual
files or when using resource files. If more than one
extension is needed, separate them with a colon.
Examples:
```
`--extension txt`, `--extension robot:txt`
```
Only `*.robot` files are parsed by default.
corresponds to the `-F --extension value` option of _robot_
""",
robot_name="extension",
robot_priority=500,
robot_short_name="F",
)
languages: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Activate localization. `lang` can be a name or a code
of a built-in language, or a path or a module name of
a custom language file.
corresponds to the `--language lang *` option of _robot_
""",
robot_name="language",
robot_priority=500,
)
listeners: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Class or module for monitoring test execution.
Gets notifications e.g. when tests start and end.
Arguments to the listener class can be given after
the name using a colon or a semicolon as a separator.
Examples:
```
--listener MyListener
--listener path/to/Listener.py:arg1:arg2
```
corresponds to the `--listener listener *` option of _robot_
""",
robot_name="listener",
robot_priority=500,
)
log_level: Optional[Union[str, StringExpression]] = field(
description="""\
Threshold level for logging. Available levels: TRACE,
DEBUG, INFO (default), WARN, NONE (no logging). Use
syntax `LOGLEVEL:DEFAULT` to define the default
visible log level in log files.
Examples:
```
--loglevel DEBUG
--loglevel DEBUG:INFO
```
corresponds to the `-L --loglevel level` option of _robot_
""",
robot_name="loglevel",
robot_priority=500,
robot_short_name="L",
)
max_assign_length: Optional[int] = field(
description="""\
Maximum number of characters to show in log
when variables are assigned. Zero or negative values
can be used to avoid showing assigned values at all.
Default is 200.
corresponds to the `--maxassignlength characters` option of _robot_
""",
robot_name="maxassignlength",
robot_priority=500,
)
max_error_lines: Optional[int] = field(
description="""\
Maximum number of error message lines to show in
report when tests fail. Default is 40, minimum is 10
and `NONE` can be used to show the full message.
corresponds to the `--maxerrorlines lines` option of _robot_
""",
robot_name="maxerrorlines",
robot_priority=500,
)
output: Optional[Union[str, StringExpression]] = field(
description="""\
XML output file. Given path, similarly as paths given
to --log, --report, --xunit, and --debugfile, is
relative to --outputdir unless given as an absolute
path. Other output files are created based on XML
output files after the test execution and XML outputs
can also be further processed with Rebot tool. Can be
disabled by giving a special value `NONE`.
Default: output.xml
corresponds to the `-o --output file` option of _robot_
""",
robot_name="output",
robot_priority=500,
robot_short_name="o",
)
parsers: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Custom parser class or module. Parser classes accept
arguments the same way as with --listener.
corresponds to the `--parser parser *` option of _robot_
""",
robot_name="parser",
robot_priority=500,
)
pre_run_modifiers: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Class to programmatically modify the suite
structure before execution. Accepts arguments the
same way as with --listener.
corresponds to the `--prerunmodifier modifier *` option of _robot_
""",
robot_name="prerunmodifier",
robot_priority=500,
)
quiet: Union[bool, Flag, None] = field(
description="""\
Shortcut for `--console quiet`.
corresponds to the `--quiet` option of _robot_
""",
robot_name="quiet",
robot_priority=500,
robot_is_flag=True,
)
randomize: Optional[Union[str, Literal["all", "suites", "tests", "none"]]] = field(
description="""\
Randomizes the test execution order.
all: randomizes both suites and tests
suites: randomizes suites
tests: randomizes tests
none: no randomization (default)
Use syntax `VALUE:SEED` to give a custom random seed.
The seed must be an integer.
Examples:
```
--randomize all
--randomize tests:1234
```
corresponds to the `--randomize all|suites|tests|none` option of _robot_
""",
robot_name="randomize",
robot_priority=500,
)
re_run_failed: Optional[Union[str, StringExpression]] = field(
description="""\
Select failed tests from an earlier output file to be
re-executed. Equivalent to selecting same tests
individually using --test.
corresponds to the `-R --rerunfailed output` option of _robot_
""",
robot_name="rerunfailed",
robot_priority=500,
robot_short_name="R",
)
re_run_failed_suites: Optional[Union[str, StringExpression]] = field(
description="""\
Select failed suites from an earlier output
file to be re-executed.
corresponds to the `-S --rerunfailedsuites output` option of _robot_
""",
robot_name="rerunfailedsuites",
robot_priority=500,
robot_short_name="S",
)
run_empty_suite: Union[bool, Flag, None] = field(
description="""\
Executes suite even if it contains no tests. Useful
e.g. with --include/--exclude when it is not an error
that no test matches the condition.
corresponds to the `--runemptysuite` option of _robot_
""",
robot_name="runemptysuite",
robot_priority=500,
robot_is_flag=True,
)
skip: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Tests having given tag will be skipped. Tag can be
a pattern.
corresponds to the `--skip tag *` option of _robot_
""",
robot_name="skip",
robot_priority=500,
)
skip_on_failure: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Tests having given tag will be skipped if they fail.
Tag can be a pattern
corresponds to the `--skiponfailure tag *` option of _robot_
""",
robot_name="skiponfailure",
robot_priority=500,
)
skip_teardown_on_exit: Union[bool, Flag, None] = field(
description="""\
Causes teardowns to be skipped if test execution is
stopped prematurely.
corresponds to the `--skipteardownonexit` option of _robot_
""",
robot_name="skipteardownonexit",
robot_priority=500,
robot_is_flag=True,
)
variables: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Set variables in the test data. Only scalar
variables with string value are supported and name is
given without `${}`. See --variablefile for a more
powerful variable setting mechanism.
Examples:
```
--variable name:Robot => ${name} = `Robot`
-v "hello:Hello world" => ${hello} = `Hello world`
-v x: -v y:42 => ${x} = ``, ${y} = `42`
```
corresponds to the `-v --variable name:value *` option of _robot_
""",
robot_name="variable",
robot_priority=500,
robot_short_name="v",
)
variable_files: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Python or YAML file file to read variables from.
Possible arguments to the variable file can be given
after the path using colon or semicolon as separator.
Examples:
```
--variablefile path/vars.yaml
--variablefile environment.py:testing
```
corresponds to the `-V --variablefile path *` option of _robot_
""",
robot_name="variablefile",
robot_priority=500,
robot_short_name="V",
)
@dataclass
class RobotExtraOptions(BaseOptions):
"""Extra options for _robot_ command."""
extra_languages: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --language option.
Activate localization. `lang` can be a name or a code
of a built-in language, or a path or a module name of
a custom language file.
corresponds to the `--language lang *` option of _rebot_
""",
)
extra_listeners: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Appends entries to the --listener option.
Class or module for monitoring test execution.
Gets notifications e.g. when tests start and end.
Arguments to the listener class can be given after
the name using a colon or a semicolon as a separator.
Examples:
```
--listener MyListener
--listener path/to/Listener.py:arg1:arg2
```
corresponds to the `--listener listener *` option of _rebot_
""",
)
extra_parsers: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Appends entries to the --parser option.
Custom parser class or module. Parser classes accept
arguments the same way as with --listener.
corresponds to the `--parser parser *` option of _rebot_
""",
)
extra_pre_run_modifiers: Optional[Dict[str, List[Union[str, StringExpression]]]] = field(
description="""\
Appends entries to the --prerunmodifier option.
Class to programmatically modify the suite
structure before execution. Accepts arguments the
same way as with --listener.
corresponds to the `--prerunmodifier modifier *` option of _rebot_
""",
)
extra_skip: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --skip option.
Tests having given tag will be skipped. Tag can be
a pattern.
corresponds to the `--skip tag *` option of _rebot_
""",
)
extra_skip_on_failure: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --skiponfailure option.
Tests having given tag will be skipped if they fail.
Tag can be a pattern
corresponds to the `--skiponfailure tag *` option of _rebot_
""",
)
extra_variables: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --variable option.
Set variables in the test data. Only scalar
variables with string value are supported and name is
given without `${}`. See --variablefile for a more
powerful variable setting mechanism.
Examples:
```
--variable name:Robot => ${name} = `Robot`
-v "hello:Hello world" => ${hello} = `Hello world`
-v x: -v y:42 => ${x} = ``, ${y} = `42`
```
corresponds to the `-v --variable name:value *` option of _rebot_
""",
)
extra_variable_files: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --variablefile option.
Python or YAML file file to read variables from.
Possible arguments to the variable file can be given
after the path using colon or semicolon as separator.
Examples:
```
--variablefile path/vars.yaml
--variablefile environment.py:testing
```
corresponds to the `-V --variablefile path *` option of _rebot_
""",
)
@dataclass
class RebotOptions(BaseOptions):
"""Options for _rebot_ command."""
end_time: Optional[Union[str, StringExpression]] = field(
description="""\
Same as --starttime but for end time. If both options
are used, elapsed time of the suite is calculated
based on them. For combined suites, it is otherwise
calculated by adding elapsed times of the combined
suites together.
corresponds to the `--endtime timestamp` option of _rebot_
""",
robot_name="endtime",
robot_priority=500,
)
log_level: Optional[Union[str, StringExpression]] = field(
description="""\
Threshold for selecting messages. Available levels:
TRACE (default), DEBUG, INFO, WARN, NONE (no msgs).
Use syntax `LOGLEVEL:DEFAULT` to define the default
visible log level in log files.
Examples:
```
--loglevel DEBUG
--loglevel DEBUG:INFO
```
corresponds to the `-L --loglevel level` option of _rebot_
""",
robot_name="loglevel",
robot_priority=500,
robot_short_name="L",
)
merge: Union[bool, Flag, None] = field(
description="""\
When combining results, merge outputs together
instead of putting them under a new top level suite.
Example: rebot --merge orig.xml rerun.xml
corresponds to the `-R --merge` option of _rebot_
""",
robot_name="merge",
robot_priority=500,
robot_short_name="R",
robot_is_flag=True,
)
output: Optional[Union[str, StringExpression]] = field(
description="""\
XML output file. Not created unless this option is
specified. Given path, similarly as paths given to
--log, --report and --xunit, is relative to
--outputdir unless given as an absolute path.
corresponds to the `-o --output file` option of _rebot_
""",
robot_name="output",
robot_priority=500,
robot_short_name="o",
)
process_empty_suite: Union[bool, Flag, None] = field(
description="""\
Processes output also if the top level suite is
empty. Useful e.g. with --include/--exclude when it
is not an error that there are no matches.
Use --skiponfailure when starting execution instead.
corresponds to the `--processemptysuite` option of _rebot_
""",
robot_name="processemptysuite",
robot_priority=500,
robot_is_flag=True,
)
start_time: Optional[Union[str, StringExpression]] = field(
description="""\
Set execution start time. Timestamp must be given in
format `2007-10-01 15:12:42.268` where all separators
are optional (e.g. `20071001151242268` is ok too) and
parts from milliseconds to hours can be omitted if
they are zero (e.g. `2007-10-01`). This can be used
to override start time of a single suite or to set
start time for a combined suite, which would
otherwise be `N/A`.
corresponds to the `--starttime timestamp` option of _rebot_
""",
robot_name="starttime",
robot_priority=500,
)
@dataclass
class LibDocOptions(BaseOptions):
"""Options for _libdoc_ command."""
doc_format: Optional[Literal["ROBOT", "HTML", "TEXT", "REST"]] = field(
description="""\
Specifies the source documentation format. Possible
values are Robot Framework's documentation format,
HTML, plain text, and reStructuredText. The default
value can be specified in library source code and
the initial default value is ROBOT.
corresponds to the `-F --docformat ROBOT|HTML|TEXT|REST` option of _libdoc_
""",
robot_name="docformat",
robot_priority=500,
robot_short_name="F",
)
format: Optional[Literal["HTML", "XML", "JSON", "LIBSPEC"]] = field(
description="""\
Specifies whether to generate an HTML output for
humans or a machine readable spec file in XML or JSON
format. The LIBSPEC format means XML spec with
documentations converted to HTML. The default format
is got from the output file extension.
corresponds to the `-f --format HTML|XML|JSON|LIBSPEC` option of _libdoc_
""",
robot_name="format",
robot_priority=500,
robot_short_name="f",
)
name: Optional[Union[str, StringExpression]] = field(
description="""\
Sets the name of the documented library or resource.
corresponds to the `-n --name name` option of _libdoc_
""",
robot_name="name",
robot_priority=500,
robot_short_name="n",
)
python_path: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Additional locations where to search for libraries
and resources.
corresponds to the `-P --pythonpath path *` option of _libdoc_
""",
robot_name="pythonpath",
robot_priority=500,
robot_short_name="P",
)
quiet: Union[bool, Flag, None] = field(
description="""\
Do not print the path of the generated output file
to the console. New in RF 4.0.
corresponds to the `--quiet` option of _libdoc_
""",
robot_name="quiet",
robot_priority=500,
robot_is_flag=True,
)
spec_doc_format: Optional[Literal["RAW", "HTML"]] = field(
description="""\
Specifies the documentation format used with XML and
JSON spec files. RAW means preserving the original
documentation format and HTML means converting
documentation to HTML. The default is RAW with XML
spec files and HTML with JSON specs and when using
the special LIBSPEC format. New in RF 4.0.
corresponds to the `-s --specdocformat RAW|HTML` option of _libdoc_
""",
robot_name="specdocformat",
robot_priority=500,
robot_short_name="s",
)
theme: Optional[Literal["DARK", "LIGHT", "NONE"]] = field(
description="""\
Use dark or light HTML theme. If this option is not
used, or the value is NONE, the theme is selected
based on the browser color scheme. New in RF 6.0.
corresponds to the `--theme DARK|LIGHT|NONE` option of _libdoc_
""",
robot_name="theme",
robot_priority=500,
)
@dataclass
class LibDocExtraOptions(BaseOptions):
"""Extra options for _libdoc_ command."""
extra_python_path: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --pythonpath option.
Additional locations where to search for libraries
and resources.
corresponds to the `-P --pythonpath path *` option of _libdoc_
""",
)
@dataclass
class TestDocOptions(BaseOptions):
"""Options for _testdoc_ command."""
doc: Optional[Union[str, StringExpression]] = field(
description="""\
Override the documentation of the top level suite.
corresponds to the `-D --doc document` option of _testdoc_
""",
robot_name="doc",
robot_priority=500,
robot_short_name="D",
)
excludes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Exclude tests by tags.
corresponds to the `-e --exclude tag *` option of _testdoc_
""",
robot_name="exclude",
robot_priority=500,
robot_short_name="e",
)
includes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Include tests by tags.
corresponds to the `-i --include tag *` option of _testdoc_
""",
robot_name="include",
robot_priority=500,
robot_short_name="i",
)
metadata: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Set/override metadata of the top level suite.
corresponds to the `-M --metadata name:value *` option of _testdoc_
""",
robot_name="metadata",
robot_priority=500,
robot_short_name="M",
)
name: Optional[Union[str, StringExpression]] = field(
description="""\
Override the name of the top level suite.
corresponds to the `-N --name name` option of _testdoc_
""",
robot_name="name",
robot_priority=500,
robot_short_name="N",
)
set_tag: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Set given tag(s) to all test cases.
corresponds to the `-G --settag tag *` option of _testdoc_
""",
robot_name="settag",
robot_priority=500,
robot_short_name="G",
)
suites: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Include suites by name.
corresponds to the `-s --suite name *` option of _testdoc_
""",
robot_name="suite",
robot_priority=500,
robot_short_name="s",
)
tests: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Include tests by name.
corresponds to the `-t --test name *` option of _testdoc_
""",
robot_name="test",
robot_priority=500,
robot_short_name="t",
)
title: Optional[Union[str, StringExpression]] = field(
description="""\
Set the title of the generated documentation.
Underscores in the title are converted to spaces.
The default title is the name of the top level suite.
corresponds to the `-T --title title` option of _testdoc_
""",
robot_name="title",
robot_priority=500,
robot_short_name="T",
)
@dataclass
class TestDocExtraOptions(BaseOptions):
"""Extra options for _testdoc_ command."""
extra_excludes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --exclude option.
Exclude tests by tags.
corresponds to the `-e --exclude tag *` option of _testdoc_
""",
)
extra_includes: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --include option.
Include tests by tags.
corresponds to the `-i --include tag *` option of _testdoc_
""",
)
extra_metadata: Optional[Dict[str, Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --metadata option.
Set/override metadata of the top level suite.
corresponds to the `-M --metadata name:value *` option of _testdoc_
""",
)
extra_set_tag: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --settag option.
Set given tag(s) to all test cases.
corresponds to the `-G --settag tag *` option of _testdoc_
""",
)
extra_suites: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --suite option.
Include suites by name.
corresponds to the `-s --suite name *` option of _testdoc_
""",
)
extra_tests: Optional[List[Union[str, StringExpression]]] = field(
description="""\
Appends entries to the --test option.
Include tests by name.
corresponds to the `-t --test name *` option of _testdoc_
""",
)
# end generated code
@dataclass
class RebotProfile(RebotOptions, CommonOptions, CommonExtraOptions):
"""Profile for _rebot_ command."""
@dataclass
class LibDocProfile(LibDocOptions, LibDocExtraOptions):
"""Profile for _libdoc_ command."""
@dataclass
class TestDocProfile(TestDocOptions, TestDocExtraOptions):
"""Profile for _testdoc_ command."""
@dataclass
class RobotBaseProfile(CommonOptions, CommonExtraOptions, RobotOptions, RobotExtraOptions):
"""Base profile for Robot Framework."""
args: Optional[List[str]] = field(
description="""\
Arguments to be passed to _robot_.
Examples:
```toml
args = ["-t", "abc"]
```
""",
robot_priority=1000,
)
paths: Union[str, List[str], None] = field(
description="""\
Specifies the paths where robot/robotcode should discover tests.
If no paths are given at the command line this value is used.
Examples:
```toml
paths = ["tests"]
```
Corresponds to the `paths` argument of __robot__.
"""
)
env: Optional[Dict[str, str]] = field(
description="""\
Define environment variables to be set before running tests.
Examples:
```toml
[env]
TEST_VAR = "test"
SECRET = "password"
```
""",
)
rebot: Optional[RebotProfile] = field(
description="""\
Options to be passed to _rebot_.
"""
)
libdoc: Optional[LibDocProfile] = field(
description="""\
Options to be passed to _libdoc_.
"""
)
testdoc: Optional[TestDocProfile] = field(
description="""\
Options to be passed to _testdoc_.
"""
)
def save(self, path: "os.PathLike[str]") -> None:
Path(path).parent.mkdir(parents=True, exist_ok=True)
with Path(path).open("w", encoding="utf-8") as f:
f.write(tomli_w.dumps(as_dict(self, remove_defaults=True)))
@dataclass
class RobotExtraBaseProfile(RobotBaseProfile):
"""Base profile for Robot Framework with Extras."""
extra_args: Optional[List[str]] = field(
description="""\
Append extra arguments to be passed to _robot_.
""",
)
extra_env: Optional[Dict[str, str]] = field(
description="""\
Append extra environment variables to be set before tests.
""",
)
extra_paths: Union[str, List[str], None] = field(
description="""\
Append extra entries to the paths argument.
Examples:
```toml
paths = ["tests"]
```
"""
)
@dataclass
class RobotProfile(RobotExtraBaseProfile):
"""Robot Framework configuration profile."""
description: Optional[str] = field(description="Description of the profile.")
detached: Optional[bool] = field(
description="""\
The profile should be detached.
Detached means it is not inherited from the main profile.
""",
)
enabled: Union[bool, Condition, None] = field(
description="""\
If enabled the profile is used. You can also use and `if` condition
to calculate the enabled state.
Examples:
```toml
# alway disabled
enabled = false
```
```toml
# enabled if TEST_VAR is set
enabled = { if = 'environ.get("CI") == "true"' }
```
"""
)
precedence: Optional[int] = field(
description="""\
Precedence of the profile. Lower values are executed first. If not set the order is undefined.
"""
)
@dataclass
class RobotConfig(RobotExtraBaseProfile):
"""Robot Framework configuration."""
default_profiles: Union[str, List[str], None] = field(
description="""\
Selects the Default profile if no profile is given at command line.
Examples:
```toml
default_profiles = "default"
```
```toml
default_profiles = ["default", "Firefox"]
```
""",
)
profiles: Optional[Dict[str, RobotProfile]] = field(
metadata={"description": "Execution profiles."},
)
extra_profiles: Optional[Dict[str, RobotProfile]] = field(
metadata={"description": "Extra execution profiles."},
)
tool: Any = field(
metadata={"description": "Tool configuration."},
)
def select_profiles(
self, *names: str, verbose_callback: Optional[Callable[..., None]] = None
) -> Dict[str, RobotProfile]:
result: Dict[str, RobotProfile] = {}
profiles = self.profiles or {}
if not names:
if verbose_callback:
verbose_callback("No profiles given, try to check if there are default profiles specified.")
default_profile = (
[self.default_profiles] if isinstance(self.default_profiles, str) else self.default_profiles
)
if verbose_callback and default_profile:
verbose_callback(f"Using default profiles: {', '.join( default_profile)}.")
names = (*(default_profile or ()),)
for name in names:
profile_names = [p for p in profiles.keys() if fnmatch.fnmatchcase(p, name)]
if not profile_names:
raise ValueError(f"Can't find any profiles matching the pattern '{name}'.")
for v in profile_names:
result.update({v: profiles[v]})
return result
def combine_profiles(self, *names: str, verbose_callback: Optional[Callable[..., None]] = None) -> RobotBaseProfile:
type_hints = get_type_hints(RobotBaseProfile)
base_field_names = [f.name for f in dataclasses.fields(RobotBaseProfile)]
result = RobotBaseProfile(
**{
f.name: self._verified_value(f.name, new, type_hints[f.name], self)
for f in dataclasses.fields(RobotBaseProfile)
if (new := getattr(self, f.name)) is not None
}
)
selected_profiles = self.select_profiles(*names, verbose_callback=verbose_callback)
if verbose_callback:
if selected_profiles:
verbose_callback(f"Select profiles: {', '.join(selected_profiles.keys())}")
else:
verbose_callback("No profiles selected.")
for profile_name, profile in sorted(selected_profiles.items(), key=lambda x: x[1].precedence or 0):
try:
if profile.enabled is not None and (
isinstance(profile.enabled, Condition) and not profile.enabled.evaluate() or not profile.enabled
):
if verbose_callback:
verbose_callback(f'Skipping profile "{profile_name}" because it\'s disabled.')
continue
except EvaluationError as e:
raise ValueError(f'Error evaluating "enabled" condition for profile "{profile_name}": {e}') from e
if verbose_callback:
verbose_callback(f'Using profile "{profile_name}".')
if profile.detached:
result = RobotBaseProfile()
for f in dataclasses.fields(profile):
if f.name.startswith("extra_"):
new = self._verified_value(f.name, getattr(profile, f.name), type_hints[f.name[6:]], profile)
if new is None:
continue
old = getattr(result, f.name[6:])
if old is None:
setattr(result, f.name[6:], new)
else:
if isinstance(old, dict):
setattr(result, f.name[6:], {**old, **new})
elif isinstance(old, list):
setattr(result, f.name[6:], [*old, *new])
elif isinstance(old, tuple):
setattr(result, f.name[6:], (*old, *new))
else:
setattr(result, f.name[6:], new)
continue
if f.name not in base_field_names:
continue
if getattr(profile, f"extra_{f.name}", None) is not None:
continue
new = self._verified_value(f.name, getattr(profile, f.name), type_hints[f.name], profile)
if new is not None:
setattr(result, f.name, new)
return result | /robotcode_robot-0.54.3-py3-none-any.whl/robotcode/robot/config/model.py | 0.80969 | 0.34319 | model.py | pypi |
import os
from pathlib import Path
from typing import Any, Optional, Tuple, cast
import click
from robot.errors import DataError, Information
from robot.libdoc import USAGE, LibDoc
from robot.version import get_full_version
from robotcode.plugin import Application, pass_application
from robotcode.robot.config.loader import load_config_from_path
from robotcode.robot.config.model import LibDocProfile
from robotcode.robot.config.utils import get_config_files
from ..__version__ import __version__
class LibDocEx(LibDoc):
def __init__(self, dry: bool, root_folder: Optional[Path]) -> None:
super().__init__()
self.dry = dry
self.root_folder = root_folder
def parse_arguments(self, cli_args: Any) -> Any:
options, arguments = super().parse_arguments(cli_args)
if self.dry:
line_end = "\n"
raise Information(
"Dry run, not executing any commands. "
f"Would execute libdoc with the following options and arguments:\n"
f'{line_end.join((*(f"{k} = {v!r}" for k, v in options.items()) ,*arguments))}'
)
return options, arguments
def main(self, arguments: Any, **options: Any) -> Any:
if self.root_folder is not None:
os.chdir(self.root_folder)
return super().main(arguments, **options)
@click.command(
context_settings={
"allow_extra_args": True,
"ignore_unknown_options": True,
},
add_help_option=True,
epilog='Use "-- --help" to see the `libdoc` help.',
)
@click.version_option(
version=__version__,
package_name="robotcode.runner.libdoc",
prog_name="RobotCode libdoc",
message=f"%(prog)s %(version)s\n{USAGE.splitlines()[0].split(' -- ')[0].strip()} {get_full_version()}",
)
@click.argument("robot_options_and_args", nargs=-1, type=click.Path())
@pass_application
def libdoc(
app: Application,
robot_options_and_args: Tuple[str, ...],
) -> None:
"""Runs `libdoc` with the selected configuration, profiles, options and arguments.
The options and arguments are passed to `libdoc` as is.
"""
robot_arguments = None
try:
_, robot_arguments = LibDoc().parse_arguments(robot_options_and_args)
except (DataError, Information):
pass
config_files, root_folder, _ = get_config_files(
robot_arguments, app.config.config_files, verbose_callback=app.verbose
)
try:
profile = (
load_config_from_path(*config_files)
.combine_profiles(*(app.config.profiles or []), verbose_callback=app.verbose)
.evaluated()
)
except (TypeError, ValueError) as e:
raise click.ClickException(str(e)) from e
libdoc_options = profile.libdoc
if libdoc_options is None:
libdoc_options = LibDocProfile()
libdoc_options.add_options(profile)
options = libdoc_options.build_command_line()
if profile.env:
for k, v in profile.env.items():
os.environ[k] = v
app.verbose(lambda: f"Set environment variable {k} to {v}")
app.verbose(
lambda: "Executing libdoc robot with the following options:\n "
+ " ".join(f'"{o}"' for o in (options + list(robot_options_and_args)))
)
app.exit(
cast(
int,
LibDocEx(app.config.dry, root_folder).execute_cli((*options, *robot_options_and_args), exit=False),
)
) | /robotcode_runner-0.54.3-py3-none-any.whl/robotcode/runner/cli/libdoc.py | 0.752195 | 0.197116 | libdoc.py | pypi |
import os
from pathlib import Path
from typing import Any, Optional, Tuple, cast
import click
from robot.errors import DataError, Information
from robot.rebot import USAGE, Rebot
from robot.version import get_full_version
from robotcode.plugin import Application, pass_application
from robotcode.robot.config.loader import load_config_from_path
from robotcode.robot.config.model import RebotProfile
from robotcode.robot.config.utils import get_config_files
from ..__version__ import __version__
class RebotEx(Rebot):
def __init__(self, dry: bool, root_folder: Optional[Path]) -> None:
super().__init__()
self.dry = dry
self.root_folder = root_folder
def parse_arguments(self, cli_args: Any) -> Any:
options, arguments = super().parse_arguments(cli_args)
if self.dry:
line_end = "\n"
raise Information(
"Dry run, not executing any commands. "
f"Would execute libdoc with the following options and arguments:\n"
f'{line_end.join((*(f"{k} = {v!r}" for k, v in options.items()) ,*arguments))}'
)
return options, arguments
def main(self, arguments: Any, **options: Any) -> Any:
if self.root_folder is not None:
os.chdir(self.root_folder)
return super().main(arguments, **options)
@click.command(
context_settings={
"allow_extra_args": True,
"ignore_unknown_options": True,
},
add_help_option=True,
epilog='Use "-- --help" to see `rebot` help.',
)
@click.version_option(
version=__version__,
package_name="robotcode.runner.rebot",
prog_name="RobotCode rebot",
message=f"%(prog)s %(version)s\n{USAGE.splitlines()[0].split(' -- ')[0].strip()} {get_full_version()}",
)
@click.argument("robot_options_and_args", nargs=-1, type=click.Path())
@pass_application
def rebot(
app: Application,
robot_options_and_args: Tuple[str, ...],
) -> None:
"""Runs `rebot` with the selected configuration, profiles, options and arguments.
The options and arguments are passed to `rebot` as is.
"""
robot_arguments = None
try:
_, robot_arguments = Rebot().parse_arguments(robot_options_and_args)
except (DataError, Information):
pass
config_files, root_folder, _ = get_config_files(
robot_arguments, app.config.config_files, verbose_callback=app.verbose
)
try:
profile = (
load_config_from_path(*config_files)
.combine_profiles(*(app.config.profiles or []), verbose_callback=app.verbose)
.evaluated()
)
except (TypeError, ValueError) as e:
raise click.ClickException(str(e)) from e
rebot_options = profile.rebot
if rebot_options is None:
rebot_options = RebotProfile()
rebot_options.add_options(profile)
try:
options = rebot_options.build_command_line()
except (TypeError, ValueError) as e:
raise click.ClickException(str(e)) from e
if profile.env:
for k, v in profile.env.items():
os.environ[k] = v
app.verbose(lambda: f"Set environment variable {k} to {v}")
app.verbose(
lambda: "Executing rebot with the following options:\n "
+ " ".join(f'"{o}"' for o in (options + list(robot_options_and_args)))
)
app.exit(
cast(
int,
RebotEx(app.config.dry, root_folder).execute_cli((*options, *robot_options_and_args), exit=False),
)
) | /robotcode_runner-0.54.3-py3-none-any.whl/robotcode/runner/cli/rebot.py | 0.742795 | 0.239772 | rebot.py | pypi |
import os
import sys
from pathlib import Path
from typing import Any, List, Optional, Set, Tuple, Union, cast
import click
from robot.errors import DataError, Information
from robot.run import USAGE, RobotFramework
from robot.version import get_full_version
from robotcode.plugin import Application, pass_application
from robotcode.plugin.click_helper.aliases import AliasedCommand
from robotcode.plugin.click_helper.types import add_options
from robotcode.robot.config.loader import load_config_from_path
from robotcode.robot.config.model import RobotBaseProfile
from robotcode.robot.config.utils import get_config_files
from ..__version__ import __version__
class RobotFrameworkEx(RobotFramework):
def __init__(self, app: Application, paths: List[str], dry: bool, root_folder: Optional[Path]) -> None:
super().__init__()
self.app = app
self.paths = paths
self.dry = dry
self.root_folder = root_folder
self._orig_cwd = Path.cwd()
def parse_arguments(self, cli_args: Any) -> Any:
if self.root_folder is not None and Path.cwd() != self.root_folder:
self.app.verbose(f"Changing working directory from {self._orig_cwd} to {self.root_folder}")
os.chdir(self.root_folder)
try:
options, arguments = super().parse_arguments(cli_args)
if self.root_folder is not None:
for i, arg in enumerate(arguments.copy()):
if Path(arg).is_absolute():
continue
arguments[i] = str((self._orig_cwd / Path(arg)).absolute().relative_to(self.root_folder))
except DataError:
options, arguments = super().parse_arguments((*cli_args, *self.paths))
if not arguments:
arguments = self.paths
if self.dry:
line_end = "\n"
raise Information(
"Dry run, not executing any commands. "
f"Would execute robot with the following options and arguments:\n"
f'{line_end.join((*(f"{k} = {v!r}" for k, v in options.items()) ,*arguments))}'
)
return options, arguments
# mypy: disable-error-code="arg-type"
ROBOT_OPTIONS: Set[click.Command] = {
click.option("--by-longname", type=str, multiple=True, help="Select tests/tasks or suites by longname."),
click.option(
"--exclude-by-longname",
type=str,
multiple=True,
help="Excludes tests/tasks or suites by longname.",
),
click.version_option(
version=__version__,
package_name="robotcode.runner",
prog_name="RobotCode Runner",
message=f"%(prog)s %(version)s\n{USAGE.splitlines()[0].split(' -- ')[0].strip()} {get_full_version()}",
),
click.argument("robot_options_and_args", nargs=-1, type=click.Path()),
}
def handle_robot_options(
app: Application,
by_longname: Tuple[str, ...],
exclude_by_longname: Tuple[str, ...],
robot_options_and_args: Tuple[str, ...],
) -> Tuple[Optional[Path], RobotBaseProfile, List[str]]:
robot_arguments: Optional[List[Union[str, Path]]] = None
old_sys_path = sys.path.copy()
try:
_, robot_arguments = RobotFramework().parse_arguments(robot_options_and_args)
except (DataError, Information):
pass
finally:
sys.path = old_sys_path
config_files, root_folder, _ = get_config_files(
robot_arguments, app.config.config_files, verbose_callback=app.verbose
)
try:
profile = (
load_config_from_path(*config_files)
.combine_profiles(*(app.config.profiles or []), verbose_callback=app.verbose)
.evaluated()
)
except (TypeError, ValueError) as e:
raise click.ClickException(str(e)) from e
cmd_options = profile.build_command_line()
if by_longname:
sep = ";" if any(True for l in by_longname if ":" in l) else ":"
cmd_options += ("--prerunmodifier", f"robotcode.modifiers.ByLongName{sep}{sep.join(by_longname)}")
if exclude_by_longname:
sep = ";" if any(True for l in exclude_by_longname if ":" in l) else ":"
cmd_options += (
"--prerunmodifier",
f"robotcode.modifiers.ExcludedByLongName{sep}{sep.join(exclude_by_longname)}",
)
if profile.env:
for k, v in profile.env.items():
os.environ[k] = v
app.verbose(lambda: f"Set environment variable {k} to {v}")
app.verbose(
lambda: "Executing robot with following options:\n "
+ " ".join(f'"{o}"' for o in (cmd_options + list(robot_options_and_args)))
)
return root_folder, profile, cmd_options
@click.command(
cls=AliasedCommand,
aliases=["run"],
context_settings={
"allow_extra_args": True,
"ignore_unknown_options": True,
},
add_help_option=True,
epilog='Use "-- --help" to see `robot` help.',
)
@add_options(*ROBOT_OPTIONS)
@pass_application
def robot(
app: Application,
by_longname: Tuple[str, ...],
exclude_by_longname: Tuple[str, ...],
robot_options_and_args: Tuple[str, ...],
) -> None:
"""Runs `robot` with the selected configuration, profiles, options and arguments.
The options and arguments are passed to `robot` as is.
Examples:
\b
```
robotcode run
```
"""
root_folder, profile, cmd_options = handle_robot_options(
app, by_longname, exclude_by_longname, robot_options_and_args
)
app.exit(
cast(
int,
RobotFrameworkEx(
app,
[*(app.config.default_paths if app.config.default_paths else ())]
if profile.paths is None
else profile.paths
if isinstance(profile.paths, list)
else [profile.paths],
app.config.dry,
root_folder,
).execute_cli(
(*cmd_options, *robot_options_and_args),
exit=False,
),
)
) | /robotcode_runner-0.54.3-py3-none-any.whl/robotcode/runner/cli/robot.py | 0.64791 | 0.227598 | robot.py | pypi |
# RobotCode - Language support for Robot Framework for Visual Studio Code
[](https://marketplace.visualstudio.com/items?itemName=d-biehl.robotcode)
[](https://marketplace.visualstudio.com/items?itemName=d-biehl.robotcode)
[](https://github.com/d-biehl/robotcode/actions?query=workflow:build_test_package_publish)
[](https://github.com/d-biehl/robotcode/blob/master/LICENSE)
[](https://pypi.org/project/robotcode)
[](https://pypi.org/project/robotcode)
[](https://pypi.org/project/robotcode/)
----
An [extension](https://marketplace.visualstudio.com/VSCode) which brings support for [RobotFramework](https://robotframework.org/)
to [Visual Studio Code](https://code.visualstudio.com/), including [features](#features) like code completion, debugging, test explorer, refactoring and more!
## Quick start
1. [Install a supported version of Python on your system](https://code.visualstudio.com/docs/python/python-tutorial#_prerequisites)
(note: only Python 3.8 and above are supported)
2. [Install a supported version of RobotFramwork on your system](https://github.com/robotframework/robotframework/blob/master/INSTALL.rst) (note: only RobotFramework 4.0 and above are supported)
3. [Install the RobotCode extension for Visual Studio Code](https://code.visualstudio.com/docs/editor/extension-gallery).
4. Open or create a robot file and start coding! 😉
## Requirements
* Python 3.8 or above
* Robotframework 4.1 and above
* VSCode version 1.74 and above
## Features
With RobotCode you can edit your code with auto-completion, code navigation, syntax checking and many more.
Here is a list of Features:
- [Autocomplete and IntelliSense](#Autocomplete-and-IntelliSense)
- [Code Navigation](#code-navigation)
- [Diagnostics and Linting](#diagnostics-and-linting)
- [Code Formatting](#code-formatting)
- [Running and Debugging](#running-and-debugging)
- [Multi-root Workspace folders](#multi-root-workspace-folders)
- Find implementations and references of keywords, variables, libraries, resource and variable files
- Show codelenses for keyword definitions
- Test Explorer
- Refactorings
- renaming keywords, variables, tags
### Autocomplete and IntelliSense
Autocompletion for:
- Libraries with parameters
- Resources,
- Variables
- Keywords with parameters
- Namespaces

Autocompletion supports all supported variables types
- local variables
- variables from resource files
- variables from variables file (.py and .yaml)
- static and dynamic
- command line variables
- builtin variables

### Code Navigation
- Symbols
- Goto definitions and implementations
- Keywords
- Variables
- Libraries
- Resources
- Find references
- Keywords
- Variables
- Imports
- Libraries
- Resources
- Variables
- Tags
- Errors and Warnings
### Diagnostics and Linting
RobotCode analyse your code and show diagnostics for:
- Syntax Errors
- Unknown keywords
- Duplicate keywords
- Missing libraries, resource and variable imports
- Duplicate libraries, resource and variable imports
- ... and many more
For most things RobotCode uses the installed RobotFramework version to parse and analyse the code, so you get the same errors as when you run it.
Get additional code analysis with [Robocop](https://robocop.readthedocs.io/). Just install it in your python environment.
### Code Formatting
RobotCode can format your code with the internal RobotFramework robot.tidy tool (deprecated), but also with [Robotidy](https://robotidy.readthedocs.io/). Just install it.
### Running and Debugging
RobotCode supports running and debugging of RobotFramework testcases and tasks out of the box, directly from the definition of the test or suite.

In the debug console you can see all log messages of the current run and navigate to the keyword the message was written by.
### Multi-root Workspace folders
RobotCodes support for [Multi-root Workspaces](https://code.visualstudio.com/docs/editor/multi-root-workspaces), enables loading and editing different Robotframework projects/folders with different RobotFramework/Python environments and settings at the same time or you can share the same RobotFramework/Python environment and settings for all folders in the workspace.
## Installed extensions
RobotCode will automatically install [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
Extensions installed through the marketplace are subject to the [Marketplace Terms of Use](https://cdn.vsassets.io/v/M146_20190123.39/_content/Microsoft-Visual-Studio-Marketplace-Terms-of-Use.pdf).
## Setting up your environment
You can alway use your local python environment, just select the correct python interpreter in Visual Studio Code.
### With pipenv
This is the simpliest way to create an running environment.
- As a prerequisite you need to install [pipenv](https://pipenv.pypa.io/) like this:
```bash
python -m pip install pipenv
```
- Create your project directory (robottest is just an example)
```bash
mkdir robottest
cd robottest
```
- Install robotframework
```bash
python -m pipenv install robotframework
```
- Open project in VSCode
- Set the python interpreter to the created virtual environment
## Customization
### Editor Style
You can change some stylings for RobotFramework files in VSCode editor, independently of the current theme. (see [Customizing a Color Theme](https://code.visualstudio.com/docs/getstarted/themes#_customizing-a-color-theme))
See the difference:
| Before | After |
| ---------------------------------------------------------------- | ---------------------------------------------------------- |
|  |  |
As a template you can put the following code to your user settings of VSCode.
Open the user `settings.json` like this:
<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or <kbd>F1</kbd> or <kbd>CMD</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>
and then type:
`Preferences: Open Settings (JSON)`
put this to the `settings.json`
```jsonc
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope": "variable.function.keyword-call.inner.robotframework",
"settings": {
"fontStyle": "italic"
}
},
{
"scope": "variable.function.keyword-call.robotframework",
"settings": {
//"fontStyle": "bold"
}
},
{
"scope": "string.unquoted.embeddedArgument.robotframework",
"settings": {
"fontStyle": "italic"
}
},
{
"scope": "entity.name.function.testcase.name.robotframework",
"settings": {
"fontStyle": "bold underline"
}
},
{
"scope": "entity.name.function.keyword.name.robotframework",
"settings": {
"fontStyle": "bold italic"
}
},
{
"scope": "variable.other.readwrite.robotframework",
"settings": {
//"fontStyle": "italic",
}
},
{
"scope": "keyword.control.import.robotframework",
"settings": {
"fontStyle": "italic"
}
},
{
"scope": "keyword.other.header.setting.robotframework",
"settings": {
"fontStyle": "bold underline"
}
},
{
"scope": "keyword.other.header.variable.robotframework",
"settings": {
"fontStyle": "bold underline"
}
},
{
"scope": "keyword.other.header.testcase.robotframework",
"settings": {
"fontStyle": "bold underline"
}
},
{
"scope": "keyword.other.header.keyword.robotframework",
"settings": {
"fontStyle": "bold underline"
}
},
{
"scope": "keyword.other.header.setting.robotframework",
"settings": {
"fontStyle": "bold underline"
}
},
{
"scope": "keyword.other.header.comment.robotframework",
"settings": {
"fontStyle": "bold italic underline"
}
},
{
"scope": "constant.character.escape.robotframework",
"settings": {
//"foreground": "#FF0000",
}
}
]
},
"editor.semanticTokenColorCustomizations": {
"rules": {
"*.documentation:robotframework": {
"fontStyle": "italic",
//"foreground": "#aaaaaa"
}
}
}
```
| /robotcode-0.47.5.tar.gz/robotcode-0.47.5/README.md | 0.783036 | 0.89275 | README.md | pypi |
import tkinter as tk
from tkinter import messagebox, simpledialog, Tk
from tkinter.ttk import Combobox
window_location = "+300+300"
def enter(prompt, default_value):
"""
Zobrazí dialogové okno s výzvou k zadání reálné hodnoty
při zavření okna zavíracím tlačítkem ukončí aplikaci.
:param prompt: Text výzvy oznamující uživateli, co má zadat
:param default_value: Implicitní hodnota.
:return: Uživatelem zadaná hodnota, resp. potvrzená implicitní hodnota.
"""
application_window = Tk()
application_window.withdraw()
if isinstance(default_value, str):
sd = simpledialog.askstring("Input", prompt,
parent=application_window,
initialvalue=default_value)
elif isinstance(default_value, int):
sd = simpledialog.askinteger("Input", prompt,
parent=application_window,
initialvalue=default_value)
elif isinstance(default_value, float):
sd = simpledialog.askfloat("Input", prompt,
parent=application_window,
initialvalue=default_value)
else:
raise Exception("Atribut default value must be integer,string or float")
return sd
def choose(question, *buttons):
"""
Zobrazí dialogové okno se otázkou, na níž má uživatel odpovědět stiskem
některého z tlačítek, jejichž popisky naznačují možné odpovědi.
Vrátí pořadí stisknutého tlačítka.
Pokud uživatel neodpoví a zavře dialog, metoda ukončí program.
:param question: Zobrazovaný text otázky
:param buttons: Popisky na tlačítcích
:return: Pořadí stisknutého tlačítka, přičemž první tlačítko zleva
na pořadí 0
"""
application_window = Tk()
application_window.withdraw()
def command(string):
global result
result = string
tl.destroy()
application_window.destroy()
def on_closing():
tl.destroy()
application_window.destroy()
global result
result = -1
tl = tk.Toplevel()
tl.geometry(window_location)
tl.protocol("WM_DELETE_WINDOW", on_closing)
label = tk.Label(tl, text=question)
label.pack(padx=5, pady=5)
for button_text in buttons:
button = tk.Button(tl, text=button_text, command=lambda: command(button_text))
button.pack(side=tk.LEFT, padx=5, pady=5)
application_window.mainloop()
return result
def confirm(question) -> bool:
"""
Zobrazí dialogové okno se zprávou a umožní uživateli odpovědět
<b>ANO</b> nebo <b>NE</b>. Vrátí informaci o tom, jak uživatel odpověděl.
Neodpoví-li a zavře dialog, ukončí program.
:param question: Zobrazovaný text otázky.
:return:<b>{@code true}</b> Odpověděl-li uživatel <b>ANO</b>,
<b>{@code false}</b> odpověděl-li <b>NE</b>
"""
application_window = Tk()
application_window.withdraw()
return messagebox.askyesno("Question", question)
def inform(text) -> None:
"""
Zobrazí dialogové okno se zprávou a počká,
až uživatel stiskne tlačítko OK;
při zavření okna zavíracím tlačítkem ukončí celou aplikaci.
:param text: Zobrazovaný text
"""
application_window = Tk()
application_window.withdraw()
application_window.geometry(window_location)
mb = messagebox.showinfo("Information", text)
def select(prompt, *options):
"""
Zobrazí dialogové okno s výzvou k zadání
některého z textů v rozbalovacím seznamu;
při zavření okna nebo stisku tlačítka Cancel
se celá aplikace ukončí.
:param prompt: Text výzvy oznamující uživateli, co má zadat
:param options: Texty, z nichž si může uživatel vybrat
:return: Uživatelem zadaná hodnota
"""
application_window = Tk()
application_window.withdraw()
def command():
global result
result = combo.get()
tl.destroy()
application_window.destroy()
def on_closing():
tl.destroy()
application_window.destroy()
global result
result = -1
tl = tk.Toplevel()
tl.geometry(window_location)
tl.protocol("WM_DELETE_WINDOW", on_closing)
label = tk.Label(tl, text=prompt)
label.pack(padx=5, pady=5)
combo = Combobox(tl, values=options)
combo.set(options[0])
combo.pack(padx=5, pady=5)
combo['state'] = 'readonly'
button = tk.Button(tl, text="Submit", command=command)
button.pack(padx=5, pady=5)
application_window.mainloop()
return result
def set_dialog_position(x: int, y: int):
"""
Nastaví pozici příštího dialogového okna.
:param x: Vodorovná souřadnice
:param y: Svislá souřadnice
"""
global window_location
window_location = '+%d+%d' % (x, y)
def pause(miliseconds: int):
"""
Počká zadaný počet milisekund.
:param miliseconds: Počet milisekund, po něž se má čekat
"""
from time import sleep
sleep(float(miliseconds / 1000)) | /robotcz-0.0.3-py3-none-any.whl/IO.py | 0.403449 | 0.317281 | IO.py | pypi |
import dbg; dbg.start_pkg(2, __name__, __doc__, new_line=False)
###########################################################################q
# Konstanta určující hlavní paradigma - to ovlivňuje,
# zda budou na konci modulu exportovány třídy nebo funkce.
OO_PARADIGM = False
###########################################################################q
from enum import IntEnum
from . import IO
###########################################################################q
class Color(IntEnum):
"""Výčtový typ definující 8 základních RGB barev.
Lze je zadat jak plným, tak jednoznakovým názvem.
"""
BLACK = 0
BLUE = 1
RED = 2
MAGENTA = 3
GREEN = 4
CYAN = 5
YELLOW = 6
WHITE = 7
# Implicitní barva přidávaného robota.
DEFAULT_COLOR = Color.BLUE
###########################################################################q
class Direction4(IntEnum):
"""Výčtový typ definující 4 hlavní světové strany.
Lze je zadat jak plným, tak jednoznakovým názvem.
"""
EAST = 0 # Východ - doprava
NORTH = 1 # Sever - nahoru
WEST = 2 # Západ - doleva
SOUTH = 3 # Jih - dolů
@property
def dx(self):
"""Vrátí vodorovný přírůstek při přesunu v daném směru."""
return Direction4._dx[self.value]
@property
def dy(self):
"""Vrátí svislý přírůstek při přesunu v daném směru. """
return Direction4._dy[self.value]
def turn_left(self) -> 'Direction4':
"""Vrátí směr po otočení o 90°vlevo."""
return Direction4((self.value + 1) & 0b11)
def turn_right(self) -> 'Direction4':
"""Vrátí směr po otočení o 90°vpravo."""
return Direction4((self.value + 3) & 0b11)
def turn_about(self) -> 'Direction4':
"""Vrátí směr po otočení o 180°."""
return Direction4((self.value + 2) & 0b11)
# Aby se atributy staly běžnými atributy, musí se dodat dodatečně
Direction4._dx = [1, 0, -1, 0]
Direction4._dy = [0, -1, 0, 1]
# Implicitní směr natočení přidávaného robota
DEFAULT_DIR = Direction4.EAST
###########################################################################q
IKarel:type = None
from typing import Protocol, runtime_checkable
@runtime_checkable
class IKarel(Protocol):
"""Třída definuje protokol pro minimální verzi robota Karla.
"""
def pick(self) -> IKarel: """Zvedne značku."""
def put(self) -> IKarel: """Položí značku."""
def step(self) -> IKarel: """Posune se na další políčko"""
def turn_left(self) -> IKarel: """Otočí se o 90° vlevo."""
def is_east(self) -> bool: """Prozradí, je-li otočen na východ."""
def is_marker(self) -> bool: """Prozradí, je-li pod ním značka."""
def is_wall(self) -> bool: """Prozradí, je-li před ním zeď."""
def robot_before(self)-> IKarel:"""Vrátí odkaz na robota před ním."""
def hide(self) -> True: """Skryje robota a zrychlí."""
def unhide(self) -> int: """Vrátí úroveň zobrazování robota."""
###########################################################################q
class Karel():
"""Definuje minimální verzi robota Karla implementující protokol IKarel.
"""
def __init__(self, row:int =-1, col:int = 0,
dir4 :Direction4 = DEFAULT_DIR,
color:Color = DEFAULT_COLOR,
add:bool = True):
"""Vytvoří roboty s rodným číslem.
"""
if not active_world():
raise Exception(
'\nNelze vytvořit robota - není dostupný svět robotů')
if add:
active_world().add_robot(self, row, col, dir4, color)
def __repr__(self):
"""Vrátí systémový podpis robota zobrazující jeho souřadnice,
směr natočení, barvu a je-li skryt, tak i úroveň skrytí.
"""
return active_world().repr(self)
def pick(self) -> 'Karel':
"""Zvedne značku z políčka, na němž stojí.
Není-li již na daném políčku žádná značka, ohlásí chybu.
"""
active_world().pick(self)
return self
def put(self) -> 'Karel':
"""Položí značku na políčko, na němž stojí.
Je-li již na něm maximální povolený počet značek, ohlásí chybu.
"""
active_world().put(self)
return self
def step(self) -> 'Karel':
"""Posune robota na další políčko ve směru, do nějž je natočen.
Je-li na daném políčku robot nebo zeď, ohlásí chybu.
"""
active_world().step(self)
return self
def turn_left(self) -> 'Karel':
"""Otočí robotem o 90° vlevo.
"""
active_world().turn_left(self)
return self
def is_east(self) -> bool:
"""Vrátí informaci o tom,
je-li robot otočen na východ.
"""
return active_world().is_east(self)
def is_marker(self) -> bool:
"""Vrátí informaci o tom,
je-li na políčku pod robotem nějaká značka.
"""
return active_world().is_marker(self)
def is_wall(self) -> bool:
"""Vrátí informaci o tom,
je-li na políčku před robotem zeď.
"""
return active_world().is_wall(self)
def robot_before(self) -> 'Karel':
"""Je-li na políčku před robotem jiný robot, vrátí odkaz na něj,
jinak vrátí prázdný odkaz.
"""
return active_world().robot_before(self)
def hide(self) -> True:
"""Přestane robota zobrazovat, čímž jeho činnost výrazně zrychlí,
a vrátí hodnotu True, aby jej bylo možno použít jako podmínku
v podmíněném příkazu iniciujícím odsazení.
"""
return active_world().hide(self)
def unhide(self) -> int:
"""Vrátí úroveň zobrazování do stavy před posledním skrytím.
Byl-li proto již tehdy skrytý (a tím pádem i zrychlený),
zůstane skrytý (a zrychlený) i nadále.
Byl-li zobrazovaný, začne se opět zobrazovat.
Vrátí aktuální hloubku potlačování zobrazení.
"""
return active_world().unhide(self)
###########################################################################q
# Veřejné metody modulu
def new_world(*fields:[int|str]):
"""Případnou existující aktivní instanci světa robotů nejprve deaktivuje.
Poté vytvoří nový šachovnicový svět.
Jsou-li zadány celočíselné argumenty, je vytvořen prázdný svět
se zadaným počtem řádků (první argument) a sloupců (druhý argument).
Jsou-li zadány stringy, reprezentují jejich znaky jednotlivá políčka.
Číslo na políčku udává počet značek, znak # označuje zeď.
Není-li zadán žádný argument, chová se jako po zavolání new_world(10,10).
"""
# dbg.prSE(0, 1, 'new_world', f'{fields = }')
if active_world(): active_world().destroy()
if len(fields)==0:
# dbg.prSE(0, 0, 'new_world', f'len(fields)==0')
return new_world(10, 10) # Rekurzivní volání
elif isinstance(fields[0], int):
from .robotworld import new_empty_world
new_empty_world(fields[0], fields[1])
elif isinstance(fields[0], str):
fields = [fields]
from .robotworld import new_world as new_rw
new_rw(*fields)
else:
# dbg.prSE(0, 0, 'new_world', f'EXCEPTION'
# f'{type(fields[0])=},{fields=} ')
raise Exception(f'\nNeplatné argumenty volání funkce: '
f'new_word{fields}')
result = active_world()
from .robotwindow import RobotWindow
RobotWindow(active_world())
# dbg.prSE(0, 0, 'new_world', f'{fields = }')
return result
def active_world() ->'RobotWorld':
"""Vrátí odkaz na aktuálně používaný svět robotů.
"""
from .robotworld import active_world
return active_world
###########################################################################q
# Globální atributy
###########################################################################q
# Exportované atributy
if OO_PARADIGM:
__all__ = ('dbg', 'IO',
'active_world', 'new_world', 'IKarel', 'Karel',
'Color', 'Direction4', 'DEFAULT_COLOR', 'DEFAULT_DIR',
#'RobotWorld', 'RobotWindow', 'IRobotWorldListener',
#'get_world', 'new_empty_world', 'new_world',
)
else:
# Odkazy na hodnoty třídy Color
BLACK = Color.BLACK
BLUE = Color.BLUE
RED = Color.RED
MAGENTA = Color.MAGENTA
GREEN = Color.GREEN
CYAN = Color.CYAN
YELLOW = Color.YELLOW
WHITE = Color.WHITE
# Odkazy na hodnoty třídy Direction4
EAST = Direction4.EAST
NORTH = Direction4.NORTH
WEST = Direction4.WEST
SOUTH = Direction4.SOUTH
# Odkazy na metody třídy Karel
pick = Karel.pick
put = Karel.put
step = Karel.step
turn_left = Karel.turn_left
is_east = Karel.is_east
is_marker = Karel.is_marker
is_wall = Karel.is_wall
robot_before = Karel.robot_before
hide = Karel.hide
unhide = Karel.unhide
# Definice exportovaných proměnných
__all__ = ('dbg', 'IO',
'active_world', 'new_world', 'IKarel', 'Karel',
'BLACK', 'BLUE', 'RED', 'MAGENTA', 'GREEN', 'CYAN', 'YELLOW', 'WHITE',
'DEFAULT_COLOR', 'DEFAULT_DIR',
'EAST', 'NORTH', 'WEST', 'SOUTH',
'pick', 'put', 'step', 'turn_left',
'is_east', 'is_marker', 'is_wall', 'robot_before',
'hide', 'unhide',
)
###########################################################################q
dbg.stop_pkg(2, __name__) | /robotcz-0.0.3-py3-none-any.whl/__init__.py | 0.527317 | 0.405743 | __init__.py | pypi |
import json
from typing import List
from networkx import DiGraph, dfs_tree, node_link_graph, shortest_path
from networkx.classes.reportviews import OutEdgeView
class Auditor(object):
def __init__(self, graph_specification: str) -> None:
self.graph = self._load_graph(graph_specification)
def _load_graph(self, graph_specification: str) -> DiGraph:
with open(graph_specification, "r") as inf:
graph: dict = json.load(inf)
return node_link_graph(graph)
def _explore_from_vertex(self,
vertex: str,
depth_limit: int = 5) -> List[str]:
subgraph: DiGraph = dfs_tree(self.graph,
vertex,
depth_limit=depth_limit)
edges: OutEdgeView = subgraph.edges()
can_reach: List[str] = []
for edge, edge_info in edges.items():
u, v = edge # edge is a tuple ("u", "v"), python type hints don't work with .items? # type: ignore # noqa:E501
can_reach.append(v)
return can_reach
def get_shortest_path(self, source: str, target: str) -> list:
return shortest_path(self.graph,
source=source,
target=target)
def _check_valid_query(self,
proposed_variable: str,
variable_kind: str) -> bool:
if proposed_variable in set(self.graph.nodes):
return True
else:
# e.g., "cant look for instrument asjelira4a because ... "
msg = f"The auditor can't look for violations for the {variable_kind} {proposed_variable} because it is not a known variable." # noqa: E501
msg = msg + " Try another instrument "
msg = msg + "(hint: do you need to use semantic similarity?)"
raise AttributeError(msg)
def has_iv_violation(self,
proposed_instrument: str = "weather",
proposed_outcome: str = "research",
depth_limit: int = 5) -> bool:
self._check_valid_query(proposed_variable=proposed_instrument,
variable_kind="instrument")
self._check_valid_query(proposed_variable=proposed_outcome,
variable_kind="outcome")
can_reach: List[str] = self._explore_from_vertex(
vertex=proposed_instrument, depth_limit=depth_limit
)
return proposed_outcome in can_reach | /roboteconomist-0.4.9.tar.gz/roboteconomist-0.4.9/src/auditor.py | 0.722723 | 0.247294 | auditor.py | pypi |
KEYWORDS = {'imageCount': {'arg': ['image'], 'doc': 'Image Count\n Count how many times the same picture is detected in screen.\n\n Examples:\n | ${image_cnt}= | Image Count | test.png |'}, 'waitMobilePageContainText': {'arg': ['text', 'exactMatch=true', 'timeOut=10'], 'doc': 'Wait Mobile Page Contain Text\nExamples:\n| Wait Mobile Page Contain Text | text | exactMatch=true | timeOut: default 10s'}, 'changeScreenId': {'arg': ['screenId'], 'doc': 'Change screen id\n For multi display, user could use this keyword to switch to the correct screen\n\n Examples:\n | Change screen id | 1 |'}, 'selectRegion': {'arg': ['message'], 'doc': 'Select Region\n\n Allow user to select a region and capture it.\n Return array of [capturedImagePath, x, y, w, h]\n\n Examples:\n | @{SelectedRegion}= | Select region |'}, 'setRoi': {'arg': ['coordinates', 'timeout=0'], 'doc': 'Set ROI\n\n Set region of interest on screen\n Optionally pass highlight timeout.\n\n Examples:${coordinates} | set variable | @{x, y, w, h] |\n | Set ROI | ${coordinates} |\n | Set ROI | ${coordinates} | 2 |'}, 'clickText': {'arg': ['text'], 'doc': 'Click Text\n\nClick on text.\nExamples:\n| Click Text | Hello |'}, 'highlightRoi': {'arg': ['timeout'], 'doc': 'Highlight ROI'}, 'setPsm': {'arg': ['psm'], 'doc': 'Set PSM\nExamples:\n| Set PSM | 1 - 13 |'}, 'mobileElementShouldNotContainText': {'arg': ['locator', 'text'], 'doc': 'Mobile Element Should Not Contain Text\nExamples:\n| Mobile Element Should Not Contain Text | locator | text |'}, 'mouseDown': {'arg': ['*mouseButtons'], 'doc': 'Mouse down\n Press and hold the specified buttons\n\n @mouseButtons: Could be LEFT, MIDDLE, RIGHT\n\n Examples:\n | Mouse Move | test.png | \n | Mouse Down | LEFT | RIGHT |\n | Mouse Up |'}, 'mobilePageShouldContainElement': {'arg': ['locator'], 'doc': 'Mobile Page Should Contain Element\nExamples:\n| Mobile Page Should Contain Element | locator |'}, 'closeMobileApplication': {'arg': [], 'doc': 'Close Mobile Application'}, 'tapOnBestMobileImage': {'arg': ['images'], 'doc': 'Tap On Best Mobile Image\n\nTap an best image with similarity and offset.\nExamples:\n| Mobile Tap On Best Image | hello.png |'}, 'addImagePath': {'arg': ['path'], 'doc': 'Add image path'}, 'mobilePageShouldContainText': {'arg': ['text'], 'doc': 'Mobile Page Should Contain Text\nExamples:\n| Mobile Page Should Contain Element | text |'}, 'tapWordOnMobile': {'arg': ['text', 'colorOption=0'], 'doc': 'Tap Word On Mobile\n\nTap an Tap Word On Mobile with similarity and offset.\nExamples:\n| Tap Word On Mobile | Hello | Text Color : 0 (default) 1 (light white) 2 (light gray)'}, 'resetOCRSetting': {'arg': [], 'doc': 'Reset OCR Setting\nSet Reset Font Setting'}, 'wheelDown': {'arg': ['steps', 'image='], 'doc': 'Wheel down\n Move mouse to the target, and wheel down with give steps\n\n Examples:\n | Wheel Down | 5 | \n | Wheel Down | 5 | test.png |'}, 'closeApplication': {'arg': ['name'], 'doc': 'Close application'}, 'swipeUntilTextVisible': {'arg': ['text'], 'doc': 'Swipe Until Text Visible\nExamples:\n| Swipe Until Text Visible | text |'}, 'getScreenCoordinates': {'arg': [], 'doc': 'Get screen coordinates\n\nReturn screen coordinates for active screen\n\nExamples:\n| @{coordinates}= | Get Screen Coordinates | 0 |'}, 'getCurrentScreenId': {'arg': [], 'doc': 'Get current screen id'}, 'hideMobileKeyboard': {'arg': [], 'doc': 'Hide Mobile Keyboard'}, 'stop_remote_server': {'arg': [], 'doc': 'Stops the remote server.\n\nThe server may be configured so that users cannot stop it.'}, 'mouseMoveLocation': {'arg': ['x=0', 'y=0'], 'doc': 'Mouse move locationMove the mouse pointer to the target location\n\n @x: x cooridnate where mouse should move\n\n @y: y cooridnate where mouse should move\n\n Examples:\n | Mouse Move Location | 20 | 20 |'}, 'captureMobileScreen': {'arg': ['imagePath'], 'doc': 'Capture Mobile Screen\nExamples:\n| Mobile Capture Screen | demo.png |'}, 'waitForImage': {'arg': ['wantedImage', 'notWantedImage', 'timeout'], 'doc': 'Wait For Image\n\n Check wantedImage exist. If notWantedImage appear or timeout happened, throw exception\n\n @wantedImage: expected image in screen\n\n @notWantedImage: unexpected image in screen\n\n @timeout: wait seconds\n\n Examples:\n | Wait For Image | wanted.png | notWanted.png | 5 |'}, 'clearAllHighlights': {'arg': [], 'doc': 'Clear all highlights from screen'}, 'fromRegionJumpTo': {'arg': ['region', 'direction', 'jumps', 'margin'], 'doc': "From Region Jump To\n Create a region and translate it related to the given region, the created region will have the exactly same height and width as the passed one \n ${jumps} = number of 'jumps' to move, like on a chess game, jumps will be the number of squares a piece moves \n ${direction} = | below | above | left | right | \n ${margem} = add a space between jumps, must be >= 1 \n |${translated_region} = | From Region Jump To | ${original_region} | below | 4 | 1 |"}, 'waitUntilScreenContain': {'arg': ['image', 'timeout'], 'doc': 'Wait until screen contain\n Wait until image shown in screen'}, 'getText': {'arg': ['image='], 'doc': 'Get text\n\n If image is not given, keyword will get text from whole Screen\n If image is given, keyword will get text from matched region\n Call keyword setOcrTextRead to set OcrTextRead as true, before using text recognition keywords\n\n Examples:\n | Set Ocr Text Read | true |\n | Get Text |\n | Get Text | test.png |'}, 'setOcrLanguage': {'arg': ['ocrTextLanguage'], 'doc': 'Set OCR language\n\nSet OCR language\nThree letters parameter\nDefault : eng for English language\nExamples:\n| Set OCR Language | eng |\n| Set OCR Language | fra |'}, 'tapTextOnMobile': {'arg': ['text', 'colorOption=0'], 'doc': 'Tap Text On Mobile\n\nTap an Tap Text On Mobile with similarity and offset.\nExamples:\n| Tap Text On Mobile | Hello World | Text Color : 0 (default) 1 (light white) 2 (light gray)'}, 'setAppiumImplicitWait': {'arg': ['millisecond'], 'doc': 'Set Appium Implicit Wait\nExamples:\n| Set Appium Implicit Wait | MILLISECONDS |'}, 'isTextExistOnMobileScreen': {'arg': ['text'], 'doc': 'Is Text Exist On Mobile Screen\nExamples:\n| Is Text Exist On Mobile Screen | text |'}, 'click': {'arg': ['image', 'xOffset=0', 'yOffset=0'], 'doc': 'Click\n\nClick on an image with similarity and offset.\nExamples:\n| Click | hello.png |'}, 'clickMobileElement': {'arg': ['locator'], 'doc': 'Click Mobile Element\nExamples:\n| Mobile Click Element | locator |'}, 'tapOnBestMobileImageAndWaitText': {'arg': ['images', 'text'], 'doc': 'Tap On Best Mobile Image And Wait Text\n\nTap an best image with similarity and offset.\nExamples:\n| Mobile Tap On Best Image | hello.png | text |'}, 'waitUntilMobileScreenContainAny': {'arg': ['images', 'timeOut=10'], 'doc': 'Wait Until Mobile Screen Contain Any\nExamples:\n| Wait Until Mobile Screen Contain Any | images | timeOut: default 10s'}, 'doubleClick': {'arg': ['image', 'xOffset=0', 'yOffset=0'], 'doc': 'Double click'}, 'getExtendedRegionFromImage': {'arg': ['image', 'direction', 'number of times to repeat'], 'doc': 'Get Extended Region From Image\n Extended the given image creating a new region above, below, on the left or on the right side, with the same height and width\n The height and width can change using the multiplier @number_of_times_to_repeat \n If orginal if giver as arguments, the region will be exactly the same location as the image, last argument is ignored \n Ex: If 2 is given and direction = below the new region will have twice the height of the given image and will be located right below it\n |${region} = | Get Extended Region From Image | image.png | below | 1 |\n |${region} = | Get Extended Region From Image | image.png | original | 1 #this argument is ignored |'}, 'mouseUp': {'arg': ['*mouseButtons'], 'doc': 'Mouse up\n Release the specified mouse buttons\n\n @mouseButtons: Could be LEFT, MIDDLE, RIGHT. If empty, all currently held buttons are released\n\n Examples:\n | Mouse Move | test.png | \n | Mouse Down | LEFT | RIGHT |\n | Mouse Up | LEFT | RIGHT |'}, 'pasteText': {'arg': ['image', 'text'], 'doc': 'Paste text. Image could be empty'}, 'mouseMoveRegion': {'arg': ['coordinates', 'highlight_timeout'], 'doc': 'Mouse move regionMove the mouse pointer to the target region\n\n @coordinates: coordinates where mouse should move\n\n Examples:\n | Mouse Move region | [20, 20, 20, 20] |'}, 'waitForMultipleImages': {'arg': ['timeout', 'pollingInterval', 'expectedImages', 'notExpectedImages'], 'doc': 'Wait For Multiple Images\n\n Check if images exists in expectedImages or notExpectedImages list. If image appears that is listed in notExpectedImages list or timeout happened, throw exception If image appears that is listed in expectedImageslist return succesfully. \n\n @timeout: wait seconds\n\n @pollingInterval: time in seconds between screen checks\n\n @expectedImages: list of expected images in screen\n\n @notExpectedImages: list of not expected images in screen\n\n Examples:\n | @{wanted_images} = | Create List | wanted_image1.png | wanted_image2.png |\n | @{not_wanted_images} = | Create List | not_wanted_image1.png | not_wanted_image2.png | not_wanted_image3.png |\n | Wait For Multiple Images | 900 | 10 | ${wanted_images} | ${not_wanted_images} |'}, 'clickAny': {'arg': ['images', 'timeout'], 'doc': 'Click Any\n\n Click any best image matched\n\n Examples:\n | Click Any | image1.png,image2.png,image3.png | timeout'}, 'tapTextAndTypeTextOnMobile': {'arg': ['textTap', 'textInput', 'colorOption=0'], 'doc': 'Tap Text And Type Text On Mobile\n\nTap an Tap Text And Type Text On Mobile with similarity and offset.\nExamples:\n| Tap Text And Type Text On Mobile | Hello World | Text | Text Color : 0 (default) 1 (light white) 2 (light gray)'}, 'RegionClickText': {'arg': ['text'], 'doc': 'Region Click Text\n\nClick on text in region.\nSet a region before.\nExamples:\n| Region Click Text | Hello |'}, 'mobileElementShouldContainText': {'arg': ['locator', 'text'], 'doc': 'Mobile Element Should Contain Text\nExamples:\n| Mobile Element Should Contain Text | locator | text |'}, 'keyUp': {'arg': ['keyConstant'], 'doc': 'Key up\n Release keyboard key.\n\n For a list of possible Keys view docs for org.sikuli.script.Key .\n\n Examples:\n | Click | textFieldWithDefaultText.png | \n | Key UP | CTRL | '}, 'setWaitScanRate': {'arg': ['delay'], 'doc': 'Set wait scan rate\n Specify the number of times actual search operations are performed per second while waiting for a pattern to appear or vanish.'}, 'setSmallFont': {'arg': [], 'doc': 'Set Small Font\nSet Small Font Option'}, 'setMobileTimeout': {'arg': ['timeout'], 'doc': 'Set Mobile TimeOut\nExamples:\n| Set Mobile TimeOut | 10 |'}, 'highlightRegion': {'arg': ['coordinates', 'timeout'], 'doc': 'Highlight region'}, 'typeWithModifiers': {'arg': ['text', '*modifiers'], 'doc': 'Type with modifiers\n\n Examples:\n |Type With Modifiers| A | CTRL |'}, 'clickTextAndWaitTextOnMobile': {'arg': ['textClick', 'textWait', 'timeOut=10', 'exactMatch=True'], 'doc': 'Click Text And Wait Text On Mobile\nExamples:\n| Click Text And Wait Text On Mobile | textClick | textWait | timeOut | exactMatch | '}, 'setShowActions': {'arg': ['showActions'], 'doc': 'Set show actions'}, 'wheelUp': {'arg': ['steps', 'image='], 'doc': 'Wheel up\n Move mouse to the target, and wheel up with give steps\n\n Examples:\n | Wheel Up | 5 | \n | Wheel Up | 5 | test.png |'}, 'rightClick': {'arg': ['image', 'xOffset=0', 'yOffset=0'], 'doc': 'Right click\n\nClick on an image with similarity and offset.\nExamples:\n| Click | hello.png |'}, 'clickOnMatch': {'arg': ['match'], 'doc': "Click On Match\n there's no offset to be configured\n works with the keyword Return Match From Region"}, 'getExtendedRegionFromRegion': {'arg': ['image', 'direction', 'number of times to repeat'], 'doc': 'Get Extended Region From Region\n Extended the given image creating a region above, below, in the left side or on the right, with the same height and width\n The height and width can change using the multiplier @number_of_times_to_repeat \n If 2 is given and direction = below the new region will have twice the height of the orignal and will be located right below it\n |${below_region} = | Get Extended Region From Region | ${another_region} | below | 1 |'}, 'setTimeout': {'arg': ['timeout'], 'doc': 'Set timeout\n\nSet Sikuli timeout(seconds)\nExamples:\n| Set timeout | 10 |'}, 'dragAndDropByOffset': {'arg': ['srcImage', 'xOffset', 'yOffset'], 'doc': 'Drag the source image to target by offset.\nIf source image is empty, drag the last match and drop at given target'}, 'doubleClickOnRegion': {'arg': ['region'], 'doc': "Double Click On Region\n there's no offset to be configured\n works with the keyword Get Extended Region From"}, 'clickAndSendTextOnMobile': {'arg': ['textClick', 'textInput'], 'doc': 'Click And Send Text On Mobile\nExamples:\n| Click And Send Text On Mobile | textClick | textInput'}, 'exists': {'arg': ['image', 'timeout='], 'doc': 'Exists\n\n Check whether image exists in screen\n @image: expected image in screen\n @timeout: wait seconds\n\n Examples:\n | ${is_exist}= | Exists | image.png | 0 |'}, 'waitUntilScreenContainAny': {'arg': ['images', 'timeOut=10'], 'doc': 'Wait Until Screen Contain Any\nExamples:\n| Wait Until Screen Contain Any | images | timeOut: default 10s'}, 'removeImagePath': {'arg': ['path'], 'doc': 'Remove image path'}, 'getMatchScore': {'arg': ['image'], 'doc': 'Get match scoreTries to find the image on the screen, returns accuracy score (0-1)\n\n Examples:\n | ${score} = | Get Match Score | somethingThatMayExist.png |\n | Run Keyword if | ${score} > 0.95 | keyword1 | ELSE | keyword2 |'}, 'tapOnMobileImage': {'arg': ['image'], 'doc': 'Tap On Mobile Image\n\nTap On Mobile an image with similarity and offset.\nExamples:\n| Mobile Tap On Image | hello.png |'}, 'setAlwaysResize': {'arg': ['resize'], 'doc': 'Set Always Resize\nA decimal value greater 0 and not equal to 1 to switch the feature on.\nWith this setting you can tell SikuliX to generally resize all given images before a search operation using the given factor, which is applied to both width and height. The implementation internally uses the standard behavior of resizing a Java-AWT-BufferedImage.\n\nTo switch the feature off again, just assign 0 or 1.'}, 'tapMobileImageAndWaitBestImage': {'arg': ['image', 'checks'], 'doc': 'Tap Mobile Image And Wait Best Image\n\nTap Image On Mobile And Wait Best Image with similarity and offset.\nExamples:\n| Mobile Tap Image And Wait Best Image | tap.png | wait.png'}, 'returnMatchFromRegion': {'arg': ['region', 'target'], 'doc': 'Return Match From Region\n expect a region (from keyword Get Extended Region From) and a target to be search for (an image.png)\n returns the target as a object (string), it can be used with Click On Match keywords'}, 'captureRegion': {'arg': ['coordinates', 'imageName='], 'doc': 'Capture region\n\n\nCapture region passed\nExamples:\n| ${coor} | Create List | x | y | w | h |\n| ${screenshotname}= | Capture region | ${coor} | demo.png |\n| ${screenshotname}= | Capture region | ${coor} | '}, 'clickAndTypeTextOnMobile': {'arg': ['textClick', 'textType', 'exactMatch=True', 'hide=False'], 'doc': 'Click And Type Text On Mobile\nExamples:\n| Click And Type Text On Mobile | text_click | text | hide keyboard'}, 'doubleClickOnMatch': {'arg': ['match'], 'doc': "Double Click On Match\n there's no offset to be configured\n works with the keyword Return Match From Region"}, 'clickIn': {'arg': ['areaImage', 'targetImage'], 'doc': 'Click in. \nClick target image in area image.'}, 'setTesseractPath': {'arg': ['path'], 'doc': 'Set Tesseract Path\nExamples:\n| Set Tesseract Path | Path Trained Data |'}, 'pickDate': {'arg': ['date', 'month', 'year'], 'doc': 'Pick Date\nExamples:\n| Pick Date | 10 | November | 2000 |'}, 'mobileElementShouldBe': {'arg': ['locator', 'text'], 'doc': 'Mobile Element Should Be\nExamples:\n| Mobile Element Should Be | locator | text |'}, 'getExtendedRegionFrom': {'arg': ['image', 'direction', 'number_of_times_to_repeat'], 'doc': 'Get extended region from\n Extended the given image creating a region above or below with the same width\n The height can change using the multiplier @number_of_times_to_repeat, if 2 is given the new region will have twice the height of the orignalge '}, 'clearTextOnMobileElement': {'arg': ['locator'], 'doc': 'Clear Text On Mobile Element\nExamples:\n| Clear Text On Mobile Element | locator |'}, 'getNumberOfScreens': {'arg': [], 'doc': 'Get number of screens'}, 'waitUntilScreenContainAndClick': {'arg': ['image', 'timeout'], 'doc': 'Wait until screen contain and click\n Wait until image shown in screen and click to the image'}, 'clickAndPress': {'arg': ['image', 'keyConstant'], 'doc': 'Click And Press\n\n Click image and press key C_END.\n\n For a list of possible Keys view docs for org.sikuli.script.Key .\n\n Examples:\n | Click And Press To End | textFieldWithDefaultText.png | '}, 'tapWordAndSendTextOnMobile': {'arg': ['textTap', 'textInput', 'colorOption=0'], 'doc': 'Tap Word And Send Text On Mobile\n\nTap an Tap Word And Send Text On Mobile with similarity and offset.\nExamples:\n| Tap Word And Send Text On Mobile | Hello | World | Text Color : 0 (default) 1 (light white) 2 (light gray)'}, 'setOcrTextRead': {'arg': ['ocrTextRead'], 'doc': 'OCR text read\nIf needed use Set OCR Language before.`\nDefault language : English (eng).'}, 'inputTextOnMobileElement': {'arg': ['locator', 'text'], 'doc': 'Input Text On Mobile Element\nExamples:\n| Mobile Input Text On Element | locator | text |'}, 'goBackOnMobileApplication': {'arg': [], 'doc': 'Go Back On Mobile Application'}, 'openApplication': {'arg': ['path'], 'doc': 'Open application\n To open app with parameters, refer:\n https://sikulix-2014.readthedocs.io/en/latest/appclass.html#App.App'}, 'clickTextOnMobile': {'arg': ['textClick', 'exactMatch=True', 'number=1'], 'doc': 'Click Text On Mobile\nExamples:\n| Click Text On Mobile | textClick | exactMatch | click 1 time'}, 'openMobileApplication': {'arg': ['appiumUrl', 'capabilities'], 'doc': 'Open Mobile Application\nExamples:\n| Mobile Open Application | appiumUrl | capabilities'}, 'tapOnBestMobileImageAndWaitBestImage': {'arg': ['images', 'checks'], 'doc': 'Tap On Best Mobile Image And Wait Best Image\n\nTap Best Image On Mobile And Wait Best Image with similarity and offset.\nExamples:\n| Mobile Tap On Best Image And Wait Best Image | tap.png | wait.png'}, 'typeTextOnMobile': {'arg': ['text'], 'doc': 'Type Text On Mobile\nExamples:\n| Type Text On Mobile | text |'}, 'clearTextOnMobile': {'arg': ['text', 'exactMatch=true'], 'doc': 'Clear Text On Mobile\nExamples:\n| Clear Text On Mobile | text |'}, 'inputText': {'arg': ['image', 'text'], 'doc': 'Input text.\n Image could be empty\n\n Examples:\n | Input text | image.png | Sikuli |\n | Input text | ${EMPTY} | Sikuli |'}, 'doubleClickIn': {'arg': ['areaImage', 'targetImage'], 'doc': 'Double click in. \nDouble click target image in area image.'}, 'captureScreen': {'arg': [], 'doc': 'Capture whole screen, file name is returned'}, 'swipeInMobile': {'arg': ['startX', 'startY', 'endX', 'endY'], 'doc': 'Swipe In Mobile\nExamples:\n| Swipe In Mobile | start x | start y | end x | end y |'}, 'tapWordAndClearOnMobile': {'arg': ['textTap', 'colorOption=0'], 'doc': 'Tap Word And Clear On Mobile\n\nTap an Tap Word And Clear Text On Mobile with similarity and offset.\nExamples:\n| Tap Word And Clear On Mobile | Hello | Text Color : 0 (default) 1 (light white) 2 (light gray)'}, 'screenShouldContain': {'arg': ['image'], 'doc': 'Screen should contain'}, 'clearHighlight': {'arg': ['image'], 'doc': 'Clear highlight from screen'}, 'waitMobilePageNotContainText': {'arg': ['text', 'timeOut=10'], 'doc': 'Wait Mobile Page Not Contain Text\nExamples:\n| Wait Mobile Page Not Contain Text | text | timeOut: default 10s'}, 'tapMobileImageAndWaitImage': {'arg': ['image', 'check'], 'doc': 'Tap Mobile Image And Wait Image\n\nTap Image On Mobile And Wait image with similarity and offset.\nExamples:\n| Mobile Tap Image And Wait Image | tap.png | wait.png'}, 'setCaptureFolder': {'arg': ['path'], 'doc': 'Set captured folder\n\nSet folder for captured images\nExamples:\n| Set captured folder | PATH |'}, 'readTextFromRegion': {'arg': ['reg'], 'doc': 'Read text from region'}, 'setMinSimilarity': {'arg': ['minSimilarity'], 'doc': 'Set min similarity (accuracy of matching elements).\n\nminSimilarity can be a decimal number between 0 and 1\n\nExample:\n\n| Set Min Similarity | 0.85 |'}, 'clickNth': {'arg': ['image', 'index', 'sortByColumn=true'], 'doc': 'Click nth\n\n Click on specific image.\n Optionally pass similarity and sort by column or row.\n\n Examples:\n | Click on nth image in region | image.png | 1 |\n | Click on nth image in region | image.png | 1 | ${FALSE} |'}, 'setMobileStepWait': {'arg': ['time'], 'doc': 'Set Mobile Step Wait\nExamples:\n| Set Mobile Step Wait | 10 |'}, 'getTextFromMobileElement': {'arg': ['locator'], 'doc': 'Get Text From Mobile Element\nExamples:\n| Get Text From Mobile Element | locator |'}, 'mobilePageShouldNotContainText': {'arg': ['text'], 'doc': 'Mobile Page Should Not Contain Text\nExamples:\n| Mobile Page Should Not Contain Text | text |'}, 'getMobileSession': {'arg': [], 'doc': 'Get Current Mobile Session'}, 'dragAndDrop': {'arg': ['srcImage', 'targetImage'], 'doc': 'Drag the source image to target image.\nIf source image is empty, drag the last match and drop at given target'}, 'highlight': {'arg': ['image', 'secs='], 'doc': 'Highlight matched image.\n If secs is set, highlight will vanish automatically after setted seconds'}, 'setGrayFont': {'arg': [], 'doc': 'Set Gray Font\nTurn on OCR Gray Font Option'}, 'clickOnRegion': {'arg': ['region'], 'doc': "Click On Region\n there's no offset to be configured\n works with the keyword Get Extended Region From"}, 'setSlowMotionDelay': {'arg': ['delay'], 'doc': 'Set slow motion delay\n Control the duration of the visual effect (seconds).'}, 'pressSpecialKey': {'arg': ['keyConstant'], 'doc': 'Press special key\n\n Presses a special keyboard key.\n\n For a list of possible Keys view docs for org.sikuli.script.Key .\n\n Examples:\n | Double Click | textFieldWithDefaultText.png | \n | Press Special Key | DELETE | '}, 'setLightFont': {'arg': [], 'doc': 'Set Light Font\nTurn on OCR Light Font Option'}, 'setMoveMouseDelay': {'arg': ['delay'], 'doc': 'Set move mouse delay'}, 'rightClickIn': {'arg': ['areaImage', 'targetImage'], 'doc': 'Right click in. \nRight click target image in area image.'}, 'resetRoi': {'arg': [], 'doc': 'Reset Roi\n Set Region of interest to full screen\n\n Examples:\n | Reset roi |'}, 'captureRoi': {'arg': ['imageName='], 'doc': 'Capture Roi'}, 'clickRegion': {'arg': ['coordinates', 'waitChange=0', 'timeout=0'], 'doc': 'Click region\n\n Click on defined region cooridinates.\n Optionally Wait for specified time to ensure region has changed.\n Also, optionally set highlight\n\n Examples:\n | ${coor} | Create List | 0 | 0 | 100 | 100 |\n | Click Region | ${coor} |\n | Click Region | ${coor} | 0 |\n | Click Region | ${coor} | 0 | 2 |'}, 'mouseMove': {'arg': ['image='], 'doc': 'Mouse moveMove the mouse pointer to the target\n\n @image: if image is empty, will move mouse to the last matched.\n\n Examples:\n | Mouse Move | test.png | \n | Screen Should Contain | test.png | \n | Mouse Move |'}, 'waitUntilMobileScreenContain': {'arg': ['image', 'timeOut'], 'doc': 'Wait Until Mobile Screen Contain\nExamples:\n| Wait Until Mobile Screen Contain | image | timeOut: default 10s'}, 'waitUntilScreenNotContain': {'arg': ['image', 'timeout'], 'doc': 'Wait until screen not contain\n Wait until image not in screen'}, 'tapMobileImageAndWaitText': {'arg': ['image', 'check'], 'doc': 'Tap Mobile Image And Wait Text\n\nTap Image On Mobile And Wait Text with similarity and offset.\nExamples:\n| Mobile Tap Image And Wait Text | tap.png | text'}, 'isScreenContain': {'arg': ['image'], 'doc': 'Is Screen Contain\n\n Check screen contain image\n\n Return: true | false'}, 'resetFontSetting': {'arg': [], 'doc': 'Reset Font Setting\nSet Reset Font Setting'}, 'screenShouldNotContain': {'arg': ['image'], 'doc': 'Screen should not contain\n Screen should not contain image\n\n Examples:\n | Screen should not contain | image.png |'}, 'quitMobileSession': {'arg': [], 'doc': 'Quit Mobile Session'}, 'getImageCoordinates': {'arg': ['image', 'coordinates=[]'], 'doc': 'Get Image Coordinates\n\n Return image coordinates, within region\n Examples:\n | ${imageCoordinates}= | Get Image Coordinates | image.png=0.75 |\n | ${imageCoordinates}= | Get Image Coordinates | image.png=0.75 | [x, y, w, z] |'}, 'configureAppiumPageTimeOuts': {'arg': ['time'], 'doc': 'Configure Appium Page TimeOuts\nExamples:\n| Configure Appium Page TimeOuts | time |'}, 'keyDown': {'arg': ['keyConstant'], 'doc': 'Key down\n Press keyboard key and hold it.\n\n For a list of possible Keys view docs for org.sikuli.script.Key .\n\n Examples:\n | Key down | CTRL | \n | Click | textFieldWithDefaultText.png | '}, 'setCaptureMatchedImage': {'arg': ['value'], 'doc': 'Set capture matched image\n\nSet capture matched images, the default value is true\nExamples:\n| Set Capture Matched Image | false |'}, 'start_sikuli_process': {'arg': ['port=None'], 'doc': '\n This keyword is used to start sikuli java process.\n If library is inited with mode "OLD", sikuli java process is started automatically.\n If library is inited with mode "NEW", this keyword should be used.\n\n :param port: port of sikuli java process, if value is None or 0, a random free port will be used\n :return: None\n '}} | /robotframework_AppiumSikuliLibrary-2023.8.17-py3-none-any.whl/AppiumSikuliLibrary/keywords.py | 0.713531 | 0.369372 | keywords.py | pypi |
# Copyright (c) 2015 Cutting Edge QA Marcin Koperski
from datetime import datetime
from robot.api import logger
from robot.libraries.DateTime import Date
from robot.libraries.DateTime import Time
from robot.utils import is_falsy
def get_current_time_for_timers():
return datetime.now()
from robot.api.deco import keyword, library
@library
class TimerKeywords(Time, Date):
TIMERS_DICTIONARY = {}
@keyword
def timer_start(self, timer_name="Global"):
current_time = get_current_time_for_timers()
logger.info(current_time)
if timer_name in self.TIMERS_DICTIONARY:
error = 'Timer with name "%s" already stated at %s' % (
timer_name,
self.TIMERS_DICTIONARY[timer_name].__str__(),
)
logger.warn(error)
self.TIMERS_DICTIONARY[timer_name] = current_time
msg = 'Timer with name "%s" stated at %s' % (
timer_name,
self.TIMERS_DICTIONARY[timer_name].__str__(),
)
logger.info(msg)
@keyword
def timer_stop(
self, timer_name="Global", result_format="number", exclude_millis="True"
):
current_time = get_current_time_for_timers()
if timer_name not in self.TIMERS_DICTIONARY:
message = "Time '%s' is not started." % timer_name
raise AssertionError(message)
else:
delta = Time(current_time - self.TIMERS_DICTIONARY[timer_name]).convert(
result_format, millis=is_falsy(exclude_millis)
)
del self.TIMERS_DICTIONARY[timer_name]
return delta
@keyword
def timer_restart(
self, timer_name="Global", result_format="number", exclude_millis="True"
):
time_results = self.timer_stop(timer_name, result_format, exclude_millis)
self.timer_start(timer_name)
return time_results
@keyword
def timer_log(
self,
timer_name="Global",
log_level="INFO",
result_format="number",
exclude_millis="True",
):
current_time = get_current_time_for_timers()
if timer_name not in self.TIMERS_DICTIONARY:
message = "Time '%s' is not started." % timer_name
raise AssertionError(message)
else:
delta = Time(current_time - self.TIMERS_DICTIONARY[timer_name]).convert(
result_format, millis=is_falsy(exclude_millis)
)
msg = 'Timer "%s" current results is %s' % (
timer_name,
Time(current_time - self.TIMERS_DICTIONARY[timer_name]).convert(
"verbose", millis=is_falsy(exclude_millis)
),
)
logger.write(msg, log_level)
return delta
@keyword
def timer_should_be_lesser_then(self, expected_time, timer_name="Global"):
if timer_name not in self.TIMERS_DICTIONARY:
message = "Time '%s' is not started." % timer_name
raise AssertionError(message)
else:
delta = get_current_time_for_timers() - self.TIMERS_DICTIONARY[timer_name]
delta = Time._convert_time_to_seconds(self, delta)
expected_time = Time._convert_time_to_seconds(self, expected_time)
if delta > expected_time:
message = (
"Timer '%s' is above expected time. Actual time %s > %s expected time "
% (timer_name, delta, expected_time)
)
raise AssertionError(message)
return delta
@keyword
def timer_should_be_greater_then(self, expected_time, timer_name="Global"):
if timer_name not in self.TIMERS_DICTIONARY:
message = "Time '%s' is not started." % timer_name
raise AssertionError(message)
else:
delta = get_current_time_for_timers() - self.TIMERS_DICTIONARY[timer_name]
delta = Time._convert_time_to_seconds(self, delta)
expected_time = Time._convert_time_to_seconds(self, expected_time)
if delta < expected_time:
message = (
"Timer '%s' is below expected time. Actual time %s < %s expected time "
% (timer_name, delta, expected_time)
)
raise AssertionError(message)
return delta | /robotframework_MarcinKoperski-1.2.0.15-py3-none-any.whl/TestToolsMK/timers_keywords.py | 0.660939 | 0.210117 | timers_keywords.py | pypi |
# Copyright (c) 2015 Cutting Edge QA Marcin Koperski
import csv
import os
from robot.api import logger
from robot.libraries import DateTime
from TestToolsMK.robot_instances import validate_create_artifacts_dir, bi
from robot.api.deco import keyword, library
@library
class LoggerKeywords(object):
@keyword
def log_variable_to_file(
self, name, comment="", output_file="Artifacts/variables.csv"
):
log_file = validate_create_artifacts_dir(output_file)
logger.debug("Log to file " + log_file)
fieldnames = [
"Time",
"Test Case Name",
"Variable Name",
"Variable Value",
"Comment",
]
current_time = DateTime.get_current_date(result_format="%Y.%m.%d %H:%M:%S")
test_case_name = str(bi().get_variable_value("${TEST_NAME}"))
suite_name = str(bi().get_variable_value("${SUITE_NAME}"))
variable_value = name
with open(log_file, "a") as csv_file:
writer_csv = csv.writer(csv_file, dialect="excel")
if os.stat(log_file).st_size < 10:
writer_csv.writerow(fieldnames)
writer_csv.writerow(
[
current_time,
suite_name + "." + test_case_name,
name,
variable_value,
comment,
]
)
# noinspection PyProtectedMember
@keyword
def set_log_level_none(self):
log_level_history = bi().get_variable_value("${LOG_LEVEL_HISTORY}")
if log_level_history is None:
log_level_history = []
old = bi().set_log_level("None")
log_level_history.append(old)
bi().set_global_variable("${LOG_LEVEL_HISTORY}", log_level_history)
# noinspection PyProtectedMember
@keyword
def set_log_level_restore(self):
log_level_history = bi().get_variable_value("${LOG_LEVEL_HISTORY}")
if not log_level_history:
bi().set_log_level("INFO")
else:
last = log_level_history.pop()
bi().set_log_level(last) | /robotframework_MarcinKoperski-1.2.0.15-py3-none-any.whl/TestToolsMK/logger_extension_keywords.py | 0.434701 | 0.156878 | logger_extension_keywords.py | pypi |
import time
from typing import Optional
from typing_extensions import Literal
from robotlibcore import keyword
from robot.api import Error
from OpenShiftCLI.base import LibraryComponent
from OpenShiftCLI.cliclient import CliClient
from OpenShiftCLI.dataloader import DataLoader
from OpenShiftCLI.dataparser import DataParser
from OpenShiftCLI.deprecated import deprecated
from OpenShiftCLI.outputformatter import OutputFormatter
from OpenShiftCLI.outputstreamer import OutputStreamer
class PodKeywords(LibraryComponent):
def __init__(self,
cli_client: CliClient,
data_loader: DataLoader,
data_parser: DataParser,
output_formatter: OutputFormatter,
output_streamer: OutputStreamer) -> None:
LibraryComponent.__init__(self, cli_client, data_loader, data_parser, output_formatter, output_streamer)
self.cli_client = cli_client
self.output_formatter = output_formatter
self.output_streamer = output_streamer
@keyword
@deprecated(new_keyword='Create')
def create_pod(self, file: str, namespace: Optional[str] = None) -> None:
"""Create Pod
Args:
file (str): Path to the yaml file containing the Pod definition
namespace (Optional[str], optional): Namespace where Pod will be created. Defaults to None.
"""
self.process(operation="create", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Delete')
def delete_pod(self, name: str, namespace: Optional[str] = None, **kwargs: str) -> None:
"""Delete Pod
Args:
name (str): Pod to delete
namespace (Optional[str]): Namespace where the Pod exists
"""
self.process(operation="delete", type="name", name=name, namespace=namespace, **kwargs)
@keyword
@deprecated(new_keyword='Get')
def get_pods(self, namespace: Optional[str] = None, label_selector: Optional[str] = None, **kwargs: str) -> None:
"""Get Pods
Args:
namespace (Optional[str], optional): Namespace to list Pods from. Defaults to None.
label_selector (Optional[str], optional): Label selector of the Pods. Defaults to None.
"""
self.process(operation="get", type="name", namespace=namespace, label_selector=label_selector, **kwargs)
@keyword
def search_pods(self, name: str = "",
label_selector: Optional[str] = None,
namespace: Optional[str] = None) -> None:
"""Search for pods with name containing a given string and/or
having a given label selector and/or from a given namespace
Args:
name (Optional[str], optional): String that pods name should contain. Defaults to None.
label_selector (Optional[str], optional): Label selector that pods should have. Defaults to None.
namespace (Optional[str], optional): [description]. Defaults to None.
"""
pods = self.cli_client.get(namespace=namespace, label_selector=label_selector)['items']
result = [pod for pod in pods if name in pod['metadata']['name']]
if not result:
self.output_streamer.stream('Pods not found in search', "error")
raise Error('Pods not found in search')
self.output_streamer.stream(self.output_formatter.format(result, "Pods found", "status"), "info")
@keyword
def wait_for_pods_number(self, number: int,
namespace: Optional[str] = None,
label_selector: Optional[str] = None,
timeout: int = 60,
comparison: Literal["EQUAL", "GREATER THAN", "LESS THAN"] = "EQUAL") -> None:
"""Wait for a given number of pods to exist
Args:
number (int): Number of pods to wait for
namespace (Optinal[str], optional): Namespace where the pods exist. Defaults to None.
label_selector (Optional[str], optional): Label selector of the pods. Defaults to None.
timeout (int, optional): Time to wait for the pods. Defaults to 60.
comparison (Literal[, optional): Comparison between expected and actual number of pods. Defaults to "EQUAL".
"""
max_time = time.time() + timeout
while time.time() < max_time:
pods_number = len(self.cli_client.get(namespace=namespace, label_selector=label_selector)['items'])
if pods_number == number and comparison == "EQUAL":
self.output_streamer.stream(f"Pods number: {number} succeeded", "info")
break
elif pods_number > number and comparison == "GREATER THAN":
self.output_streamer.stream(f"Pods number greater than: {number} succeeded", "info")
break
elif pods_number < number and comparison == "LESS THAN":
self.output_streamer.stream(f"Pods number less than: {number} succeeded", "info")
break
else:
pods = self.cli_client.get(namespace=namespace, label_selector=label_selector)['items']
pods_number = len(pods)
self.output_streamer.stream(self.output_formatter.format(
pods, f"Timeout - {pods_number} pods found", "name"), "warn")
@keyword
def wait_for_pods_status(self, namespace: Optional[str] = None,
label_selector: Optional[str] = None,
timeout: int = 60) -> None:
"""Wait for pods status
Args:
namespace (Optional[str, None], optional): Namespace where the pods exist. Defaults to None.
label_selector (Optional[str], optional): Pods' label selector. Defaults to None.
timeout (int, optional): Time to wait for pods status. Defaults to 60.
"""
max_time = time.time() + timeout
failing_containers = []
while time.time() < max_time:
pods = self.cli_client.get(namespace=namespace, label_selector=label_selector)['items']
if pods:
pending_pods = [pod for pod in pods if pod['status']['phase'] == "Pending"]
if not pending_pods:
failing_pods = [pod for pod in pods if pod['status']['phase']
== "Failed" or pod['status']['phase'] == "Unknown"]
if failing_pods:
self.output_streamer.stream(self.output_formatter.format(
failing_pods, "Error in Pod", "wide"), "error")
raise Error(self.output_formatter.format(
failing_pods, "There are pods in status Failed or Unknown: ", "name"))
failing_containers = [pod for pod in pods if pod['status']['phase']
== "Running" and pod['status']['conditions'][1]['status'] != "True"]
if not failing_containers:
self.output_streamer.stream(self.output_formatter.format(pods, "Pods", "wide"), "info")
break
else:
self.output_streamer.stream(self.output_formatter.format(
failing_containers, "Timeout - Pods with containers not ready", "wide"), "warn") | /robotframework-OpenShiftCLI-1.0.1.tar.gz/robotframework-OpenShiftCLI-1.0.1/OpenShiftCLI/keywords/pods.py | 0.876944 | 0.230281 | pods.py | pypi |
from typing import Optional
from robotlibcore import keyword
from OpenShiftCLI.base import LibraryComponent
from OpenShiftCLI.cliclient import CliClient
from OpenShiftCLI.dataloader import DataLoader
from OpenShiftCLI.dataparser import DataParser
from OpenShiftCLI.deprecated import deprecated
from OpenShiftCLI.outputformatter import OutputFormatter
from OpenShiftCLI.outputstreamer import OutputStreamer
class ConfigmapKeywords(LibraryComponent):
def __init__(self,
cli_client: CliClient,
data_loader: DataLoader,
data_parser: DataParser,
output_formatter: OutputFormatter,
output_streamer: OutputStreamer) -> None:
LibraryComponent.__init__(self, cli_client, data_loader, data_parser, output_formatter, output_streamer)
@keyword
@deprecated(new_keyword='Create')
def create_configmap(self, file: str, namespace: Optional[str] = None) -> None:
"""Create Configmap
Args:
file (str): Path to the yaml file containing the Configmap definition
namespace (Optional[str], optional): Namespace where the Configmap will be created. Defaults to None.
"""
self.process(operation="create", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Delete')
def delete_configmap(self, name: str, namespace: Optional[str] = None, **kwargs: str) -> None:
"""Delete ConfigMap
Args:
name (str): ConfigMap to delete
namespace (Optional[str], optional): Namespace where the ConfigMap exists. Defaults to None.
"""
self.process(operation="delete", type="name", name=name, namespace=namespace, **kwargs)
@keyword
@deprecated(new_keyword='Delete')
def delete_configmap_from_file(self, file: str, namespace: Optional[str] = None, **kwargs: str) -> None:
"""Delete Configmap From File
Args:
file (str): Path to the yaml file containing the Configmap definition
namespace (Optional[str], optional): Namespace where the Configmap exists. Defaults to None.
"""
self.process(operation="delete", type="name", data_type="yaml", file=file, namespace=namespace, **kwargs)
@keyword
@deprecated(new_keyword='Patch')
def patch_configmap(self,
name: Optional[str] = None,
body: Optional[str] = None,
namespace: Optional[str] = None,
**kwargs: str) -> None:
"""Patch Configmap
Args:
name (Optional[str], optional): Configmap to patch. Defaults to None.
body (Optional[str], optional): Configmap definition file. Defaults to None.
namespace (Optional[str], optional): Namespace where the Configmap exists. Defaults to None.
"""
self.process(operation="patch", type="patch", data_type="json",
name=name, body=body, namespace=namespace, **kwargs) | /robotframework-OpenShiftCLI-1.0.1.tar.gz/robotframework-OpenShiftCLI-1.0.1/OpenShiftCLI/keywords/configmaps.py | 0.910856 | 0.181825 | configmaps.py | pypi |
from typing import Optional
from robotlibcore import keyword
from OpenShiftCLI.base import LibraryComponent
from OpenShiftCLI.cliclient import CliClient
from OpenShiftCLI.dataloader import DataLoader
from OpenShiftCLI.dataparser import DataParser
from OpenShiftCLI.deprecated import deprecated
from OpenShiftCLI.outputformatter import OutputFormatter
from OpenShiftCLI.outputstreamer import OutputStreamer
class KFDEFKeywords(LibraryComponent):
def __init__(self,
cli_client: CliClient,
data_loader: DataLoader,
data_parser: DataParser,
output_formatter: OutputFormatter,
output_streamer: OutputStreamer) -> None:
LibraryComponent.__init__(self, cli_client, data_loader, data_parser, output_formatter, output_streamer)
self.cli_client = cli_client
self.output_formatter = output_formatter
self.output_streamer = output_streamer
@keyword
@deprecated(new_keyword='Create')
def create_kfdef(self, file: str, namespace: Optional[str] = None) -> None:
"""Create KfDef
Args:
file(str): Path to the yaml file containing the KfDef definition
namespace (Optional[str]): Namespace where the KfDef will be created
"""
self.process(operation="create", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Delete')
def delete_kfdef(self, name: str, namespace: Optional[str] = None, **kwargs: str) -> None:
"""Delete KfDef
Args:
name (str): KfDef to delete
namespace (Union[str, None], optional): Namespace where the KfDef exists. Defaults to None.
"""
self.process(operation="delete", type="name", name=name, namespace=namespace, **kwargs)
@keyword
@deprecated(new_keyword='Get')
def get_kfdefs(self, namespace: Optional[str] = None, label_selector: Optional[str] = None) -> None:
"""Get KfDefs
Args:
namespace (Optional[str], optional): Namespace where the KfDefs exist. Defaults to None.
label_selector (Optional[str], optional): Label selector of the KfDefs. Defaults to None.
"""
self.process(operation="get", type="name", namespace=namespace, label_selector=label_selector)
@keyword
@deprecated(new_keyword='Path')
def patch_kfdef(self,
name: Optional[str] = None,
body: Optional[str] = None,
namespace: Optional[str] = None,
**kwargs: str) -> None:
"""Patch KfDef
Args:
name (Optional[str], optional): KfDef to patch. Defaults to None.
body (Optional[str], optional): KfDef definition file. Defaults to None.
namespace (Optional[str], optional): Namespace where the KfDef exists. Defaults to None.
"""
self.process(operation="patch", type="patch", data_type="json",
name=name, body=body, namespace=namespace, **kwargs) | /robotframework-OpenShiftCLI-1.0.1.tar.gz/robotframework-OpenShiftCLI-1.0.1/OpenShiftCLI/keywords/kfdefs.py | 0.909176 | 0.160233 | kfdefs.py | pypi |
from typing import Optional
from robotlibcore import keyword
from OpenShiftCLI.base import LibraryComponent
from OpenShiftCLI.cliclient import CliClient
from OpenShiftCLI.dataloader import DataLoader
from OpenShiftCLI.dataparser import DataParser
from OpenShiftCLI.deprecated import deprecated
from OpenShiftCLI.outputformatter import OutputFormatter
from OpenShiftCLI.outputstreamer import OutputStreamer
class SecretKeywords(LibraryComponent):
def __init__(self,
cli_client: CliClient,
data_loader: DataLoader,
data_parser: DataParser,
output_formatter: OutputFormatter,
output_streamer: OutputStreamer) -> None:
LibraryComponent.__init__(self, cli_client, data_loader, data_parser, output_formatter, output_streamer)
@keyword
@deprecated(new_keyword='Apply')
def apply_secret(self, file: str, namespace: Optional[str] = None) -> None:
"""Apply Secret
Args:
file (str): Path to the yaml file containing the Secret definition
namespace (Optional[str], optional): Namespace where the Secret exists. Defaults to None.
"""
self.process(operation="apply", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Create')
def create_secret(self, file: str, namespace: Optional[str] = None) -> None:
"""Create Secret
Args:
file (str): Path to the yaml file containing the Secret definition
namespace (Optional[str], optional): Namespace where the Secret will be created
"""
self.process(operation="create", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Delete')
def delete_secret(self, name: str, namespace: Optional[str] = None, **kwargs: str) -> None:
"""Delete Secret
Args:
name (str): Secret to delete
namespace (Optional[str], optional): Namespace where the Secret exists. Defaults to None.
"""
self.process(operation="delete", type="name", name=name, namespace=namespace, **kwargs)
@keyword
@deprecated(new_keyword='Delete')
def delete_secret_from_file(self, file: str, namespace: Optional[str] = None, **kwargs: str) -> None:
"""Delete Secret From File
Args:
file (str): Path to the yaml file containing the Secret definition
namespace (Optional[str], optional): Namespace where the Secret exists. Defaults to None.
"""
self.process(operation="delete", type="name", data_type="yaml", file=file, namespace=namespace, **kwargs) | /robotframework-OpenShiftCLI-1.0.1.tar.gz/robotframework-OpenShiftCLI-1.0.1/OpenShiftCLI/keywords/secrets.py | 0.916549 | 0.174973 | secrets.py | pypi |
import json
import os
import validators
import yaml
from typing import Any, Dict, List, Optional, Union
from robotlibcore import keyword
from OpenShiftCLI.cliclient import GenericClient
from OpenShiftCLI.dataloader import DataLoader
from OpenShiftCLI.dataparser import DataParser
from OpenShiftCLI.errors import ResourceOperationFailed
from OpenShiftCLI.outputformatter import OutputFormatter
from OpenShiftCLI.outputstreamer import OutputStreamer
class GenericKeywords(object):
def __init__(self, client: GenericClient, data_loader: DataLoader, data_parser: DataParser,
output_formatter: OutputFormatter, output_streamer: OutputStreamer) -> None:
self.client = client
self.data_loader = data_loader
self.data_parser = data_parser
self.output_formatter = output_formatter
self.output_streamer = output_streamer
@keyword
def apply(self, kind: str, src: str = None, namespace: Optional[str] = None,
**kwargs: Optional[str]) -> List[Dict[str, Any]]:
"""Applies definition/s from file on one or more resources
Args:
kind (str): Resource/s kind/s
src (str): Path/Url/String containing the yaml with the Resource/s definition/s
namespace (str, optional): Namespace where the Resource/s exist/s or will be
created. Defaults to None.
Returns:
List[Dict[str, Any]]: List containing the apply operation/s result/s
"""
return self._apply_or_create(kind=kind, operation='apply', src=src,
namespace=namespace, **kwargs)
@keyword
def create(self, kind: str, src: str = None, namespace: Optional[str] = None,
**kwargs: Optional[str]) -> List[Dict[str, Any]]:
"""Creates one or multiple resources
Args:
kind (str): Resource/s kind/s
src (str): Path/Url/String containing the yamm with the Resource/s definition/s
namespace (Optional[str], optional): Namespace where the Resource/s will be created. Defaults to None.
Returns:
List[Dict[str, Any]]: List containing the create operation/s result/s
"""
return self._apply_or_create(kind=kind, operation='create', src=src,
namespace=namespace, **kwargs)
@keyword
def delete(self, kind: str, src: Optional[str] = None, name: Optional[str] = None,
namespace: Optional[str] = None, label_selector: Optional[str] = None,
field_selector: Optional[str] = None, **kwargs: str) -> List[Dict[str, Any]]:
"""Deletes one or more Resources
Args:
kind (str): Resource/s kind/s
src (str): Path/Url/String containing the yaml with the Resource/s definition/s
name (Optional[str], optional): Name of the Resource/s to delete
namespace (Optional[str], optional): Namespace where the Resource/s to delete exist/s. Defaults to None.
label_selector (Optional[str], optional): Label Selector of the Resource/s to delete. Defaults to None.
field_selector (Optional[str], optional): Field Selector of the Resource/s to delete. Defaults to None.
Returns:
List[Dict[str, Any]]: List containing the delete operation/s result/s
"""
if not (src or name or label_selector or field_selector):
self._handle_error(operation='delete',
error_reason=("Src or at least one of name, label_selector "
"or field_selector is required"))
if src and (name or label_selector or field_selector):
self._handle_error(operation='delete',
error_reason=("Src or at least one of name, label_selector "
"or field_selector is required, but not both"))
result = []
if src and not (name or label_selector or field_selector):
items = self._get_items(operation='delete', src=src, kind=kind, data_type='yaml')
if kind == 'List':
result = [self._operate(kind=kind, operation='delete', body=item,
namespace=namespace or item.get('metadata', {}).get('namespace'),
**kwargs) for item in items]
else:
result = [self._operate(kind=kind, operation='delete',
name=item.get('metadata', {}).get('name'),
namespace=namespace or item.get('metadata', {}).get('namespace'),
label_selector=item.get('metadata', {}).get('label_selector'),
field_selector=item.get('metadata', {}).get('field_selector'),
**kwargs) for item in items]
if not src and (name or label_selector or field_selector):
result = [self._operate(kind=kind, operation='delete', name=name,
namespace=namespace, label_selector=label_selector,
field_selector=field_selector, **kwargs)]
self._generate_output(output=result, output_message="Delete result", output_type=None)
return result
@keyword
def get(self, kind: str, name: Optional[str] = None, namespace: Optional[str] = None,
label_selector: Optional[str] = None, field_selector: Optional[str] = None,
**kwargs: str) -> List[Dict[str, Any]]:
"""Gets Resource/s
Args:
kind (str): Resource/s kind/s
name (Optional[str], optional): Resource name. Defaults to None.
namespace (Optional[str], optional): Namespace where the Resource/s exist/s. Defaults to None.
label_selector (Optional[str], optional): Label Selector of the Resource/s. Defaults to None.
field_selector (Optional[str], optional): Field Selector of the Resource/s. Defaults to None.
Returns:
List[Dict[str, Any]]: List containing the get operation/s result/s
"""
arguments = {'name': name, 'namespace': namespace, 'label_selector': label_selector,
'field_selector': field_selector, **kwargs}
result = self._operate(kind=kind, operation='get', **arguments).get('items')
if not result:
self._handle_error(operation='get', error_reason="Not Found")
self._generate_output(output=result, output_message="Get result", output_type=None)
return result
@keyword
def get_pod_logs(self, name: str, namespace: str, **kwargs: Optional[str]) -> None:
result = None
try:
result = self.client.get_pod_logs(name=name, namespace=namespace, **kwargs)
except Exception as error:
self._handle_error(operation='get pod logs', error_reason=error)
self.output_streamer.stream(type(result), 'info')
self._generate_output(output=result, output_message="Get Pod Logs result", output_type=None)
@keyword
def patch(self, kind: str, src: str = None, name: Optional[str] = None,
namespace: Optional[str] = None, **kwargs: str) -> List[Dict[str, Any]]:
"""Updates Fields of the Resource using JSON merge patch
Args:
kind (str): Resource kind
src (str): Path/Url/String containing the json with the Resource patch
name (Optional[str], optional): Name of Resource to patch
namespace (Optional[str], optional): Namespace where the Resource Exists. Defaults to None.
Returns:
Dict[str, Any]: [description]
"""
if not (src and name):
self._handle_error('patch', "Src and name required")
items = self._get_items(operation='patch', src=src, kind=kind, data_type='json')
result = [self._operate(kind=kind, operation='patch', name=name, body=item,
namespace=namespace, content_type='application/merge-patch+json',
**kwargs) for item in items]
self._generate_output(output=result, output_message="Patch result", output_type=None)
return result
@keyword
def watch(self, kind: str, namespace: Optional[str] = None, name: Optional[str] = None,
label_selector: Optional[str] = None, field_selector: Optional[str] = None,
resource_version: Optional[str] = None,
timeout: Optional[int] = 60) -> List[Dict[str, Any]]:
"""Watches changes to a one or more Resources
Args:
kind (str): Resource/s kind/s
name (Optional[str], optional): Resource name. Defaults to None.
namespace (Optional[str], optional): Namespace where the Resource/s exist/s. Defaults to None.
label_selector (Optional[str], optional): Label Selector of the Resource/s. Defaults to None.
field_selector (Optional[str], optional): Field Selector of the Resource/s. Defaults to None.
resource_version (Optional[str], optional): Resource Version of the Resource/s. Defaults to None.
timeout (Optional[int], optional): Timeout for the watch. Defaults to 60.
Returns:
List[Dict[str, Any]]: [description]
"""
arguments = {'name': name, 'namespace': namespace, 'label_selector': label_selector,
'field_selector': field_selector, 'resource_version': resource_version,
'timeout': timeout}
result = self._operate(kind=kind, operation='watch', **arguments)
self._generate_output(output=result, output_message="Watch result", output_type=None)
return result
def _apply_or_create(self, kind: str, operation: str, src: str, namespace: Optional[str] = None,
**kwargs: Optional[str]) -> List[Dict[str, Any]]:
if not src:
self._handle_error(operation, "Src required")
items = self._get_items(operation=operation, src=src, kind=kind, data_type='yaml')
result = [self._operate(kind=kind, operation=operation, body=item,
namespace=namespace or item.get('metadata', {}).get('namespace'),
**kwargs) for item in items]
self._generate_output(output=result, output_message=f"{operation.capitalize()} result", output_type=None)
return result
def _get_items(self, operation: str, src: str, kind: str, data_type: str) -> List[Dict[str, Any]]:
return self._parse_data(operation, self._get_data(operation, src, kind), data_type)
def _get_data(self, operation: str, src: str, kind: str) -> str:
if os.path.isfile(src):
try:
return self.data_loader.from_file(path=src)
except Exception as error:
self._handle_error(operation=operation,
error_reason=f"Load data from file failed\n{error}")
if validators.url(src):
try:
return self.data_loader.from_url(path=src)
except Exception as error:
self._handle_error(operation=operation,
error_reason=f"Load data from url failed\n{error}")
if ('kind' in yaml.safe_load(src)) or self._validate_json(src):
return src
self._handle_error(operation=operation,
error_reason="Src is not a valid path, url, yaml or json")
def _parse_data(self, operation: str, data: str, data_type: str) -> List[Dict[str, Any]]:
if data_type == 'yaml':
try:
return self.data_parser.from_yaml(data=data)
except Exception as error:
self._handle_error(operation=operation,
error_reason=f"Data is not a valid yaml\n{error}")
if data_type == 'json':
try:
return self.data_parser.from_json(data=data)
except Exception as error:
self._handle_error(operation=operation,
error_reason=f"Data is not a valid json\n{error}")
def _operate(self, kind: str, operation: str, **arguments) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
try:
return getattr(self.client, operation)(kind=kind, **arguments)
except AttributeError as error:
self._handle_error(operation=operation,
error_reason=f"Operation {operation} does not exists\n{error}")
except Exception as error:
self._handle_error(operation=operation, error_reason=error)
def _handle_error(self, operation: str, error_reason: str) -> None:
error_message = f"{operation.capitalize()} failed\nReason: {error_reason}"
self.output_streamer.stream(output=error_message, type='error')
raise ResourceOperationFailed(error_message)
def _generate_output(self, output: Union[List[List[Dict[str, Any]]], List[Dict[str, Any]]],
output_message: str, output_type: Optional[str] = None) -> None:
output = self.output_formatter.format(output=output, message=output_message,
type=output_type)
self.output_streamer.stream(output=output, type='info')
def _validate_json(self, src: str) -> bool:
try:
json.loads(src)
except ValueError:
return False
return True | /robotframework-OpenShiftCLI-1.0.1.tar.gz/robotframework-OpenShiftCLI-1.0.1/OpenShiftCLI/keywords/generic.py | 0.804175 | 0.254808 | generic.py | pypi |
from typing import Optional
from robotlibcore import keyword
from OpenShiftCLI.base import LibraryComponent
from OpenShiftCLI.cliclient import CliClient
from OpenShiftCLI.dataloader import DataLoader
from OpenShiftCLI.dataparser import DataParser
from OpenShiftCLI.deprecated import deprecated
from OpenShiftCLI.outputformatter import OutputFormatter
from OpenShiftCLI.outputstreamer import OutputStreamer
class ListKeywords(LibraryComponent):
def __init__(self,
cli_client: CliClient,
data_loader: DataLoader,
data_parser: DataParser,
output_formatter: OutputFormatter,
output_streamer: OutputStreamer) -> None:
LibraryComponent.__init__(self, cli_client, data_loader, data_parser, output_formatter, output_streamer)
@keyword
@deprecated(new_keyword='Apply')
def apply_resources_list(self, file: str, namespace: Optional[str] = None) -> None:
"""Apply Resources List
Args:
file (str): Path to the yaml file containing the Resources List definition
namespace (str, optional): Namespace where the Resources List will be created. Defaults to None.
"""
self.process(operation="apply", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Create')
def create_resources_list(self, file: str, namespace: Optional[str] = None) -> None:
"""Create Resources List
Args:
file (str): Path to yaml file containing the Resources List definition
namespace (Optional[str], optional): Namespace where the Resources List will be created
"""
self.process(operation="create", type="body", data_type="yaml", file=file, namespace=namespace)
@keyword
@deprecated(new_keyword='Delete')
def delete_resources_list(self, file: str, namespace: Optional[str] = None) -> None:
"""Delete Resources List
Args:
file (str): Path to the Resources List to delete
namespace (Union[str, None], optional): Namespace where the Resources List exists. Defaults to None.
"""
self.process(operation="delete_from_file", type="body", data_type="yaml", file=file, namespace=namespace) | /robotframework-OpenShiftCLI-1.0.1.tar.gz/robotframework-OpenShiftCLI-1.0.1/OpenShiftCLI/keywords/lists.py | 0.896987 | 0.192577 | lists.py | pypi |
import asyncio
import os
import traceback
import warnings
import logging
import signal
import sys
import robot
from PuppeteerLibrary.keywords.checkbox import CheckboxKeywords
from typing import List
from PuppeteerLibrary.base.ipuppeteer_library import iPuppeteerLibrary
from robot.api.deco import not_keyword
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
from robot.errors import ExecutionFailed
from pyppeteer.browser import Browser
from PuppeteerLibrary.library_context.ilibrary_context import iLibraryContext
from PuppeteerLibrary.library_context.library_context_factory import LibraryContextFactory
from PuppeteerLibrary.base.robotlibcore import DynamicCore
from PuppeteerLibrary.keywords import (
AlertKeywords,
BrowserManagementKeywords,
DropdownKeywords,
ElementKeywords,
FormElementKeywords,
JavascriptKeywords,
MockResponseKeywords,
MouseEventKeywords,
PDFKeywords,
ScreenshotKeywords,
UtilityKeywords,
WaitingKeywords)
# Get the version from the _version.py versioneer file. For a git checkout,
# this is computed based on the number of commits since the last tag.
from ._version import get_versions
__version__ = str(get_versions()['version']).split('+')[0]
del get_versions
class PuppeteerLibrary(DynamicCore, iPuppeteerLibrary):
"""PuppeteerLibrary is a web testing library for Robot Framework.
PuppeteerLibrary uses the pyppeteer library internally to
control a web browser.
This document explains how to use keywords provided by PuppeteerLibrary.
== Locator syntax ==
PuppeteerLibrary supports finding elements based on different strategies
such as the element id, XPath expressions, or CSS selectors same as SeleniumLibrary
Locator strategy is specified with a prefix using either syntax ``strategy:value`` or ``strategy=value``.
| = Strategy = | = Match based on = | = Example = |
| id | Element ``id``. | ``id:example`` |
| xpath | XPath expression. | ``xpath://div[@id="example"]`` |
| css | CSS selector. | ``css:div#example`` |
| link | Exact text a link has. | ``link:Home page`` |
| partial link | Partial link text | ``partial link:Home`` |
== Chain Locator only for Playwright ==
Playwright support ``Chaining selectors`` strategy. This allow us to chain following support locator.
Selectors can be combined with the ``>>`` token, e.g. selector1 >> selector2 >> selectors3.
When selectors are chained, next one is queried relative to the previous one's result.
Support chaining locator strategy: css and xpath
More detail [Chaining selectors](https://playwright.dev/docs/selectors#chaining-selectors)
Example:
chain=css=article >> css=.bar > css=.baz >> css=span[attr=value]
== Timeout ==
Timeout will use for Wait.. keywords. By default Puppeteer will use default timeout value if you
didn't specific in keywords argument.
Default Timeout is ``30 seconds``.
User can set new default timeout using ``Set Timeout`` keyword
*Time format*
All timeouts and waits can be given as numbers considered seconds (e.g. 0.5 or 42) or in Robot Framework's time syntax(e.g. 1.5 seconds or 1 min 30 s).
For more information about the time syntax see the Robot Framework User Guide.
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
ROBOT_LISTENER_API_VERSION = 3
loop = None
browser = None
puppeteer_browser: iLibraryContext = None
playwright_browser: iLibraryContext = None
# contexts = {}
current_context_name = None
current_page = None
current_iframe = None
debug_mode = False
debug_mode_options = {
'slowMo': 200,
'devtools': False
}
# new context
current_libary_context: iLibraryContext = None
library_factory: LibraryContextFactory = None
library_contexts: dict = {}
def __init__(self, disable_python_logging=True):
if disable_python_logging:
self._disable_python_logging()
# Support RIDE
try:
signal.signal(signal.SIGINT, self.terminal_signal_handler)
except:
print('Warning: Not handle terminal signal')
try:
self.loop = asyncio.get_event_loop()
except:
print('Warning: Asyncio not supported')
self.run_on_failure_keyword = 'Capture Page Screenshot'
libraries = [
AlertKeywords(self),
BrowserManagementKeywords(self),
CheckboxKeywords(self),
DropdownKeywords(self),
ElementKeywords(self),
FormElementKeywords(self),
JavascriptKeywords(self),
MockResponseKeywords(self),
MouseEventKeywords(self),
PDFKeywords(self),
ScreenshotKeywords(self),
UtilityKeywords(self),
WaitingKeywords(self)
]
DynamicCore.__init__(self, libraries)
self.library_factory = LibraryContextFactory()
@not_keyword
def get_current_library_context(self) -> iLibraryContext:
return self.current_libary_context
@not_keyword
async def set_current_library_context(self, context_name) -> iLibraryContext:
self.current_libary_context = self.library_contexts[context_name]
return self.current_libary_context
@not_keyword
def get_library_context_by_name(self, alias: str) -> iLibraryContext:
if alias in self.library_contexts:
return self.library_contexts[alias]
return None
@not_keyword
def get_all_library_context(self) -> List[iLibraryContext]:
return list(self.library_contexts.values())
@not_keyword
def get_all_library_context_dict(self) -> dict:
return self.library_contexts
@not_keyword
def get_browser(self) -> Browser:
return self.browser
@not_keyword
def create_library_context(self, alias: str, browser_type: str) -> iLibraryContext:
library_context = self.library_factory.create(browser_type)
self.library_contexts[alias] = library_context
self.current_libary_context = library_context
return library_context
@not_keyword
def remove_library_context(self, alias):
if alias not in self.library_contexts.keys():
return
deleted_library_context = self.library_contexts[alias]
del self.library_contexts[alias]
if self.current_libary_context == deleted_library_context:
if len(self.library_contexts) > 0:
self.current_libary_context = list(
self.library_contexts.values())[-1]
else:
self.current_libary_context = None
@not_keyword
def run_keyword(self, name, args, kwargs):
self._running_keyword = name
try:
return DynamicCore.run_keyword(self, name, args, kwargs)
except robot.errors.TimeoutError:
logger.warn('Test timeout. Force stop puppeteer server')
# Force
self.loop.run_until_complete(
self.get_current_library_context().stop_server())
raise
except Exception:
if name.lower().replace(' ', '_') == 'close_puppeteer' or name.lower().replace(' ', '_') == 'open_browser':
logger.warn('Can\'t close puppeteer...')
elif name.lower().replace(' ', '_') != 'capture_page_screenshot':
self.failure_occurred()
raise
finally:
self._running_keyword = None
def failure_occurred(self):
try:
BuiltIn().run_keyword_and_ignore_error(self.run_on_failure_keyword)
except Exception as err:
logger.warn("Keyword '%s' could not be run on failure: %s"
% (self.run_on_failure_keyword, err))
def terminal_signal_handler(self, sig, frame):
print('You pressed Ctrl+C!')
BuiltIn().run_keyword_and_ignore_error('Close Puppeteer')
self._stop_execution_gracefully()
def _disable_python_logging(self):
# Force node not throw any unhandled task
os.environ['NODE_OPTIONS'] = '--unhandled-rejections=none'
warnings.filterwarnings('ignore')
logging.getLogger('asyncio').setLevel(logging.ERROR)
logging.getLogger('asyncio.coroutines').setLevel(logging.ERROR)
logging.disable(logging.CRITICAL)
logging.warning('Protocol problem:')
def _stop_execution_gracefully(self):
raise ExecutionFailed('Execution terminated by signal', exit=True) | /robotframework-PuppeteerLibrary-3.1.10.tar.gz/robotframework-PuppeteerLibrary-3.1.10/PuppeteerLibrary/__init__.py | 0.500732 | 0.154599 | __init__.py | pypi |
from PuppeteerLibrary.base.robotlibcore import keyword
from PuppeteerLibrary.ikeywords.iwaiting_async import iWaitingAsync
from PuppeteerLibrary.base.librarycomponent import LibraryComponent
class WaitingKeywords(LibraryComponent):
def __init__(self, ctx):
super().__init__(ctx)
def get_async_keyword_group(self) -> iWaitingAsync:
return self.ctx.get_current_library_context().get_async_keyword_group(type(self).__name__)
@keyword
def wait_for_network_idle(self, timeout=None):
"""
Wait until there are no network connections for at least 500 ms.
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_for_network_idle(timeout))
@keyword
def wait_for_request_url(self, url, method='GET', body=None, timeout=None):
"""
Wait until web application sent request to ``url``.
The ``url`` is request url. url can be partial url match using regexp
Match Options:
| Options | Url value |
| Exact match | ^http://127.0.0.1:7272/ajax_info.json$ |
| Partial match | /ajax_info.json |
| Regular expression | .*?/ajax_info.json |
The ``method`` is HTTP Request Methods:
- GET (default)
- POST
- PUT
- HEAD
- DELETE
- PATCH
The ``body`` is request body message. body can match using regexp
``Return`` request msg with properties {url, method, body}
Example:
| Open browser | ${HOME_PAGE_URL} | options=${options} | | |
| Input Text | id:username | foo | | |
| Input Text | id:password | bar | | |
| Run Async Keywords | Click Element | id:login_button | AND | |
| ... | `Wait For Request Url` | ${URL_API}/login | POST | username=demo |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_for_request_url(url, method, body, timeout))
@keyword
def wait_for_response_url(self, url, status=200, body=None, timeout=None):
"""
Wait until web application received response from ``url``.
The ``url`` is response url.
The ``status`` is HTTP Status Codes:
- 200 (default)
- 201
- 204
- 400
- 401
- 404
- 500
Reference:[https://restfulapi.net/http-status-codes/|https://restfulapi.net/http-status-codes/]
``Return`` request msg with properties {url, status, body}
Example:
| Open browser | ${HOME_PAGE_URL} | options=${options} | | |
| Input Text | id:username | foo | | |
| Input Text | id:password | bar | | |
| Run Async Keywords | Click Element | id:login_button | AND | |
| ... | `Wait For Response Url` | ${URL_API}/login | 200 | username=demo |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_for_response_url(url, status, body, timeout))
@keyword
def wait_for_navigation(self, timeout=None):
"""
Waits until web page navigates to new url or reloads.
Example:
| Open browser | ${HOME_PAGE_URL} | options=${options} | |
| Input Text | id:username | foo | |
| Input Text | id:password | bar | |
| Run Async Keywords | Click Element | id:login_button | AND |
| ... | `Wait For Navigation` | | |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_for_navigation(timeout))
@keyword
def wait_until_page_contains_element(self, locator, timeout=None):
"""
Waits until ``locator`` element appears on current page.
Example:
| Open browser | ${HOME_PAGE_URL} | options=${options} |
| `Wait Until Page Contains Element` | id:username | |
"""
self.loop.run_until_complete(self.get_async_keyword_group(
).wait_until_page_contains_element(locator, timeout))
@keyword
def wait_until_element_is_hidden(self, locator, timeout=None):
"""
Waits until ``locator`` element is hide or removed from web page.
Example:
| Run Async Keywords | Click Element | id:login_button | AND |
| ... | Wait For Navigation | | |
| `Wait Until Element Is Hidden` | id:login_button | | |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_element_is_hidden(locator, timeout))
@keyword
def wait_until_element_is_visible(self, locator, timeout=None):
"""
Waits until ``locator`` element is displayed on web page.
Example:
| Run Async Keywords | Click Element | id:login_button | AND |
| ... | Wait For Navigation | | |
| `Wait Until Element Is Visible` | id:welcome | | |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_element_is_visible(locator, timeout))
@keyword
def wait_until_page_contains(self, text, timeout=None):
"""
Waits until ``text`` appears on current page.
Example:
| Run Async Keywords | Click Element | id:login_button | AND |
| ... | Wait For Navigation | | |
| `Wait Until Page Contains` | Invalid user name or password | | |
"""
self.loop.run_until_complete(
self.get_async_keyword_group().wait_until_page_contains(text, timeout))
@keyword
def wait_until_page_does_not_contains(self, text, timeout=None):
"""
Waits until ``text`` disappears on current page.
Example:
| Run Async Keywords | Click Element | id:login_button | AND |
| ... | Wait For Navigation | | |
| `Wait Until Page Does Not Contains` | Please input your user name | | |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_page_does_not_contains(text, timeout))
@keyword
def wait_until_element_contains(self, locator, text, timeout=None):
"""
Waits until ``locator`` element contains ``text``.
Example:
| Open browser | ${HOME_PAGE_URL} | options=${options} |
| `Wait Until Element Contains` | css:#container p | Please input your user name |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_element_contains(locator, text, timeout))
@keyword
def wait_until_element_does_not_contains(self, locator, text, timeout=None):
"""
Waits until ``locator`` element does not contains ``text``.
Example:
| Run Async Keywords | Click Element | id:login_button | AND |
| ... | Wait For Navigation | | |
| `Wait Until Element Does Not Contains` | css:#container p | Please input your user name | |
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_element_does_not_contains(locator, text, timeout))
@keyword
def wait_until_location_contains(self, expected, timeout=None):
"""
Waits until the current URL contains `expected`.
The `expected` argument contains the expected value in url.
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_location_contains(expected, timeout))
@keyword
def wait_until_location_does_not_contains(self, expected, timeout=None):
"""
Waits until the current URL does not contains `expected`.
The `expected` argument contains the expected value must not in url.
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_location_does_not_contains(expected, timeout))
@keyword
def wait_until_element_is_enabled(self, selenium_locator, timeout=None):
"""
Waits until the specific element is Enabled.
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_element_is_enabled(selenium_locator, timeout))
@keyword
def wait_until_element_finished_animating(self, selenium_locator, timeout=None):
"""
Waits until the specific element is finished animating.
Check by check element position.
"""
return self.loop.run_until_complete(self.get_async_keyword_group().wait_until_element_finished_animating(selenium_locator, timeout)) | /robotframework-PuppeteerLibrary-3.1.10.tar.gz/robotframework-PuppeteerLibrary-3.1.10/PuppeteerLibrary/keywords/waiting.py | 0.792384 | 0.150746 | waiting.py | pypi |
import asyncio
from robot.utils import timestr_to_secs
from robot.libraries.BuiltIn import _RunKeyword
from PuppeteerLibrary.keywords.browsermanagement import BrowserManagementKeywords
from PuppeteerLibrary.playwright.async_keywords.playwright_browsermanagement import PlaywrightBrowserManagement
from PuppeteerLibrary.base.librarycomponent import LibraryComponent
from PuppeteerLibrary.base.robotlibcore import keyword
class UtilityKeywords(LibraryComponent):
def __init__(self, ctx):
super().__init__(ctx)
@keyword
def set_timeout(self, timeout):
"""Sets the timeout that is used by various keywords.
The value can be given as a number that is considered to be seconds or as a human-readable string like 1 second.
The previous value is returned and can be used to restore the original value later if needed.
See the Timeout section above for more information.
Example:
| Open page that loads slowly | | |
| Set Timeout | ${orig timeout} | |
"""
orig_timeout = self.ctx.timeout
if self.ctx.get_current_library_context().browser_type.lower() == 'ptchrome':
self.ctx.get_current_library_context().set_default_timeout(timestr_to_secs(timeout))
else:
self.loop.run_until_complete(
self.ctx.get_current_library_context().set_default_timeout(timestr_to_secs(timeout))
)
self.info('Original timeout is ' + str(orig_timeout) + ' seconds')
return orig_timeout
@keyword
def run_async_keywords_and_return_first_completed(self, *keywords):
"""Executes all the given keywords in a asynchronous and wait until first keyword is completed
``Return`` Array of result for each keywords based on index
Example
| `Run Async Keywords And Return First Completed` | Wait for response url | ${HOME_PAGE_URL}/login.html | AND |
| ... | Wait for response url | ${HOME_PAGE_URL}/home.html | |
"""
run_keyword = _RunKeyword()
return self.loop.run_until_complete(self._run_async_keywords_first_completed(run_keyword._split_run_keywords(list(keywords))))
@keyword
def run_async_keywords(self, *keywords):
"""Executes all the given keywords in a asynchronous and wait until all keyword is completed
``Return`` Array of result for each keywords based on index
Example:
| Open browser | ${HOME_PAGE_URL} | options=${options} | |
| `Run Async Keywords` | Click Element | id:login_button | AND |
| ... | Wait for response url | ${HOME_PAGE_URL}/home.html | |
"""
run_keyword = _RunKeyword()
return self.loop.run_until_complete(self._run_async_keywords(run_keyword._split_run_keywords(list(keywords))))
@keyword
def enable_debug_mode(self, slowMo=150, devtools=True):
"""Enable debug mode.
The ``slowMo`` argument specifies delay for each test step.
The ``devtools`` argument specifies enable devtools or not.
Example:
| Enable Debug Mode | | |
| Open browser | http://127.0.0.1:7272 | |
| Input text | id:username_field | demo |
| Input text | id:password_field | mode |
"""
self.ctx.debug_mode = True
self.ctx.debug_mode_options['headless'] = False
self.ctx.debug_mode_options['slowMo'] = slowMo
self.ctx.debug_mode_options['devtools'] = devtools
@keyword
def disable_debug_mode(self):
"""Disable debug mode. This keyword will close all browser and reset debug mode to False.
"""
async def disable_debug_mode_async():
await self.ctx.browser.close()
self.loop.run_until_complete(disable_debug_mode_async())
self.ctx.debug_mode = False
self.ctx.clear_browser()
async def _run_async_keywords(self, iterable):
statements = []
for kw, args in iterable:
kw_name = kw.lower().replace(' ', '_')
async_keywords = self.ctx.keywords[kw_name].__self__.get_async_keyword_group(
)
statements.append(getattr(async_keywords, kw_name)(*args))
try:
return await asyncio.gather(*statements)
except Exception as err:
raise Exception(err)
async def _run_async_keywords_first_completed(self, iterable):
org_statements = []
index = 0
for kw, args in iterable:
kw_name = kw.lower().replace(' ', '_')
async_keywords = self.ctx.keywords[kw_name].__self__.get_async_keyword_group(
)
org_statements.append(self._wrapped_async_keyword_return_index(
index, getattr(async_keywords, kw_name)(*args)))
index += 1
statements = org_statements
error_stack_trace = ''
while True:
done, pending = await asyncio.wait(statements, return_when=asyncio.FIRST_COMPLETED)
statements = pending
for future in done:
try:
# Raise an exception if coroutine failed
result_index = future.result()
# Force cancel all pending
for p in pending:
try:
p.cancel()
except:
pass
return result_index
except Exception as e:
error_stack_trace += str(e)+'\n'
continue
if len(pending) == 0:
raise Exception(
"All async keywords failed \r\n" + error_stack_trace)
async def _wrapped_async_keyword_return_index(self, index, future):
await future
return index | /robotframework-PuppeteerLibrary-3.1.10.tar.gz/robotframework-PuppeteerLibrary-3.1.10/PuppeteerLibrary/keywords/utility.py | 0.734596 | 0.247896 | utility.py | pypi |
from typing import Any, List, Optional
from pyppeteer.element_handle import ElementHandle
from pyppeteer.page import Page
from PuppeteerLibrary.locators.SelectorAbstraction import SelectorAbstraction
from robot.utils import timestr_to_secs
class SPage(Page):
selected_iframe: ElementHandle = None
def __init__(self):
super(Page, self).__init__()
self.selected_iframe = None
async def click_with_selenium_locator(self, selenium_locator: str, options: dict = None, **kwargs: Any):
selector_value = SelectorAbstraction.get_selector(selenium_locator)
if SelectorAbstraction.is_xpath(selenium_locator):
await self.click_xpath(selector_value, options, **kwargs)
else:
await self.click(selector_value, options, **kwargs)
async def click_xpath(self, selector: str, options: dict = None, **kwargs: Any):
element = await self.xpath(selector)
await element[0].click(options, **kwargs)
async def type_with_selenium_locator(self, selenium_locator: str, text: str, options: dict = None, **kwargs: Any):
selector_value = SelectorAbstraction.get_selector(selenium_locator)
if SelectorAbstraction.is_xpath(selenium_locator):
await self.type_xpath(selector=selector_value, text=text, options=options, kwargs=kwargs)
else:
await super().type(selector=selector_value, text=text, options=options, kwargs=kwargs)
async def type_xpath(self, selector, text: str, options: dict = None, **kwargs: Any):
element = await self.xpath(selector)
await element[0].type(text, options, **kwargs)
async def querySelectorAll_with_selenium_locator(self, selenium_locator: str):
selector_value = SelectorAbstraction.get_selector(selenium_locator)
if SelectorAbstraction.is_xpath(selenium_locator):
return await self.xpath(selector_value)
else:
return await self.querySelectorAll(selector_value)
async def querySelector_with_selenium_locator(self, selenium_locator: str):
selector_value = SelectorAbstraction.get_selector(selenium_locator)
if SelectorAbstraction.is_xpath(selenium_locator):
return (await self.xpath(selector_value))[0]
else:
return await self.querySelector(selector_value)
async def waitForSelector_with_selenium_locator(self, selenium_locator: str, timeout: float, visible=False, hidden=False):
options = {
'timeout': timeout * 1000,
'visible': visible,
'hidden': hidden
}
selector_value = SelectorAbstraction.get_selector(selenium_locator)
if SelectorAbstraction.is_xpath(selenium_locator):
return await self.waitForXPath(xpath=selector_value, options=options)
else:
return await self.waitForSelector(selector=selector_value, options=options)
# Override waitForXPath behavior for SPage
async def waitForXPath(self, xpath: str, options: dict = None, **kwargs: Any):
if self.selected_iframe is None:
return await super().waitForXPath(xpath=xpath, options=options, kwargs=kwargs)
else:
return await self.selected_iframe.waitForXPath(xpath=xpath, options=options, kwargs=kwargs)
# Override waitForSelector behavior for SPage
async def waitForSelector(self, selector: str, options: dict = None, **kwargs: Any):
if self.selected_iframe is None:
return await super().waitForSelector(selector=selector, options=options, kwargs=kwargs)
else:
return await self.selected_iframe.waitForSelector(selector=selector, options=options, kwargs=kwargs)
# Override xpath behavior for SPage
async def xpath(self, expression: str) -> List[ElementHandle]:
if self.selected_iframe is None:
return await super().xpath(expression=expression)
else:
return await self.selected_iframe.xpath(expression=expression)
# Override click behavior for SPage
async def click(self, selector: str, options: dict = None, **kwargs: Any):
if self.selected_iframe is None:
return await super().click(selector=selector, options=options, kwargs=kwargs)
else:
return await self.selected_iframe.click(selector=selector, options=options, kwargs=kwargs)
# Override querySelectorAll for SPage
async def querySelector(self, selector: str) -> Optional[ElementHandle]:
if self.selected_iframe is None:
return await super().querySelector(selector=selector)
else:
return await self.selected_iframe.querySelector(selector=selector) | /robotframework-PuppeteerLibrary-3.1.10.tar.gz/robotframework-PuppeteerLibrary-3.1.10/PuppeteerLibrary/custom_elements/SPage.py | 0.849097 | 0.163713 | SPage.py | pypi |
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from robot.api import logger
import pywinauto
import pywinauto.mouse
import time
import sys
import re
import pyautogui
import os
from datetime import datetime
from datetime import timedelta
import subprocess
class PyWindowsGuiLibrary:
"""
__Author__ = *Himavanthudu Bodapati*
The PyWindowsGuiLibrary is a library that enables users to create tests for the windows based GUI applications.
%TOC%
= Open an application / Connect an existing application =
== Opening an application ==
Firstly *make sure application is launched*.
To launch application, use keyword called `Launch Application`. After the Application is started,
you can connect to the application using the keyword `Focus Application Window`.
== Connecting an existing application ==
This library provides support even for opened applications. *To connect an existing application
use `Focus Application Window` without using `Launch Application` *.
*Note:* To open a new instance of an application from given path use `Launch Application` or
`Focus Application Window` to connect to a instance that is already opened.
= Property Section =
Initially to know about the application tittle property use AutoIT inspector.
To get the Controls and properties use `Print Current Window Page Object Properties` and
`Print Specific Object Properties On Current Window`
*Example*
*Notepad* application controls:
Control Identifiers:
Dialog - 'Untitled - Notepad*' (L-9, T-9, R1929, B1039)
['Dialog', 'Untitled - NotepadDialog*', 'Untitled - Notepad*']
*child_window(title="Untitled - Notepad*", control_type="Window")*
|
| Edit - 'Text Editor' (L0, T54, R1920, B1001)
| ['Edit', 'Edit0', 'Edit1']
| child_window(title="Text Editor", auto_id="15", control_type="Edit")
| |
| | ScrollBar - 'Vertical' (L1899, T54, R1920, B980)
| | ['Vertical', 'ScrollBar', 'VerticalScrollBar', 'ScrollBar0', 'ScrollBar1']
| | child_window(title="Vertical", auto_id="NonClientVerticalScrollBar", control_type="ScrollBar")
| | |
| | | Button - 'Line up' (L1899, T54, R1920, B75)
| | | ['Line up', 'Line upButton', 'Button', 'Button0', 'Button1']
| | | child_window(title="Line up", auto_id="UpButton", control_type="Button")
| | |
| | | Button - 'Line down' (L1899, T959, R1920, B980)
| | | ['Line downButton', 'Line down', 'Button2']
| | | child_window(title="Line down", auto_id="DownButton", control_type="Button")
| |
| | ScrollBar - 'Horizontal' (L0, T980, R1899, B1001)
| | ['Horizontal', 'ScrollBar2', 'HorizontalScrollBar']
| | child_window(title="Horizontal", auto_id="NonClientHorizontalScrollBar", control_type="ScrollBar")
| | |
| | | Button - 'Column left' (L0, T980, R21, B1001)
| | | ['Button3', 'Column leftButton', 'Column left']
| | | child_window(title="Column left", auto_id="UpButton", control_type="Button")
| | |
| | | Button - 'Column right' (L1878, T980, R1899, B1001)
| | | ['Button4', 'Column rightButton', 'Column right']
| | | child_window(title="Column right", auto_id="DownButton", control_type="Button")
| |
| | Thumb - '' (L1899, T980, R1920, B1001)
| | ['Thumb']
|
| ...
== Window property ==
This property is used to connect window. Probably window property will be same as window name visible in
application. For example refer above `Property Section`.
Below Syntax/Pattern must be follow to pass the value for window property.
As of now Library supports Title and class name as window property.
Pattern to pass the Window property.
*Example if Title is available:---> (title:Untitled - Notepad)*
*Example if class_name is available:---> (class_name:PQR)*
== Element property ==
*Locators*
To find exact element property/control, analyse the hierarchy and find from printed controls identifiers.
There is no specific syntax/pattern to pass the locator values, directly pass the matching properties to the
`keywords`.
*Example: Notepad edit property is:['Edit', 'Edit0', 'Edit1'], any one property is enough to use as locator.*
== Child window ==
Child windows can be used as property to perform certain actions like click.
= Screenshots (on failure) =
The PyWindowsGuiLibrary offers an option for automatic screenshots on error.
By default this option is enabled, use keyword `Disable Screenshots On Failure` to skip the screenshot
functionality. Alternatively, this option can be set with the ``screenshots_on_error`` argument when `importing`
the library.
= Multiple applications support =
This library enables and supports multiple window based application automation as part of E2E scenarios.
= Multiple Instances Support =
This library handles and supports Multiple instances of same application. Index argument helps us to handle
multiple instance where having same `window property`.
= Sample Scripts =
To switch between applications use `Focus Application Window` to change the controls towards the
respective application.
*Note:*
There is no need to launch application everytime when you shift the application in E2E scenarios.
Find below example testcase which covers `Multiple applications support`
== *** Settings *** ==
Library----PyWindowsGuiLibrary----screenshots_on_error=False----backend=UIA
== *** Variables *** ==
${App1}----C:\\Windows\\system32\\notepad.exe
${App2}----C:\\Program Files\\your_application.exe
${ABCB}----PQRS
== *** Test Cases *** ==
*Automation Test Case*
----Launch Application----${App1}
----Wait Until Window Present----title:Untitled - Notepad----30
----Focus Application Window----title:Untitled - Notepad
----Maximize Application Window
----Capture App Screenshot
----${t}=----Print Current Window Page Object Properties
----log----${t}
----Input Text----Edit----ABCD
----Minimize Application Window
----launch application----${App2}
----Wait Until Window Present----title:your_application
----Focus Application Window----title:your_application
----Maximize Application Window
----Click On Element----LoginButton
----Focus Application Window----title:*Untitled - Notepad
----Press Keys----{ENTER}${ABCB}
----Capture App Screenshot----ABCDPQRS----JPG
----Clear Edit Field----Edit
----Capture App Screenshot----Cleared
----Focus Application Window----title:your application
----Set Text---- Edit1----PQRS
----Clear Edit Field----Edit1
"""
__version__ = '2.1'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self, screenshots_on_error=True, backend="uia"):
"""
Sets default variables for the library.
| *Arguments* | *Documentation* |
| screenshots_on_error=True | Enables screenshots on Failures |
| screenshots_on_error=False | Disables screenshots on Failures |
| backend | UIA |
| backend | win32 |
"""
self.take_screenshots = screenshots_on_error
self.backend = backend.lower()
self.dlg = None
self.APPInstance = None
self.hae = ""
def set_backend_win32(self):
"""
This sets backend variable as win32 globally, for execution purpose.
*Example*:
| *Arguments* | *Documentation* |
| Set Backend Win32 | #sets backend process as win32. |
"""
self.backend = 'win32'
def set_backend_uia(self):
"""
This sets backend variable as uia globally, for execution purpose.
*Example*:
| *Arguments* | *Documentation* |
| Set Backend Uia | #sets backend process as uia. |
"""
self.backend = 'uia'
def disable_screenshots_on_failure(self):
"""
Disables automatic screenshots on error.
*Example*:
| *Keyword* | |
| Disable Screenshots On Failure | # This disables screenshots on failures/errors. |
"""
self.take_screenshots = False
def enable_screenshots_on_failure(self):
"""
Enables automatic screenshots on error.
*Example*:
| *Keyword* | |
| Enable Screenshots On Failure | # This enables screenshots on failures/errors. |
"""
self.take_screenshots = True
def launch_application(self, path, backend="uia"):
"""
Launches The Application from Given path.
By default applications will open with "uia" backend process. This keyword supports both uia and win32 backend
process.
If Required to open the Application in win32 than, need to pass backend process as win32.
*Example*:
| *Keyword* | *Attributes* | | |
| Launch Application | C:\\Program Files\\app.exe | | # By default application launches with uia. |
| Launch Application | C:\\Program Files\\app.exe | win32 | # Application launches with win32. |
"""
logger.info("Launching the application from the path " + path)
try:
self.APPInstance = pywinauto.application.Application(backend=backend).start(path, timeout=60)
return self.APPInstance
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to start/Launch given Application from the path " + ":::: " + "because " + str(h1)
raise Exception(mess)
def _window_handle_(self, window_property, index):
global w_handle
if 'title:' in window_property:
win_prop = window_property.replace('title:', '')
w_handle = pywinauto.findwindows.find_windows(title_re=win_prop, ctrl_index=None, top_level_only=True,
visible_only=True)[index]
elif 'class_name:' in window_property:
win_prop = window_property.replace('class_name:', '')
w_handle = pywinauto.findwindows.find_windows(class_name=win_prop, ctrl_index=None, top_level_only=True,
visible_only=True)[index]
def focus_application_window(self, window_property, backend="uia", index=0):
"""
Focuses the Application to the Front End.
And return the Connected Window Handle Instance :i.e dlg. This sets as global and the same used across
further implementation.
See the `Window property` section for details about the window.
Use Backend argument as uia/win32 as per application support.
This connects to the application.
*Note:* Use this keyword anytime to shift the control of execution between backend process win32 and uia.
*Example*:
| *Keyword* | *Attributes* | *backend process* | | |
| Focus Application Window | title:Untitled - Notepad | | | # Would focus application with backend process uia and index 0. |
| Focus Application Window | class_name:XYZ | uia | 1 | # Would focus application with backend process uia and index 1. |
| Focus Application Window | title:ABC | win32 | 1 | # Would focus application with backend process win32 and index 1. |
"""
logger.info("'Focusing the application window matches to " + window_property + "'.")
try:
self.APPInstance = pywinauto.application.Application(backend=backend)
self._window_handle_(window_property, index)
self.APPInstance.connect(handle=w_handle)
self.dlg = self.APPInstance.window(handle=w_handle)
self.dlg.set_focus()
if backend == "uia":
self.set_backend_uia()
else:
self.set_backend_win32()
return self.dlg
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to focus Application given by " + str(window_property) + " property,with " + str(index) \
+ " index and " + str(backend) + " backend process " + ":::: " + "because " + str(h1)
raise Exception(mess)
def set_focus_to_element(self, element_property):
"""
Sets focus to given element on current active window.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Set Focus To Element | element_property | # Would focuses to window element. |
"""
try:
if self.dlg and self.backend is not None:
self.dlg[element_property].set_focus()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to focus element in the Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_element_control_type(self, element_property):
"""
Return the given element control type.
See the `Element property` section for details about the locator.
Control types are : edit, combobox, radio, button ect...
*Example*:
| *Variable* | *Keyword* | *Attributes* | |
| ${ControlType}= | Get Element Control Type | element_property | # Would return given element control type. |
"""
try:
if self.dlg and self.backend is not None:
return self.dlg[element_property].friendly_class_name()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to focus element in the Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def maximize_application_window(self):
"""
Maximize the window.
*Example*:
| *Keyword* | |
| Maximize Application Window | #would maximize application window. |
"""
logger.info("Maximizing the current application window")
try:
if self.backend and self.dlg is not None:
self.dlg.maximize()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to maximize the Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def minimize_application_window(self):
"""
Minimize the window.
*Example*:
| *Keyword* | |
| Minimize Application Window | #would minimize application window. |
"""
logger.info("Minimizing the current application window.")
try:
if self.dlg and self.backend is not None:
self.dlg.minimize()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to minimize the Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def print_current_window_page_object_properties(self):
"""
Returns control identifiers for current ``window``.
Recommended to use UIA controls to get fetch more properties from backend.
*Example*:
| *Variable* | *Keyword* | |
| ${Complete window controls}= | print_current_window_page_object_properties | #would return complete controls of window. |
"""
logger.info("'Returns Complete window controls from Current connected Window" + "'.")
try:
self.dlg.print_control_identifiers()
printed_controls = sys.stdout.getvalue()
return printed_controls
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to print and return page properties " + ":::: " + "because " + str(h1)
raise Exception(mess)
def print_specific_object_properties_on_current_window(self, element_property):
"""
Returns control identifiers for given ``element property``
See the `Element property` section for details about the locator.
*Example*:
| *Variable* | *Keyword* | *Attributes* | |
| ${Specific Element controls}= | Print current window page object properties | element_property | #would return specific element controls from window. |
"""
logger.info("Returns Specific element controls from given ``element Property`` " + "``" + element_property
+ "`` " + "'.")
try:
self.dlg[element_property].print_ctrl_ids()
printed_controls = sys.stdout.getvalue()
return printed_controls
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to print and return Object " + element_property + " properties" + ":::: " + "because " \
+ str(h1)
raise Exception(mess)
def get_window_text(self):
"""
Returns the text of the currently selected window.
*Example*:
| *Variable* | *Keyword* | |
| ${Window Text}= | Get Window Text | #would returns window text. |
"""
logger.info("Retrieving current window text.")
try:
if self.backend is not None:
return self.dlg.window_text()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to get current window text in current active Application " + " :::: " + "because " \
+ str(h1)
raise Exception(mess)
def get_text(self, element_property):
"""
Returns the text value of the element identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Variable* | *Keyword* | *Attributes* | |
| ${Text}= | Get Text | element property | #would return text of specified element from window. |
"""
logger.info("Retrieving element text from given Object Property" + "'" + element_property + "'.")
try:
if self.dlg and self.backend is not None:
return self.dlg[element_property].window_text()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to Get text in Application from given by " + element_property + " :::: " + "because " \
+ str(h1)
raise Exception(mess)
def set_text(self, element_property, text):
"""
Sets the given text into the text field identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | | |
| Set Text | element property | PQRS | #would set text to specified element in window. |
"""
logger.info("Setting text " + text + " into text field identified by " + "'" + element_property + "'.")
try:
if self.dlg and self.backend is not None:
self.dlg[element_property].set_text(text) # set_edit_text(text)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to Type the given " + text + " into the text field identified by " + element_property + "." \
+ " :::: " + "because " + str(h1)
raise Exception(mess)
def click_on_element(self, element_property):
"""
Clicks at the element identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Click On Element | element property | # Would click element with by Click() method. |
"""
logger.info("Clicking element Property " + "'" + element_property + "'.")
try:
if self.backend is not None:
self.dlg[element_property].click()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to click element " + element_property + " in Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def double_click_on_element(self, element_property):
"""
Double Click at the element identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Double Click On Element | element property | # Would click element with by Double_Click() method. |
"""
logger.info("Double clicking element property " + "`" + element_property + "`.")
try:
if self.dlg and self.backend is not None:
if self.backend == "win32":
self.dlg[element_property].double_click()
elif self.backend == "uia":
logger.info("This keyword is no longer support for uia controls")
raise AssertionError
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to click object " + element_property + " in Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def right_click_on_element(self, element_property):
"""
Right Click at the element identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Right Click On Element | element property | # Would click element with by Right_Click() method. |
"""
logger.info("Right clicking element property " + "'" + element_property + "'.")
try:
if self.dlg and self.backend is not None:
if self.backend == "win32":
self.dlg[element_property].right_click()
elif self.backend == "uia":
log = "This keyword is no longer support for uia controls, Use other Click related keywords"
logger.info(log)
raise AssertionError
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to click object " + element_property + " in Application " + ":::: " + "because " + \
log + str(h1)
raise Exception(mess)
def action_right_click_on_element(self, element_property):
"""
Realistic Right Click at the element identified by ``element_property``.
This is different from click method in that it requires the control to be visible on the screen but performs
a more realistic ‘click’ simulation.
This method is also vulnerable if the mouse is moved by the user as that could easily move the mouse off the
control before the click_input has finished.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Action Right Click On Element | element property | # Would click element with by right_Click_input() method. |
"""
logger.info("Action Right Clicking element Property " + "'" + element_property + "'.")
try:
if self.dlg and self.backend is not None:
if self.backend == "win32":
self.dlg[element_property].right_click_input()
elif self.backend == "uia":
log = "This keyword is no longer support for uia controls, Use other Click related keywords"
logger.info(log)
raise AssertionError
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to click object " + element_property + " in Application " + ":::: " + "because " + log + \
str(h1)
raise Exception(mess)
def action_click(self, element_property):
"""
Clicks at the element identified by ``element_property``.
Use Element property or child window to perform the clicking operation.
This is different from click method in that it requires the control to be visible on the screen but performs
a more realistic ‘click’ simulation.
This method is also vulnerable if the mouse is moved by the user as that could easily move the mouse off the
control before the click_input has finished.
See the `Element property` and `Child window` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Action Click | element property | # Would click element with by Click_input() method. |
| Action Click | child window | # Would click element with by Click_input() method. |
"""
logger.info("Realistic clicking element property " + "'" + element_property + "'.")
try:
if self.dlg and self.backend is not None:
self.dlg[element_property].click_input()
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable to click object " + element_property + " in Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def action_double_click(self, element_property):
"""
Double Click at the element identified by ``element_property``.
Use Element property or child window to perform the clicking operation.
This is different from click method in that it requires the control to be visible on the screen but performs
a more realistic ‘click’ simulation.
This method is also vulnerable if the mouse is moved by the user as that could easily move the mouse off the
control before the click_input has finished.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Action Double Click | element property | # Would click element with by Double_Click_input() method. |
| Action Double Click | child window | # Would click element with by Double_Click_input() method. |
"""
logger.info("Realistic double clicking element Property " + "'" + element_property + "'.")
try:
if self.dlg and self.backend is not None:
self.dlg[element_property].double_click_input()
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable to perform realistic double click on object " + element_property + " in Application " \
+ ":::: " + "because " + str(h1)
raise Exception(mess)
def mouseover_click(self, x_coordinates='0', y_coordinates='0', button='left'):
"""
Clicks at the specified X and Y coordinates.
By Default this performs left mouse click
*Example*:
| *Keyword* | *Attributes* | | | |
| Mouseover Click | | | | #By default perform left click on (0,0) coordinates. |
| Mouseover Click | x_coordinates | y_coordinates | right | #Would perform right click on given coordinates. |
| Mouseover Click | x_coordinates | y_coordinates | left | #Would perform left click on given coordinates. |
"""
logger.info(button + " Mouse button clicking at X and Y coordinates i.e " + "(" + str(x_coordinates) + "," +
str(y_coordinates) + ")")
try:
x_coordinates = int(x_coordinates)
y_coordinates = int(y_coordinates)
pywinauto.mouse.click(button=button, coords=(x_coordinates, y_coordinates))
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to click object by " + str(x_coordinates), str(y_coordinates) + " in Application " + \
":::: " + "because " + str(h1)
raise Exception(mess)
def mouseover_double_click(self, x_coordinates='0', y_coordinates='0', button='left'):
"""
double click at the specified X and Y coordinates.
By Default this performs left mouse double click
*Example*:
| *Keyword* | *Attributes* | | |
| Mouseover Double Click | | | | #By default perform double left click on (0,0)) coordinates. |
| Mouseover Double Click | x_coordinates | y_coordinates | right | #Would perform right double click. |
| Mouseover Double Click | x_coordinates | y_coordinates | left | #Would perform left double click. |
"""
logger.info(button + " Mouse Button double clicking at X and Y coordinates i.e " + "(" + str(x_coordinates) +
"," + str(y_coordinates) + ")")
try:
x_coordinates = int(x_coordinates)
y_coordinates = int(y_coordinates)
pywinauto.mouse.double_click(button=button, coords=(x_coordinates, y_coordinates))
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable to double click object by " + str(x_coordinates), str(y_coordinates) + " in Application " \
+ ":::: " + "because " + str(h1)
raise Exception(mess)
def mouseover_move(self, x_coordinates='0', y_coordinates='0'):
"""
Move the mouse at specified X and Y coordinates.
*Example*:
| *Keyword* | *Attributes* | | |
| Mouseover move | | | #By default perform move on (0,0)) coordinates. |
| Mouseover move | x_coordinates | y_coordinates | #Would perform mouse move to given coordinates. |
"""
logger.info(" Moving mouse to given X and Y coordinates i.e " + "(" + str(x_coordinates) +
"," + str(y_coordinates) + ")")
try:
x_coordinates = int(x_coordinates)
y_coordinates = int(y_coordinates)
pywinauto.mouse.move(coords=(x_coordinates, y_coordinates))
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable move mouse to coordinates " + str(x_coordinates), str(y_coordinates) + " in Application "\
+ ":::: " + "because " + str(h1)
raise Exception(mess)
def mouseover_press(self, x_coordinates='0', y_coordinates='0', button='left'):
"""
Press the mouse button at specified X and Y coordinates.
*Example*:
| *Keyword* | *Attributes* | | |
| Mouseover Press | | | #By default perform mouse press on (0,0)) coordinates. |
| Mouseover Press | x_coordinates | y_coordinates | #Would perform mouse press to given coordinates. |
"""
logger.info(" Moving mouse to given X and Y coordinates and press " + button + "button i.e: clicking at " +
"(" + str(x_coordinates) + "," + str(y_coordinates) + ")")
try:
x_coordinates = int(x_coordinates)
y_coordinates = int(y_coordinates)
pywinauto.mouse.press(button=button, coords=(x_coordinates, y_coordinates))
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable move mouse to coordinates " + str(x_coordinates), str(y_coordinates) + " to perform " + \
button + " button click in Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def mouseover_release(self, x_coordinates, y_coordinates, button='left'):
"""
Release the mouse button at specified X and Y coordinates.
If already mose pressed on coordinates, this helps us to release the mouse press.
*Example*:
| *Keyword* | *Attributes* | | | |
| Mouseover Release | 10 | 10 | | #would perform mouse release on (10,10)) coordinates, if already pressed. |
| Mouseover Release | x_coordinates | y_coordinates | right | #Would perform mouse move to given coordinates. |
"""
logger.info(" Moving mouse to given X and Y coordinates and release " + button + "button i.e: releasing at " +
"(" + str(x_coordinates) + "," + str(y_coordinates) + ")")
try:
x_coordinates = int(x_coordinates)
y_coordinates = int(y_coordinates)
pywinauto.mouse.release(button=button, coords=(x_coordinates, y_coordinates))
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable move mouse to coordinates " + str(x_coordinates, y_coordinates) + " to perform " + button +\
" button release in Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def mousewheel_scroll(self, x_coordinates, y_coordinates, wheel_dist=1):
"""
Do mouse wheel scroll
If already mose pressed on coordinates, this helps us to release the mose press.
*Example*:
| *Keyword* | *Attributes* | | | |
| mousewheel scroll | 10 | 10 | | #would perform mouse scroll on (10,10)) coordinates. |
| mousewheel scroll | x_coordinates | y_coordinates | 1 | #Would perform 1 wheel mouse scroll at coordinates. |
"""
logger.info("scrolling mouse to given X and Y coordinates " + str(wheel_dist) +
" mouse wheel scroll i.e:scrolling at " + "(" + str(x_coordinates) + "," + str(y_coordinates) + ")")
try:
x_coordinates = int(x_coordinates)
y_coordinates = int(y_coordinates)
pywinauto.mouse.scroll(coords=(x_coordinates, y_coordinates), wheel_dist=wheel_dist)
except Exception as h1:
self.__screenshot_on_error__()
mess = " Unable Do mouse wheel to coordinates " + str(x_coordinates, y_coordinates) + " to perform " + \
str(wheel_dist) + " mouse wheel scroll in Application " + ":::: " + "because " + str(h1)
raise Exception(mess)
def input_text(self, element_property, text):
"""
Types the given ``text`` into the text field identified by ``element_property``.
Type keys to the element using keyboard.send_keys.
It parses modifiers Shift(+), Control(^), Menu(%) and Sequences like “{TAB}”, “{ENTER}”.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* | |
| Input Text | element property | XYZ |
| Input Text | element property | {TAB}{SPACE}{TAB} |
"""
logger.info("Typing text " + text + " into text field identified by " + element_property + ".")
try:
if self.dlg and self.backend is not None:
self.dlg[element_property].type_keys(text, pause=0.05, with_spaces=True, with_tabs=True,
with_newlines=True, turn_off_numlock=True)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to types the given" + text + "into the text field identified by " + element_property + "." \
+ " :::: " + "because " + str(h1)
raise Exception(mess)
def send_keystrokes(self, text):
"""
Silently send keystrokes to the control in an inactive window.
It parses modifiers Shift(+), Control(^), Menu(%) and Sequences like “{TAB}”, “{ENTER}”.
*Example*:
| *Keyword* | *Attributes* |
| Send Keystrokes | +^ |
"""
logger.info("sending keystrokes to the control in an inactive window.")
try:
if self.dlg and self.backend is not None:
if self.backend == 'win32':
self.dlg.send_keystrokes(text)
elif self.backend == "uia":
log = "This keyword is no longer support for uia controls, Use other send/type related keywords"
logger.info(log)
raise AssertionError
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to silently send keystrokes to the control in an inactive window. " + " :::: " \
+ "because " + log + str(h1)
raise Exception(mess)
def press_keys(self, keys, press_count=1, interval=0):
"""
This keyword Enters/performs the Keys actions On the ``window``.
Sends keys directly on screen into edit fields/ window by pyautogui.
The following are the valid strings to pass to the press() function:
https://pyautogui.readthedocs.io/en/latest/keyboard.html?highlight=press#keyboard-keys
press count helps to press the same key multiple times
*Example*:
| *Keyword* | *Attributes* | | | |
| Press Keys | tab | 2 | #would click tab 2 times | |
| Press Keys | A | 5 | 1 | #would click 'A' 5 times and for each time with 1 second time interval |
| Press Keys | enter | #would press the enter button | | |
"""
logger.info("'Pressing the given " + keys + " key(s) on Active Window"+"'.")
try:
time.sleep(0.25)
pyautogui.press(keys, presses=press_count, interval=interval)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to press the given" + keys + "on Window." + ":::: " + "because " + str(h1)
raise Exception(mess)
def text_writer(self, string, interval=0):
"""
The primary keyboard function is that types given string in to where cursor present at edit fields.
This function will type the characters in the string that is passed at cursor point. To add a delay interval
in between pressing each character key, pass an int or float for the interval keyword argument.
types given string directly on screen into edit fields/ window by pyautogui where cursor focused.
The following are the valid strings to pass to the write() function:
https://pyautogui.readthedocs.io/en/latest/keyboard.html?highlight=write#the-write-function
*Example*:
| *Keyword* | *Attributes* | | |
| Text Writer | HimaAne | #would type the given string with out any delay between character | |
| Text Writer | ABCD | 0.25 | #would type the given string with 0.25delay between each character |
"""
logger.info("'Pressing the given " + "`" + string + "`" + " string on Active Window" + "'.")
try:
time.sleep(0.25)
pyautogui.write(string, interval=interval)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to write/type the given " + "`" + string + "`" + " on Window where cursor placed." +\
":::: " + "because " + str(h1)
raise Exception(mess)
def clear_edit_field(self, element_property):
"""
This keyword Clears if any existing content available in Given Edit Field ``element_property`` On the window.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* |
| Clear Edit Field | Edit |
"""
logger.info("clearing the given edit fields " + element_property + " on Active Window.")
try:
if self.dlg and self.backend is not None:
self.dlg[element_property].set_text(u'')
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to clear the given edit field `" + element_property + "` on Active Window." + " :::: "\
+ str(h1)
raise Exception(mess)
def __checkbox_status__(self, element_property):
try:
cb_status = ""
if self.backend == "uia" and self.dlg is not None:
cb_status = self.dlg[element_property].get_toggle_state()
elif self.backend == "win32" and self.dlg is not None:
cb_status = self.dlg.CheckBox.is_checked()
return str(cb_status)
except Exception as h1:
mess = "couldn't find the check box status " + ":::: " + "because " + str(h1)
raise Exception(mess)
def select_checkbox(self, element_property):
"""
Selects(✔) the checkbox identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* |
| Select Checkbox | element property |
"""
try:
if self.dlg and self.backend is not None:
cb_status = self.__checkbox_status__(element_property)
logger.info("Enabling the checkbox")
logger.info("Checkbox is in unchecked state")
logger.info("checking (✔) unchecked checkbox")
if cb_status == str(0) or cb_status == str(False):
self.dlg[element_property].click_input()
logger.info("Changed checkbox state from unchecked to checked(✔) successfully. ")
elif cb_status == str(True) or cb_status == str(1):
logger.info("Checkbox is already in enabled/checked state (✔)")
else:
logger.info("Not able to retrieve the checkbox status, un supported & checkbox status is " +
cb_status)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to check (✔) the check box " + ":::: " + "because " + str(h1)
raise Exception(mess)
def unselect_checkbox(self, element_property):
"""
Removes the selection of checkbox identified by ``element_property``.
See the `Element property` section for details about the locator.
*Example*:
| *Keyword* | *Attributes* |
| Unselect Checkbox | element property |
"""
try:
if self.dlg and self.backend is not None:
cb_status = self.__checkbox_status__(element_property)
logger.info("Disabling the checkbox")
logger.info("Checkbox is in checked (✔) state")
logger.info("Unchecking (✔-->✖) checked checkbox")
if cb_status == str(1) or cb_status == str(True):
self.dlg[element_property].click_input()
logger.info("Changed checkbox state from checked(✔) to unchecked successfully. ")
elif cb_status == str(False) or cb_status == str(0):
logger.info("Checkbox is already in disabled/Unchecked state (✖)")
else:
logger.info("Not able to retrieve the checkbox status, un supported & checkbox status is "
+ cb_status)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to uncheck the check box " + ":::: " + "because " + str(h1)
raise Exception(mess)
def __screenshot_on_error__(self, screenshot="Application", screenshot_format="PNG", screenshot_directory=None,
width="800px"):
if self.take_screenshots is True:
self.capture_app_screenshot(screenshot, screenshot_format, screenshot_directory, width)
@keyword
def capture_app_screenshot(self, screenshot="Application", screenshot_format="PNG", screenshot_directory=None,
width="800px"):
"""
Takes a screenshot and embeds it into the log file.
By Default image extension will be .PNG.
This keyword supports .PNG/JPEG/JPG/TIFF/BMP image extensions.
This keyword is used to develop to take the screenshot even in VM/Remote/Desktop,
needs pass the screenshot name as parameter without format, default screenshot name will
be "Application Screenshot".
By Default all the screenshots will be located in results folder.
Provisioned to `set screenshot_directory` in keyword as optional argument.
*Example*:
| *Keyword* | *screenshot name* | *Format* | *screenshot_directory* | *width of screenshot* |
| Capture App Screenshot | | #By default screenshot name is Application screenshot, PNG format wth 880px |
| Capture App Screenshot | Notepad | TIFF |
| Capture App Screenshot | Notepad | JPEG | C:\\Hims | 880px |
"""
global screenshots_directory
if screenshot_directory is not None:
logger.info("Taking a screenshot in " + screenshot_format + " format and keeps in folder Location " +
screenshot_directory + ".")
if not os.path.exists(screenshot_directory):
os.makedirs(screenshot_directory)
screenshots_directory = screenshot_directory
else:
screenshots_directory = screenshot_directory
else:
logger.info("Taking a screenshot in " + screenshot_format + " format and embeds it into the log file.")
variables = BuiltIn().get_variables()
screenshots_directory = str(variables['${OUTPUTDIR}'])
screenshot_format = screenshot_format.lower()
if screenshot_format:
try:
index = 0
file_path = ""
pic = screenshot
for i in range(1000):
file_path = screenshots_directory + '\\' + pic + '_' + str(i) + '.'+screenshot_format
filename = pic + '_' + str(i) + '.'+screenshot_format
file_path = re.sub('([\w\W]+)\_0(\.'+screenshot_format+')$', r'\1\2', file_path)
hrefsrcpath = re.sub('([\w\W]+)\_0(\.'+screenshot_format+')$', r'\1\2', filename)
if os.path.exists(file_path):
pass
else:
index = i
break
if screenshot_directory is None:
logger.info(screenshot + '_Screenshot' + '</td></tr><tr><td colspan="3"><a href="%s"><img src="%s"\
width="%s"></a>' % (hrefsrcpath, hrefsrcpath, width), html=True)
else:
logger.info(screenshot + '_Screenshot' + '</td></tr><tr><td colspan="3"><a href="%s"><img src="%s"\
width="%s"></a>' % (file_path, file_path, width), html=True)
ph = pyautogui.screenshot()
ph.save(file_path)
except Exception as h1:
mess = "Unable to take application screenshot at " + str(index) + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_line(self, element_property, window_property, pattern='(.*)(L0, T0, R0, B0)(.*)', index=0, backend="uia"):
"""
Return the line which is matching to pattern. eg:By default sub-string (L0, T0, R0, B0) containing line
(by pattern).
Basically when don't have object properties to perform actions or to get status, use this keyword to get
backend properties by using matching pattern and assign boolean values to verify. Based on matching pattern
line of property will return.
print controls manually and use below application to make matching regex pattern.
For patterns: follow https://regexr.com/
refer `returning variable status`
By Default this keyword serves with zero index application, pattern (.*)(L0, T0, R0, B0)(.*)
and backend process of uia.
See the `Element property` and `Window property` section for details about the locator.
*Example*:
| *Keyword* | *element_property* | *Window property* | *pattern* | *index* | *backend process* |
| Get Line | element property | class_name:PQRS | (.*)(L989, T878, R767, B656)(.*) | 0 | win32 |
"""
try:
global result
app = pywinauto.application.Application(backend=backend)
self._window_handle_(window_property, index)
app.connect(handle=w_handle)
window = app.window(handle=w_handle)
window.set_focus()
if element_property is not None:
window[element_property].print_ctrl_ids()
elif element_property is None:
window.print_ctrl_ids()
printed_controls = sys.stdout.getvalue()
sl = printed_controls.splitlines()
for line in sl:
if re.match(pattern, line):
result = line
return result
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to Drawn Details: " + ":::: " + "because " + str(h1)
raise Exception(mess)
def returning_variable_status(self, variable, element_property, window_property, pattern,
index, backend):
"""
This keyword will return the boolean value based on variable availability in pattern matched line.
Variable is nothing but some string. returns Status for the given variable.
if variable available than boolean value ``Ture`` will return else ``False``.
*Example*:
| *Keyword* | *variable* | *element_property* | *Window property* | *pattern* | *index* | *backend process* |
| Returning Variable Status | Some required string | element property | class_name:ABCD | (.*)(L989, T878, R767, B656)(.*) | 0 | win32 |
"""
try:
result = self.get_line(element_property, window_property, pattern, index, backend)
if variable in result:
return True
else:
return False
except Exception as h1:
mess = "Unable to Drawn Details: " + ":::: " + "because " + str(h1)
raise Exception(mess)
def close_application_window(self, window_property, backend_process="win32", index=0):
"""
Close the window by pressing Alt+F4 keys.
This keyword helps us to close the active application window using window handle. This keyword also helps to us
to close application.
Need to pass the title/class_name as arguments.
if title available ---> title:PQR
if class available---> class_name:XZY
*Example*:
| *Keyword* | *Attributes* | *backend process* | *Index* |
| Close Application Window | window property | #By default window closes where index Zero and by backend process win32 |
| Close Application Window | window property | uia | 1 |
"""
try:
pwa_app = pywinauto.application.Application(backend=backend_process)
self._window_handle_(window_property, index)
pwa_app.connect(handle=w_handle)
window = pwa_app.window(handle=w_handle)
window.set_focus()
window.close_alt_f4()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Failed to close application window" + ":::: " + "because " + str(h1)
raise Exception(mess)
def __returnElementStateOnWindow__(self, element_property, window_property, index, msg=None):
try:
global status
self._window_handle_(window_property, index)
if checkup_state == 'visible':
status = self.dlg[element_property].is_visible()
if checkup_state == 'enable':
status = self.dlg[element_property].is_enabled()
return status
except Exception as e1:
print(e1)
if kick_off_time >= culmination_time:
error = AssertionError(msg) if msg else AssertionError(self)
error.ROBOT_EXIT_ON_FAILURE = True
raise error
@keyword
def get_element_visible_state(self, element_property):
"""
Returns ``True`` when element visible in current window.
returns True only when element is visible in current window.
See the `Element property` section for details about the locator.
Make sure your application response while using this keyword.ss
*Example*:
| *Keyword* | *Attributes* | |
| Get Element Visible State | element property | #would return only true when element is visible. |
"""
try:
if self.dlg and self.backend is not None:
state = self.dlg[element_property].is_visible()
return state
except Exception as h1:
print(h1)
pass
@keyword
def get_element_enable_state(self, element_property):
"""
Returns ``True`` when element enabled in current window.
returns True only when element is visible in current window.
See the `Element property` section for details about the locator.
Make sure your application response while using this keyword.
*Example*:
| *Keyword* | *Attributes* | |
| Get Element enable State | element property | #would return true when element is enabled. |
"""
try:
if self.dlg and self.backend is not None:
state = self.dlg[element_property].is_enabled()
return state
except Exception as h1:
print(h1)
pass
def wait_until_window_element_is_visible(self, element_property, window_property='title:Untitled - Notepad',
index=0, timeout=60, retry_interval=1):
"""
Waits for ``element_property`` to be made visible in given ``Window``
Wait Until Window Element Is Visible by default with maximum timeout of 60 seconds configured.
By default this will be for Notepad console.
To wait for required object to visible in window, pass respective ``Element property`` and ``Window property``.
pass as an arguments like below as shown.
if title is available ---> title:XZY
if class is available---> class_name:PQR
See the `Element property` and `Window property` section for details about the locator.
*Example*:
| *Keyword* | *Element property* | *window property* | *app index* | *timeout* | *Retry Interval* |
| Wait Until Window Element Is Visible | Edit | # This waits for Edit object to present in 60 seconds with retry interval 1sec in notepad application, |
| Wait Until Window Element Is Visible | element property | class_name:xyz | 1 | 30 | 2 |
"""
global checkup_state
checkup_state = 'visible'
logger.info("Waiting for element to be visible.")
self.__finds_window_contains_status__(element_property, window_property, index, timeout, retry_interval)
def wait_until_window_element_is_enabled(self, element_property, window_property='title:Untitled - Notepad',
index=0, timeout=60, retry_interval=1):
"""
Waits for ``element_property`` to be enabled in given ``Window``
Wait Until Window Element Is Enabled by default with maximum timeout of 60 seconds configured.
By default this will be for Notepad console.
To wait for required object to enable in window, pass respective ``Element property`` and ``Window property``.
pass as an arguments like below as shown.
if title is available ---> title:XZY
if class is available---> class_name:PQR
See the `Element property` and `Window property` section for details about the locator.
*Example*:
| *Keyword* | *Element property* | *window property* | *app index* | *timeout* | *Retry Interval* |
| Wait Until Window Element Is Enabled | Edit | # This waits for Edit object to present in 60 seconds with retry interval 1sec in notepad application, |
| Wait Until Window Element Is Enabled | element property | class_name:xyz | 1 | 30 | 2 |
"""
global checkup_state
checkup_state = 'enable'
logger.info("Waiting for element to be enable.")
self.__finds_window_contains_status__(element_property, window_property, index, timeout, retry_interval)
def __finds_window_contains_status__(self, element_property, window_property, index, timeout, retry_interval):
try:
global kick_off_time
global culmination_time
kick_off_time = datetime.now()
culmination_time = datetime.now() + timedelta(seconds=timeout)
while kick_off_time <= culmination_time:
value = self.__returnElementStateOnWindow__(element_property, window_property, index)
if value is True:
logger.info("Window element " + "``" + element_property + "``" + " is " + checkup_state +
" in Given window where " + "``" + window_property + "``")
return value
else:
time.sleep(retry_interval)
kick_off_time = datetime.now()
logger.info("Window element " + "``" + element_property + "``" + " is not " + checkup_state +
" in Given window where " + "``" + window_property + "``")
raise AssertionError
except Exception as h1:
self.__screenshot_on_error__('timeout')
msg = ("Timeout Error.Could not find matching element. After waiting for {0} seconds "
.format(str(timeout))) + str(h1)
error = AssertionError(msg) if msg else AssertionError(self)
error.ROBOT_EXIT_ON_FAILURE = True
raise error
def wait_until_window_present(self, window_property='title:Untitled - Notepad', timeout=60, retry_interval=1,
index=0):
"""
Waits for window to be present
Wait Until window present by default with maximum timeout of 60 seconds configured. By default this will be for
Notepad console.
To focus any other window screen, pass respective `Window property`. Pass as an argument like below
as shown.
if title is available ---> title:XZY
if class is available---> class_name:PQR
See the `Element property` and `Window property` section for details about the locator.
*Example*:
| *Keyword* | *window property* | *timeout* | *Retry Interval* | *app index* |
| Wait Until Window Present | optional Argument is WidowProperty, By Default it will look for Notepad |
| Wait Until Window Present | title:Untitled - Notepad | #This waits for window to present in 60 seconds with retry interval 1sec in zero index notepad application. |
| Wait Until Window Present | class_name: Save As | #By Class Name of window |
| Wait Until Window Present | class_name: Save | 60 | 1 | 0 |
"""
try:
global culmination_time
global kick_off_time
kick_off_time = datetime.now()
culmination_time = datetime.now() + timedelta(seconds=timeout)
while kick_off_time <= culmination_time:
try:
self._window_handle_(window_property, index)
logger.info("Window present with "+window_property)
return w_handle
except Exception as e:
logger.info("Window not present with " + window_property + " "":::: " + "because " + str(e))
time.sleep(retry_interval)
kick_off_time = datetime.now()
raise AssertionError
except Exception as h1:
self.__screenshot_on_error__('timeout')
msg = ("Timeout Error.Couldn't find matching Window. After waiting for {0} seconds ".format(str(timeout)))\
+ str(h1)
error = AssertionError(msg) if msg else AssertionError(self)
error.ROBOT_EXIT_ON_FAILURE = True
raise error
def close_application(self, command):
"""
Closes the application.
This should only be used when it is OK to kill the process like you would do in task manager.
Use ``task kill`` command to close the application.
*Example*:
| *Keyword* | *Attributes* |
| Close Application | command |
"""
try:
p = subprocess.Popen(command, universal_newlines=True, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
logger.info("Running command '%s'." % command)
output = p.stdout.read()
output1 = p.stderr.read()
ret_code = p.wait()
if ret_code != 0:
output = "Application is no more in active state."
logger.info("Ret code is " + str(ret_code) + " and " + output + " Verification Message: " + output1)
return
if 'SUCCESS:' in output:
logger.info("Ret code is " + str(ret_code) + " and Verification Message: " + output)
self.close_application(command)
except Exception as h1:
logger.info(h1)
def select_menu(self, menu_path):
"""
Select a menu item specified in the path.
*Example*:
| *Keyword* | *Attributes* | |
| Select Menu | Edit->Go To... | #Check notepad Edit menu option |
"""
try:
if self.dlg and self.backend is not None:
self.dlg.menu_select(menu_path)
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to select the menu path " + ":::: " + "because " + str(h1)
raise Exception(mess)
def select_combobox_item(self, combobox, item):
"""
Select the ComboBox item
``item`` argument should be given as available item from combobox list.
``item`` can be either a 0 based index of the item to select or it can be the string that you want to select
*Example*:
| *Keyword* | *Attributes* | | |
| Select Combobox_Item | ComboBox1 | item text | #would select item in combobox |
| Select Combobox_Item | ComboBox1 | item index | #would select item in combobox based on index |
"""
try:
if self.dlg and self.backend is not None:
log = ""
if item.isdigit():
item = int(item)
log = "WithIndex"
combo = self.dlg[combobox]
combo.select(item)
except Exception as h1:
time.sleep(1)
logger.info(h1)
self.__screenshot_on_error__('SelectedComboItem' + log + str(item))
pass
def get_selected_combobox_item_index(self, combobox):
"""
Return the selected item index.
*Example*:
| *Keyword* | *Attributes* | |
| Get Selected Combobox Item Index | ComboBox2 | #would return selected item index from given combobox |
"""
try:
if self.dlg and self.backend is not None:
combo = self.dlg[combobox]
index = combo.selected_index()
return index
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to select the combobox item " + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_combobox_list_items(self, combobox):
"""
Return the text of the items in the combobox
*Example*:
| *Keyword* | *Attributes* | |
| Get Combobox List Items | ComboBox3 | #would return items as a list from given combobox |
"""
try:
if self.dlg and self.backend is not None:
combo = self.dlg[combobox]
combo_list = combo.texts()
return combo_list
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to select the combobox item " + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_combobox_selected_item_text(self, combobox):
"""
Return the selected item text.
*Example*:
| *Keyword* | *Attributes* | |
| Get Combobox Selected Item Text | ComboBox4 | #would return selected item text from given combobox |
"""
try:
if self.dlg and self.backend is not None:
combo = self.dlg[combobox]
selected_item_text = combo.selected_text()
return selected_item_text
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to select the combobox item " + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_combobox_items_count(self, combobox):
"""
Return the number of items in the combobox
*Example*:
| *Keyword* | *Attributes* | |
| Get Combobox Items count | ComboBox5 | #would return items count present within the combobox |
"""
try:
if self.dlg and self.backend is not None:
combo = self.dlg[combobox]
combo_items_count = combo.item_count()
return combo_items_count
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to select the combobox item " + ":::: " + "because " + str(h1)
raise Exception(mess)
def select_list_item(self, listview, item):
"""
Select the list item
``item`` argument should be given as available item from list items.
``item`` can be either a 0 based index of the item to select or it can be the string that you want to select
To shift to win32 controls, just use the `Focus Application Window`
*Example*:
| *Keyword* | *Attributes* | | |
| Focus Application Window | title:Print | win32 | |
| Select List Item | ListView | item text | #would select item in list based on item string |
| Select List Item | ListView | item index | #would select item in list based on item index |
"""
try:
if self.dlg and self.backend is not None:
log = " by item string"
if item.isdigit():
item = int(item)
log = "by item index"
b = self.dlg[listview]
b.set_focus()
b.select(item)
self.capture_app_screenshot('SelectedListItem' + log + str(item))
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to select the given Item from the list view " + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_list_item_text(self, listview, item):
"""
Returns the list item text.
``item`` argument should be given as available item from list items.
``item`` can be either a 0 based index of the item to select or it can be the string that you want to select
Use `Focus Application Window` keyword anytime to shift the control of execution between backend process
win32 and uia.
*Example*:
| *Keyword* | *Attributes* | | |
| Focus Application Window | title:Print | win32 | |
| Get List Item Text | ListView | item text | #would select item in list based on item string |
| Get List Item Text | ListView | item index | #would select item in list based on index |
"""
try:
if self.dlg and self.backend is not None:
log = "by item string"
if item.isdigit():
item = int(item)
log = "by Item Index"
b = self.dlg[listview]
list_item = b.item(item).text()
return list_item
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to get the list item text from list box " + log + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_list_items_count(self, listview):
"""
Returns the list items count.
Use `Focus Application Window` keyword anytime to shift the control of execution between backend process
win32 and uia.
*Example*:
| *Keyword* | *Attributes* | |
| Focus Application Window | title:Print | win32 |
| Get List Items Count | ListView | #would return items count from list |
"""
try:
if self.dlg and self.backend is not None:
list_items_count = self.dlg[listview].item_count()
return list_items_count
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to get the list items count from list box " + ":::: " + "because " + str(h1)
raise Exception(mess)
def check_list_item_present(self, listview, item):
"""
Returns ``item handle`` if given item present in list, else return failure.
Use `Focus Application Window` keyword anytime to shift the control of execution between backend process
win32 and uia.
``item`` can be either a 0 based index of the item to select or it can be the string that you want to select
*Example*:
| *Keyword* | *Attributes* | | |
| Focus Application Window | title:Print | win32 | |
| Check List Item Present | ListView | item text | #would check item in list based on item string |
| Check List Item Present | ListView | item index | #would check item in list based on index |
"""
try:
if self.dlg and self.backend is not None:
log = "By item string"
if item.isdigit():
item = int(item)
log = "By Item Index"
list_items = self.dlg[listview]
item_handle = list_items.check(item)
return item_handle
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to check the list item presence from list box " + log + ":::: " + "because " + str(h1)
raise Exception(mess)
def get_systemTray_icon_Text(self, app_child_window_property, timeout=1,
taskbar_win_property='class_name:Shell_TrayWnd',
show_hidden_icons_property="title:Notification Chevron",
sys_tray_property="class_name:NotifyIconOverflowWindow", backend='uia'):
"""
Returns the text of systemTray Icon.
`timeout`, `taskbar_win_property` , `show_hidden_icons_property` , `sys_tray_property` , `backend`
is optional arguments. If property changes use appropriate properties.
Increase and use timeout argument for sync purpose to perform the get text of application action.
This keyword internally handles: connecting to taskbar, clicking on show hidden icon (^) from task bar,
takes application control from tray icons to perform the actions.
*Example*:
| *Keyword* | *Attributes* | | |
| Get SystemTray Icon Text | title:notepad | | #would return app text with by default 1 second time wait |
| Get SystemTray Icon Text | class_name:note | 2 | #would return app text from systemTray with 2seconds wait |
"""
logger.info("Getting text of " + "`" + app_child_window_property + "`" + " application from system tray")
try:
self.__openSysTray_ConnectTray_TakeAppChildWindowControl__(app_child_window_property, timeout,
taskbar_win_property, show_hidden_icons_property,
sys_tray_property, backend)
iconText = self.hae.window_text()
logger.info(iconText)
return iconText
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to get the text of application Icon which is present in the systemTray " + ":::: " + \
"because " + str(h1)
raise Exception(mess)
def click_on_show_hidden_icons(self, taskbar_win_property, show_hidden_icons_property, backend):
"""
clicks on show hidden icons (^) from task bar.
*Example*:
| *Keyword* | *Attributes-->* *taskbar_win_property* | *show_hidden_icons_property* | *backend* |
| Click On Show Hidden Icons | class_name:Shell_TrayWnd | title:Notification Chevron | uia |
"""
logger.info("Clicking at show hidden icons (^) option from task bar")
try:
self.connect_taskbar(taskbar_win_property, backend)
self.__apps_child_window_handle__(show_hidden_icons_property)
self.hae.click()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to open show hidden icons (From Tool Bar-->^) " + ":::: " + "because " + str(h1)
raise Exception(mess)
def __connect_to_tray_handle__(self, timeout, sys_tray_property, backend):
self.connect_app(sys_tray_property, backend)
self.hae = self.dlg
self.hae.wait('visible', timeout=timeout, retry_interval=.25)
def connect_app(self, window_property, backend):
"""
connects to application window, it will only perform connect function based on title/class_name of the
applications.
it will made connection to application and returns reference in self.dlg variable.
*Example*:
| *Keyword* | *Attributes-->* *window_property* | *backend* |
| Connect App | class_name:Shell_TrayWnd | uia |
| Connect App | title:Shell_TrayWnd | win32 |
"""
if 'title:' in window_property:
win_prop = window_property.replace('title:', '')
app = pywinauto.application.Application(backend=backend).connect(title=win_prop)
self.dlg = app.window(title=win_prop)
elif 'class_name:' in window_property:
win_prop = window_property.replace('class_name:', '')
app = pywinauto.application.Application(backend=backend).connect(class_name=win_prop)
self.dlg = app.window(class_name=win_prop)
def connect_taskbar(self, taskbar_win_property, backend):
"""
connects to window taskbar, it will made connection to taskbar and returns reference in self.hae variable.
Use Shell_TrayWnd class name to connect taskbar
*Example*:
| *Keyword* | *Attributes-->* *window_property* | *backend* |
| Connect Taskbar | class_name:Shell_TrayWnd | uia |
"""
logger.info("Connecting to task bar")
self.connect_app(taskbar_win_property, backend)
self.hae = self.dlg
def click_on_systemTray_icon(self, app_child_window_property, timeout=1,
taskbar_win_property='class_name:Shell_TrayWnd',
show_hidden_icons_property="title:Notification Chevron",
sys_tray_property='class_name:NotifyIconOverflowWindow', backend='uia'):
"""
Performs Click on application Icon presents in SystemTray.
`timeout`, `taskbar_win_property` , `show_hidden_icons_property` , `sys_tray_property` , `backend`
is optional arguments. If property changes use appropriate properties.
Increase and use timeout argument for sync purpose to perform the click action.
This keyword internally handles: connecting to taskbar, clicking on show hidden icon (^) from task bar,
takes application control from tray icons to perform the click action on tray apps.
*Example*:
| *Keyword* | *Attributes* |
| Click On SystemTray Icon | title:Microsoft Teams - New activity |
"""
logger.info("Clicking on " + "`" + app_child_window_property + "`" + " application from system tray")
try:
self.__openSysTray_ConnectTray_TakeAppChildWindowControl__(app_child_window_property, timeout,
taskbar_win_property, show_hidden_icons_property,
sys_tray_property, backend)
self.hae.click()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to click on application icon which is presents in systemTray " + ":::: " + "because " + \
str(h1)
raise Exception(mess)
def double_click_on_systemTray_icon(self, app_child_window_property, timeout=1,
taskbar_win_property='class_name:Shell_TrayWnd',
show_hidden_icons_property="title:Notification Chevron",
sys_tray_property="class_name:NotifyIconOverflowWindow", backend='uia'):
"""
Performs Double clicks on application Icon presents in SystemTray.
`timeout`, `taskbar_win_property` , `show_hidden_icons_property` , `sys_tray_property` , `backend`
is optional arguments. If property changes use appropriate properties.
Increase and use timeout argument for sync purpose to perform the click action.
This keyword internally handles: connecting to taskbar, clicking on show hidden icon (^) from task bar,
takes application control from tray icons to perform the double click action on tray apps.
*Example*:
| *Keyword* | *Attributes* | |
| Double Click On SystemTray Icon | title:Microsoft Teams - New activity | |
| Double Click On SystemTray Icon | title:Microsoft Teams - New activity | 2 |
"""
logger.info("Double clicking on " + "`" + app_child_window_property + "`" + " application from system tray")
try:
self.__openSysTray_ConnectTray_TakeAppChildWindowControl__(app_child_window_property, timeout,
taskbar_win_property, show_hidden_icons_property,
sys_tray_property, backend)
self.hae.double_click_input()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to double click on application icon which is presents in systemTray " + ":::: " + \
"because " + str(h1)
raise Exception(mess)
def __apps_child_window_handle__(self, window_property):
if 'title:' in window_property:
win_prop = window_property.replace('title:', '')
self.hae = self.hae.child_window(title=win_prop).wrapper_object()
elif 'class_name:' in window_property:
win_prop = window_property.replace('class_name:', '')
self.hae = self.hae.child_window(class_name=win_prop).wrapper_object()
def right_click_on_systemTray_icon(self, app_child_window_property, timeout=1,
taskbar_win_property='class_name:Shell_TrayWnd',
show_hidden_icons_property="title:Notification Chevron",
sys_tray_property="class_name:NotifyIconOverflowWindow", backend='uia'):
"""
Performs Right click on application Icon presents in SystemTray.
`timeout`, `taskbar_win_property` , `show_hidden_icons_property` , `sys_tray_property` , `backend`
is optional arguments. If property changes use appropriate properties.
Increase and use timeout argument for sync purpose to perform the click action.
This keyword internally handles: connecting to taskbar, clicking on show hidden icon (^) from task bar,
takes application control from tray icons to perform the right click action on tray apps.
*Example*:
| *Keyword* | *Attributes* |
| Right Click On SystemTray Icon | title:Microsoft Teams - New activity |
"""
logger.info("right clicking on " + "`" + app_child_window_property + "`" + " application from system tray")
try:
self.__openSysTray_ConnectTray_TakeAppChildWindowControl__(app_child_window_property, timeout,
taskbar_win_property, show_hidden_icons_property,
sys_tray_property, backend)
self.hae.click_input(button="right")
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to right click on application icon which is present in systemTray Icon " + ":::: " + \
"because " + str(h1)
raise Exception(mess)
def __openSysTray_ConnectTray_TakeAppChildWindowControl__(self, app_child_window_property, timeout,
taskbar_win_property, show_hidden_icons_property,
sys_tray_property, backend):
self.click_on_show_hidden_icons(taskbar_win_property, show_hidden_icons_property, backend)
time.sleep(timeout)
logger.info("Connecting to system tray handle")
self.__connect_to_tray_handle__(timeout, sys_tray_property, backend)
logger.info("Taking control of app child window present in system tray to perform actions")
self.__apps_child_window_handle__(app_child_window_property)
def click_on_window_start(self, windows_icon_property='class_name:Start',
taskbar_win_property='class_name:Shell_TrayWnd', backend='uia'):
"""
Clicks at windows Icon at task bar.
`windows_icon_property` , `taskbar_win_property` and `backend` are optional arguments. If property changes use
appropriate properties.
Clicking based on windows class property by default.
*Example*:
| *Keyword* | *Attributes* |
| Click On Window Start | #would clicks on windows button |
"""
try:
self.connect_taskbar(taskbar_win_property, backend)
self.__apps_child_window_handle__(windows_icon_property)
logger.info("Clicking on Windows Icon at taskbar")
self.hae.click()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to clicks on windows start button from task bar " + ":::: " + "because " + str(h1)
raise Exception(mess)
def click_at_windows_type_here_to_search_option(self, button='Button1',
taskbar_win_property='class_name:Shell_TrayWnd', backend='uia'):
"""
Clicks at window's "type here to search" in task bar.
`button` , `taskbar_win_property` and `backend` are optional arguments. If property changes use
appropriate properties.
*Example*:
| *Keyword* | *Attributes* | |
| Click At Windows Type here To Search Option | #would clicks on windows Search option | |
| Click At Windows Type here To Search Option | Button1 | #would clicks on windows Search option |
"""
try:
self.connect_taskbar(taskbar_win_property, backend)
logger.info("Clicking on ``Type here to search`` in task bar.")
self.hae[button].click()
except Exception as h1:
self.__screenshot_on_error__()
mess = "Unable to clicks on windows type here search option button from task bar " + ":::: " + \
"because " + str(h1)
raise Exception(mess) | /robotframework-PyWindowsGuiLibrary-2.1.tar.gz/robotframework-PyWindowsGuiLibrary-2.1/PyWindowsGuiLibrary/PyWindowsGuiLibrary.py | 0.680454 | 0.378172 | PyWindowsGuiLibrary.py | pypi |
# RobotOil
- [RobotOil](#robotoil)
- [Introduction](#introduction)
- [Dependencies](#dependencies)
- [Installation](#installation)
- [Importing RobotOil](#importing-robotoil)
- [Importing into Robot](#importing-into-robot)
- [Importing into Python](#importing-into-python)
- [Features and Examples](#features-and-examples)
- [Smart Browser](#smart-browser)
- [Smart Browser Example](#smart-browser-example)
- [Smart Keywords](#smart-keywords)
- [Smart Click Example](#smart-click-example)
- [Smart Keywords from Python](#smart-keywords-from-python)
- [Conclusion](#conclusion)
## Introduction
RobotOil is a library of quality-of-life features for automated test case development with [Robot Framework](https://robotframework.org/) and [SeleniumLibrary](https://github.com/robotframework/SeleniumLibrary).
Enhancements include the option of persistent browser sessions to assist with debugging your scripts and "Smart" versions of common-use SeleniumLibrary Keywords to make navigating your web application even easier. Additionally, everything within RobotOil may be executed from either a Robot Test Suite OR the execution of a Python file.
Grease the gears of your next automation project with [RobotOil](https://github.com/Worakow1138/RobotOil)!
## Dependencies
Requires RobotFramework and SeleniumLibrary.
Use these commands to stay up to date with the latest versions.
pip install robotframework -U
pip install robotframework-seleniumlibrary -U
## Installation
Recommend using pip to install RobotOil.
pip install robotframework-RobotOil -U
If using [GitHub](https://github.com/Worakow1138/RobotOil), copy the RobotOil folder from the src folder to anywhere in your PATH.
Ideally, to the (your Python library)/Lib/site-packages folder.
## Importing RobotOil
RobotOil and all Keywords within may be executed from either a Robot Test Suite or a Python module.
### Importing into Robot
Simply call RobotOil as Library within your Test Suite or Resource file of choice.
*** Settings ***
Library RobotOil
### Importing into Python
Import the RobotOil module and class into a Python file.
All RobotOil Keywords/methods may be called from this class.
from RobotOil import RobotOil
oil_can = RobotOil()
## Features and Examples
### Smart Browser
If you've worked with Selenium, you've likely noticed how every automated test needs to begin with the creation of a new browser session.
Even with debugging tools native to many IDE's, automated test cases with traditional browser sessions can become incredibly time-consuming to maintain when needing to, say, correct step 48 of a 50 step test case but needing to execute steps 1-47 everytime you try a new fix.
By contast, Smart Browser sessions provide the option to remain open after a Robot or Python test execution has finished allowing them to be reusable for additonal sessions as long as the browser remains open and no new sessions are created.
#### Smart Browser Example
Create a file named `oil_test.robot` anywhere on your machine and enter the following code:
*** Settings ***
Library SeleniumLibrary
Library RobotOil
*** Test Cases ***
Begin Session
Open Smart Browser https://phptravels.com/demo chrome persist
In a console, run the command `robot -t "Begin Session" PATH_TO_TEST_SUITE\oil_test.robot`.
A chrome browser session is started and the test site is navigated to.
Leave this browser *open* before beginning the next step.
In the same `oil_test.robot` Test Suite, add this Test Case:
Continue Session
Use Current Smart Browser
Maximize Browser Window
Run this Test Case via `robot -t "Continue Session" PATH_TO_TEST_SUITE\oil_test.robot`.
If all goes well, you should see the same browser session you opened earlier become maximized.
You may continue to send commands to Smart Browser Sessions via `Use Current Smart Browser` until either closing the browser or
creating a new Smart Browser.
When it's actually time to close up the browser and any webdrivers that may be hanging around, simply call the `Cleanup Smart Browser` Keyword.
### Smart Keywords
The [SeleniumLibrary](https://github.com/robotframework/SeleniumLibrary) package features a wide variety of powerful Keywords for interacting with web elements.
Keywords like Click Element, Input Text, and so forth probably make up the bulk of most web automation projects using [Robot Framework](https://robotframework.org/).
However, these Keywords are often limited when dealing with the unpredictability of page load times and elements appearing asynchronously on a given web page.
These limitations cause unexpected failures and sometimes require complex or time-consuming workarounds.
Smart Keywords offer enhanced versions of these SeleniumLibrary Keywords that account for this unpredictability and provide additonal quality-of-life improvements by:
1. Automatically waiting for targeted elements to be visible before attempting to interact
2. Allowing for the "time to wait" to be established per Keyword call
3. Being accessible from a Python method as well as a Robot Test Case
#### Smart Click Example
In the same `oil_test.robot` Test Suite from earlier, copy the following code:
Text Retrieval Test
Open Smart Browser https://the-internet.herokuapp.com/dynamic_loading/2 chrome
Maximize Browser Window
Click Element css:#start > button
${hello_text} Get Text css:#finish
Run using `robot -t "Text Retrieval Test" PATH_TO_TEST_SUITE\oil_test.robot`.
This test ends up failing because the Get Text keyword gives up looking for the #finish id before this element can become available.

A typical workaround to this issue might include having to write in a `Wait For Page to Contain Element` or worse, a call to the dreaded `Sleep` Keyword. Static waits like Sleep and the variability of internet connections and server responses do NOT mix well and having to write out a `Wait For...` Keyword before nearly every test step is a chore.
Instead, simple add the word `Smart` to the `Get Text` keyword so the last line looks like this:
${hello_text} Smart Get Text css:#finish
And run the test again. The test passes due to `Smart Get Text` understanding that it has to wait until the "finish" element is visible before attempting to retrieve its text.
If you want to ensure that the finish element, or any element you want to interact with using a Smart Keyword, becomes visible within a known time limit, you may simply give the `timeout` parameter a specific argument like so:
${hello_text} Smart Get Text css:#finish timeout=120
This will make `Smart Get Text` wait for **up to** 2 minutes for the finish element to become visible before attempting to click the button.
Note: Not all SeleniumLibrary Keywords are available by simply adding `Smart` as a prefix. If a keyword has not been explicitly added to the `Smart Keywords` class, you may add `Smart Keyword` to a SeleniumLibrary keyword and receive the same benefits. For example:
${hello_text} Smart Keyword Get Text css:#finish timeout=120
With this enhancement, you'll never have to explicitly call another `Sleep` or `Wait For...` Keyword in your test cases again!
#### Smart Keywords from Python
One of RobotFramework's greatest advantages is the ease of creating custom Python libraries and methods and being able to execute these directly from a Robot Test Case.
This is especially useful when needing to write out a more complex set of actions from Python where features like nested for loops, while loops, etc, are available.
To further facilitate this capability, Smart Keywords are also accessible from your extended Python libraries and methods.
Create a file named `click_test.py` anywhere on your machine, copy the following example code, and execute the file:
from RobotOil import RobotOil
oil_can = RobotOil()
oil_can.open_smart_browser('https://phptravels.com/', 'chrome', 'persist')
oil_can.browser.maximize_window()
oil_can.smart_click_element('link:Features')
oil_can.smart_click_element('link:Main Features')
oil_can.smart_click_element('link:Demo')
To move this functionality back into your established Robot Test Cases, simply wrap this code in a method:
from RobotOil import RobotOil
oil_can = RobotOil()
def python_clicking():
oil_can.open_smart_browser('https://phptravels.com/', 'chrome', 'persist')
oil_can.browser.maximize_window()
oil_can.smart_click_element('link:Features')
oil_can.smart_click_element('link:Main Features')
oil_can.smart_click_element('link:Demo')
And import the file into your `oil_test.robot` Test Suite:
*** Settings ***
Library SeleniumLibrary
Library RobotOil
Library PATH_TO_CLICK_TEXT/click_test.py
From there, simply call `Python Clicking` from a Test Case of your choice:
*** Test Cases ***
Python Example
Python Clicking
You may now leverage the already powerful SeleniumLibrary Keywords, with Smart Keyword enhancements, DIRECTLY from Python, and back into your Robot Test Cases!
## Conclusion
I hope you enjoy the additional capabilities and ease-of-use that RobotOil brings to automated web testing with RobotFramework.
Please don't hesitate to reach out with questions or suggestions on [GitHub](https://github.com/Worakow1138/RobotOil) | /robotframework-RobotOil-1.0.0.tar.gz/robotframework-RobotOil-1.0.0/README.md | 0.810028 | 0.824885 | README.md | pypi |
from ScapyLibrary.utils.baseclass import _BaseClass
from ScapyLibrary.utils._scapy import scapylib
class SendRecv(_BaseClass):
def send_and_receive_at_layer3(self, packet, return_answer=True,
return_unanswer=False, return_send=False, *args, **kwargs):
'''This keyword support send layer 3 packets and receive the answers, it use "sr" function in scapy
@packet: Layer 3 packets created by scapy
@return_answer: boolean, whether return answered packets
@return_unanswer: boolean, whether return unanswered packets
@return_send: boolean, whether return sended packets which are answered
@args: please check doc of "sr" function in scapy to get detail
@kwargs: please check doc of "sr" function in scapy to get detail
@return: return sended packets/answered packets/unanswered packets,
By default, only answered packets are return
| ${answered} | Send And Receive At Layer3 | ${packets} | timeout=${10} |
| Log Packets | ${answered[0]} |
| ${answered} | Send And Receive At Layer3 | ${packets} | timeout=${10} | return_send=${True} |
| Log Packets | ${answered[0][0]} |
| Log Packets | ${answered[0][1]} |
| ${answered} | ${unanswered} | Send And Receive At Layer3 | ${packets} | timeout=${10} | return_send=${True} | return_answer=${True} |
| Log Packets | ${answered[0][0]} |
| Log Packets | ${answered[0][1]} |
| Log Packets | ${unanswered[0]} |
'''
an, unan = scapylib.sr(packet, *args, **kwargs)
answered = scapylib.plist.PacketList(name='Answered')
returnAnswer = True
if return_answer and return_send:
answered = an
elif (not return_answer) and return_send:
for _an in an:
answered.append(_an[0])
elif return_answer and (not return_send):
for _an in an:
answered.append(_an[1])
else:
returnAnswer = False
if returnAnswer and return_unanswer:
return answered, unan
elif returnAnswer and (not return_unanswer):
return answered
elif (not returnAnswer) and return_unanswer:
return unan
def send_and_receive_at_layer2(self, packet, return_answer=True,
return_unanswer=False, return_send=False, *args, **kwargs):
'''This keyword support send layer 2 packets and receive the answers, it use "srp" function in scapy
@packet: Layer 2 packets created by scapy
@return_answer: boolean, whether return answered packets
@return_unanswer: boolean, whether return unanswered packets
@return_send: boolean, whether return sended packets which are answered
@args: please check doc of "sr" function in scapy to get detail
@kwargs: please check doc of "sr" function in scapy to get detail
@return: return sended packets/answered packets/unanswered packets,
By default, only answered packets are return
| ${answered} | Send And Receive At Layer2 | ${packets} | timeout=${10} |
| Log Packets | ${answered[0]} |
| ${answered} | Send And Receive At Layer2 | ${packets} | timeout=${10} | return_send=${True} |
| Log Packets | ${answered[0][0]} |
| Log Packets | ${answered[0][1]} |
| ${answered} | ${unanswered} | Send And Receive At Layer2 | ${packets} | timeout=${10} | return_send=${True} | return_answer=${True} |
| Log Packets | ${answered[0][0]} |
| Log Packets | ${answered[0][1]} |
| Log Packets | ${unanswered[0]} |
'''
an, unan = scapylib.srp(packet, *args, **kwargs)
answered = scapylib.plist.PacketList(name='Answered')
returnAnswer = True
if return_answer and return_send:
answered = an
elif (not return_answer) and return_send:
for _an in an:
answered.append(_an[0])
elif return_answer and (not return_send):
for _an in an:
answered.append(_an[1])
else:
returnAnswer = False
if returnAnswer and return_unanswer:
return answered, unan
elif returnAnswer and (not return_unanswer):
return answered
elif (not returnAnswer) and return_unanswer:
return unan | /robotframework-ScapyLibrary-0.1.3.zip/robotframework-ScapyLibrary-0.1.3/src/ScapyLibrary/keywords/sendrecv.py | 0.555918 | 0.222996 | sendrecv.py | pypi |
KEYWORDS = {'openApplication': {'arg': ['path'], 'doc': 'Open application\n To open app with parameters, refer:\n https://sikulix-2014.readthedocs.io/en/latest/appclass.html#App.App'}, 'closeApplication': {'arg': ['name'], 'doc': 'Close application'}, 'captureRegion': {'arg': ['cooridnates'], 'doc': 'Capture region\n\n\nCapture region passed\nExamples:\n| ${screenshotname}= | Capture region | [x, y, w, h] |'}, 'changeScreenId': {'arg': ['screenId'], 'doc': 'Change screen id\n For multi display, user could use this keyword to switch to the correct screen\n\n Examples:\n | Change screen id | 1 |'}, 'clickIn': {'arg': ['areaImage', 'targetImage'], 'doc': 'Click in. \nClick target image in area image.'}, 'selectRegion': {'arg': ['message'], 'doc': 'Select Region\n\n Allow user to select a region and capture it.\n Return array of [capturedImagePath, x, y, w, h]\n\n Examples:\n | @{SelectedRegion}= | Select region |'}, 'setRoi': {'arg': ['cooridnates', 'timeout=0'], 'doc': 'Set ROI\n\n Set region of interest on screen\n Optionally pass highlight timeout.\n\n Examples:\n | Set ROI | [x, y, w, h] |\n | Set ROI | [x, y, w, h] | 2 |'}, 'highlightRoi': {'arg': ['timeout'], 'doc': 'Highlight ROI'}, 'mouseDown': {'arg': ['*mouseButtons'], 'doc': 'Mouse down\n Press and hold the specified buttons\n\n @mouseButtons: Could be LEFT, MIDDLE, RIGHT\n\n Examples:\n | Mouse Move | test.png | \n | Mouse Down | LEFT | RIGHT |\n | Mouse Up |'}, 'getExtendedRegionFrom': {'arg': ['image', 'direction', 'number_of_times_to_repeat'], 'doc': 'Get extended region from\n Extended the given image creating a region above or below with the same width\n The height can change using the multiplier @number_of_times_to_repeat, if 2 is given the new region will have twice the height of the orignalge '}, 'getNumberOfScreens': {'arg': [], 'doc': 'Get number of screens'}, 'addImagePath': {'arg': ['path'], 'doc': 'Add image path'}, 'wheelDown': {'arg': ['steps', 'image='], 'doc': 'Wheel down\n Move mouse to the target, and wheel down with give steps\n\n Examples:\n | Wheel Down | 5 | \n | Wheel Down | 5 | test.png |'}, 'getScreenCoordinates': {'arg': [], 'doc': 'Get screen coordinates\n\nReturn screen coordinates for active screen\n\nExamples:\n| @{coordinates}= | Get Screen Coordinates | 0 |'}, 'getCurrentScreenId': {'arg': [], 'doc': 'Get current screen id'}, 'clearAllHighlights': {'arg': [], 'doc': 'Clear all highlights from screen'}, 'waitForImage': {'arg': ['wantedImage', 'notWantedImage', 'timeout'], 'doc': 'Wait For Image\n\n Check wantedImage exist. If notWantedImage appear or timeout happened, throw exception\n\n @wantedImage: expected image in screen\n\n @notWantedImage: unexpected image in screen\n\n @timeout: wait seconds\n\n Examples:\n | Wait For Image | wanted.png | notWanted.png | 5 |'}, 'getText': {'arg': ['image='], 'doc': 'Get text\n\n If image is not given, keyword will get text from whole Screen\n If image is given, keyword will get text from matched region\n Call keyword setOcrTextRead to set OcrTextRead as true, before using text recognition keywords\n\n Examples:\n | Set Ocr Text Read | true |\n | Get Text |\n | Get Text | test.png |'}, 'waitUntilScreenContain': {'arg': ['image', 'timeout'], 'doc': 'Wait until screen contain\n Wait until image shown in screen'}, 'inputText': {'arg': ['image', 'text'], 'doc': 'Input text\n Image could be empty\n\n Examples:\n | Input text | Sikuli |'}, 'doubleClickIn': {'arg': ['areaImage', 'targetImage'], 'doc': 'Double click in. \nDouble click target image in area image.'}, 'click': {'arg': ['image', 'xOffset=0', 'yOffset=0'], 'doc': 'Click\n\nClick on an image with similarity and offset.\nExamples:\n| Set Capture Matched Image | false |'}, 'captureScreen': {'arg': [], 'doc': 'Capture whole screen, file name is returned'}, 'clearHighlight': {'arg': ['image'], 'doc': 'Clear highlight from screen'}, 'doubleClick': {'arg': ['image', 'xOffset=0', 'yOffset=0'], 'doc': 'Double click'}, 'screenShouldContain': {'arg': ['image'], 'doc': 'Screen should contain'}, 'mouseUp': {'arg': ['*mouseButtons'], 'doc': 'Mouse up\n Release the specified mouse buttons\n\n @mouseButtons: Could be LEFT, MIDDLE, RIGHT. If empty, all currently held buttons are released\n\n Examples:\n | Mouse Move | test.png | \n | Mouse Down | LEFT | RIGHT |\n | Mouse Up | LEFT | RIGHT |'}, 'pasteText': {'arg': ['image', 'text'], 'doc': 'Paste text. Image could be empty'}, 'readTextFromRegion': {'arg': ['reg'], 'doc': 'Read text from region'}, 'setCaptureFolder': {'arg': ['path'], 'doc': 'Set captured folder\n\nSet folder for captured images\nExamples:\n| Set captured folder | PATH |'}, 'clickNth': {'arg': ['image', 'index', 'similarity', 'sortByColumn=true'], 'doc': 'Click nth\n\n Click on specific image.\n Optionally pass similarity and sort by column or row.\n\n Examples:\n | Click on nth image in region | image.png | 1 | 0.9 |\n | Click on nth image in region | image.png | 1 | 0.9 | ${FALSE} |'}, 'waitForMultipleImages': {'arg': ['timeout', 'pollingInterval', 'expectedImages', 'notExpectedImages'], 'doc': 'Wait For Multiple Images\n\n Check if images exists in expectedImages or notExpectedImages list. If image appears that is listed in notExpectedImages list or timeout happened, throw exception If image appears that is listed in expectedImageslist return succesfully. \n\n @timeout: wait seconds\n\n @pollingInterval: time in seconds between screen checks\n\n @expectedImages: list of expected images in screen\n\n @notExpectedImages: list of not expected images in screen\n\n Examples:\n | @{wanted_images} = | Create List | wanted_image1.png | wanted_image2.png |\n | @{not_wanted_images} = | Create List | not_wanted_image1.png | not_wanted_image2.png | not_wanted_image3.png |\n | Wait For Multiple Images | 900 | 10 | ${wanted_images} | ${not_wanted_images} |'}, 'dragAndDrop': {'arg': ['srcImage', 'targetImage'], 'doc': 'Drag the source image to target image.\nIf source image is empty, drag the last match and drop at given target'}, 'highlight': {'arg': ['image', 'secs='], 'doc': 'Highlight matched image.\n If secs is set, highlight will vanish automatically after setted seconds'}, 'highlightRegion': {'arg': ['cooridnates', 'timeout'], 'doc': 'Highlight region'}, 'typeWithModifiers': {'arg': ['text', '*modifiers'], 'doc': 'Type with modifiers\n\n Examples:\n |Type With Modifiers| A | CTRL |'}, 'pressSpecialKey': {'arg': ['keyConstant'], 'doc': 'Press special key\n Presses a special keyboard key.\n\n For a list of possible Keys view docs for org.sikuli.script.Key .\n\n Examples:\n | Double Click | textFieldWithDefaultText.png | \n | Press Special Key | DELETE | '}, 'rightClickIn': {'arg': ['areaImage', 'targetImage'], 'doc': 'Right click in. \nRight click target image in area image.'}, 'resetRoi': {'arg': [], 'doc': 'Reset ROI\n Set Region of interest to full screen\n\n Examples:\n | Reset roi |'}, 'captureRoi': {'arg': [], 'doc': 'Capture Roi'}, 'mouseMove': {'arg': ['image='], 'doc': 'Mouse moveMove the mouse pointer to the target\n\n @image: if image is empty, will move mouse to the last matched.\n\n Examples:\n | Mouse Move | test.png | \n | Screen Should Contain | test.png | \n | Mouse Move |'}, 'clickRegion': {'arg': ['cooridnates', 'waitChange=0', 'timeout=0'], 'doc': 'Click region\n\n Click on defined region cooridinates.\n Optionally Wait for specified time to ensure region has changed.\n Also, optionally set highlight\n\n Examples:\n | Click on region | [x,y,w,h] | image.png |\n | Click on region | [x,y,w,h] | image.png | 0 |\n | Click on region | [x,y,w,h] | image.png | 0 | 2 |'}, 'wheelUp': {'arg': ['steps', 'image='], 'doc': 'Wheel up\n Move mouse to the target, and wheel up with give steps\n\n Examples:\n | Wheel Up | 5 | \n | Wheel Up | 5 | test.png |'}, 'waitUntilScreenNotContain': {'arg': ['image', 'timeout'], 'doc': 'Wait until screen not contain\n Wait until image not in screen'}, 'rightClick': {'arg': ['image'], 'doc': 'Right click'}, 'setTimeout': {'arg': ['timeout'], 'doc': 'Set timeout\n\nSet Sikuli timeout(seconds)\nExamples:\n| Set timeout | 10 |'}, 'dragAndDropByOffset': {'arg': ['srcImage', 'xOffset', 'yOffset'], 'doc': 'Drag the source image to target by offset.\nIf source image is empty, drag the last match and drop at given target'}, 'screenShouldNotContain': {'arg': ['image'], 'doc': 'Screen should not contain\n Screen should not contain image\n\n Examples:\n | Screen should not contain | image.png |'}, 'exists': {'arg': ['image', 'timeout='], 'doc': 'Exists\n\n Check whether image exists in screen\n @image: expected image in screen\n @timeout: wait seconds\n\n Examples:\n | ${is_exist} | Exists | image.png | 0 |'}, 'getImageCoordinates': {'arg': ['image', 'coordinates=[]'], 'doc': 'Get Image Coordinates\n\n Return image coordinates, within region\n Examples:\n | ${imageCoordinates}= | Get Image Coordinates | image.png=0.75 |\n | ${imageCoordinates}= | Get Image Coordinates | image.png=0.75 | [x, y, w, z] |'}, 'setCaptureMatchedImage': {'arg': ['value'], 'doc': 'Set capture matched image\n\nSet capture matched images, the default value is true\nExamples:\n| Set Capture Matched Image | false |'}, 'getMatchScore': {'arg': ['image'], 'doc': 'Get match scoreTries to find the image on the screen, returns accuracy score (0-1)\n\n Examples:\n | ${score} = | Get Match Score | somethingThatMayExist.png |\n | Run Keyword if | ${score} > 0.95 | keyword1 | ELSE | keyword2 |'}, 'removeImagePath': {'arg': ['path'], 'doc': 'Remove image path'}, 'setShowActions': {'arg': ['showActions'], 'doc': 'Set show actions'}, 'setOcrTextRead': {'arg': ['ocrTextRead'], 'doc': 'OCR text read'}, 'setSlowMotionDelay': {'arg': ['delay'], 'doc': 'Set slow motion delay\n Control the duration of the visual effect (seconds).'}, 'setWaitScanRate': {'arg': ['delay'], 'doc': 'Set wait scan rate\n Specify the number of times actual search operations are performed per second while waiting for a pattern to appear or vanish.'}, 'setMoveMouseDelay': {'arg': ['delay'], 'doc': 'Set move mouse delay'}, 'setMinSimilarity': {'arg': ['minSimilarity'], 'doc': 'Set min similarity'}, 'stop_remote_server': {'arg': [], 'doc': 'Stops the remote server.\n\nThe server may be configured so that users cannot stop it.'}, 'start_sikuli_process': {'arg': ['port=None'], 'doc': '\n This keyword is used to start sikuli java process.\n If library is inited with mode "OLD", sikuli java process is started automatically.\n If library is inited with mode "NEW", this keyword should be used.\n\n :param port: port of sikuli java process, if value is None or 0, a random free port will be used\n :return: None\n '}} | /robotframework_SikuliLibrary-1.0.4-py3-none-any.whl/SikuliLibrary/keywords.py | 0.81582 | 0.376881 | keywords.py | pypi |
import array
import pyaardvark
from . import __version__
from .utils import int_any_base, list_any_input
from robot.utils.connectioncache import ConnectionCache
from robot.api import logger
class AardvarkLibrary:
"""Robot Framework test library for the Totalphase Aardvark host adapter.
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
def __init__(self, i2c_bitrate=100, spi_bitrate=100):
self._cache = ConnectionCache()
self._i2c_bitrate = i2c_bitrate
self._spi_bitrate = spi_bitrate
self._device = None
def open_aardvark_adapter(self, port_or_serial=0, alias=None):
"""Opens a new Aardvark host adapter.
The adapter to be used is identified by the port or by a serial number.
By default the port 0 is used, which is sufficient if there is only one
host adapter. If there are multiple adapters connected, you have to
provide either the port or a serial number. The serial number must be
given in the form NNNN-NNNNNN, otherwise the argument is interpreted as
the port number.
Possible already opened adapters are cached and it is possible to
switch back to them using the `Switch Aardvark Adapter` keyword. It is
possible to switch either using explicitly given `alias` or using the
index returned by this keyword. Indexing start from 1 and is reset back
to it by the `Close All Connections` keyword.
"""
port = None
serial = None
if isinstance(port_or_serial, str) and '-' in port_or_serial:
logger.info('Opening Aardvark adapter with serial %s' %
(port_or_serial,))
serial = port_or_serial
else:
port = int(port_or_serial)
logger.info('Opening Aardvark adapter on port %d' % (port,))
device = pyaardvark.open(port=port, serial_number=serial)
device.i2c_bitrate = self._i2c_bitrate
device.spi_bitrate = self._spi_bitrate
device.enable_i2c = True
device.enable_spi = True
device.spi_configure_mode(pyaardvark.SPI_MODE_3)
self._device = device
return self._cache.register(self._device, alias)
def switch_aardvark_adapter(self, index_or_alias):
"""Switches between active Aardvark host adapters using an index or
alias.
Aliases can be given to `Open Aardvark Adapter` keyword wich also
always returns the connection index.
This keyword retruns the index of previous active connection.
"""
old_index = self._cache_current_index
self._device = self._cache.switch(index_or_alias)
return old_index
def close_all_aardvark_adapters(self):
"""Closes all open Aardvark host adapters and empties the open adapters
cache.
If multiple adapters are opened, this keyword should be used in a test
or suite teardown to make sure that all adapters are closed.
After this keyword, new indexes returned by the `Open Conection`
keyword are reset to 1.
"""
self._device = self._cache.close_all()
def close_adapter(self):
"""Closes the current Aardvark host adapter.
Use `Close All Aardvark Adapters` if you want to make sure all opened
host adapters are closed.
"""
self._device.close()
def set_i2c_bitrate(self, bitrate):
"""Sets the bitrate used during I2C transfers.
The `bitrate` is given in kHz. This changes only the bitrate for the
current adapter. The default value can be set when importing the
library.
"""
self._device.i2c_bitrate(bitrate)
def set_spi_bitrate(self, bitrate):
"""Sets the bitrate used during SPI transfers.
The `bitrate` is given in kHz. This changes only the bitrate for the
current adapter. The default value can be set when importing the
library.
"""
self._device.spi_bitrate(bitrate)
def enable_i2c_pullups(self, enable=True):
"""Enable (or disable) the I2C pullup resistors."""
if enable:
logger.info('Enabling I2C pullup resistors.')
else:
logger.info('Disabling I2C pullup resistors.')
self._device.i2c_pullups = enable
def enable_traget_power(self, enable=True):
"""Enable (or disable) the target power."""
if enable:
logger.info('Enabling target power.')
else:
logger.info('Disabling target power.')
self._device.target_power = enable
def i2c_master_read(self, address, length=1):
"""Perform an I2C master read access.
Read `length` bytes from a slave device with the address given in the
`address` argument.
"""
address = int_any_base(address)
length = int_any_base(length)
data = self._device.i2c_master_read(address, length)
data = array.array('B', data)
logger.info('Read %d bytes from %02xh: %s',
length, address, ' '.join('%02x' % d for d in data))
return data
def i2c_master_write(self, address, *data):
"""Perform an I2C master write access.
Writes the given `data` to a slave device with address given in the
`address` argument. The `data` argument can either be list of bytes, a
whitespace separated list of bytes or a single byte. See the examples
below.
Both the `address` and `data` can be given either as strings or
integers. Strings are parsed accoding to their prefix. Eg. `0x`
denotes a hexadecimal number.
Examples:
| I2C Master Write | 0xa4 | 0x10 |
| I2C Master Write | 0xa4 | 0x10 0x12 0x13 |
| I2C Master Write | 0xa4 | 0x10 | 0x12 | 0x13 |
"""
address = int_any_base(address)
if len(data) == 1:
data = list_any_input(data[0])
else:
data = [int_any_base(c) for c in data]
logger.info('Writing %d bytes to %02xh: %s' %
(len(data), address, ' '.join('%02x' % d for d in data)))
self._device.i2c_master_write(address, data)
def i2c_master_write_read(self, address, length, *data):
"""Perform an I2C master write read access.
First write the given `data` to a slave device, then read `length`
bytes from it. For more information see the `I2C Master Read` and `I2C
Master Write` keywords.
Examples:
| I2C Master Write Read | 0xa4 | 1 | 0x10 |
| I2C Master Write Read | 0xa4 | 1 | 0x10 0x12 0x13 |
| I2C Master Write Read | 0xa4 | 1 | 0x10 | 0x12 | 0x13 |
"""
address = int_any_base(address)
length = int_any_base(length)
if len(data) == 1:
data = list_any_input(data[0])
else:
data = [int_any_base(c) for c in data]
logger.info('Writing %d bytes to %02xh: %s' %
(len(data), address, ' '.join('%02x' % d for d in data)))
data = self._device.i2c_master_write_read(address, data, length)
data = array.array('B', data)
logger.info('Read %d bytes from %02xh: %s' %
(length, address, ' '.join('%02x' % d for d in data)))
return data
def spi_transfer(self, *data):
"""Performs a SPI access.
Writes a stream of bytes (given in `data`) on the SPI interface while
reading back the same amount of bytes. The read back has the same
length as the input data. If you want to read more data than writing on
the bus you have to send dummy bytes.
Examples:
| SPI Write | 0x10 |
| SPI Write | 0x10 0x12 0x13 |
| SPI Write | 0x10 | 0x12 | 0x13 |
| ${ret}= | SPI Write | 0x10 | 0x12 | 0x13 | # ${ret} is an array of 3 bytes |
"""
if len(data) == 1:
data = list_any_input(data[0])
else:
data = [int_any_base(c) for c in data]
logger.info('Writing %d bytes: %s' %
(len(data), ' '.join('%02x' % d for d in data)))
data = ''.join('%c' % chr(c) for c in data)
data = self._device.spi_write(data)
data = array.array('B', data)
logger.info('Read %d bytes: %s' %
(len(data), ' '.join('%02x' % d for d in data)))
return data | /robotframework_aardvarklibrary-0.2.1-py3-none-any.whl/AardvarkLibrary/library.py | 0.773216 | 0.2627 | library.py | pypi |
from os.path import join as path_join, normpath
from platform import platform
from typing import Iterator, Union
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.OperatingSystem import OperatingSystem
from robot.running.context import EXECUTION_CONTEXTS
class AdvancedLogging(object):
"""
Creating additional logs when testing.
If during the test you want to add any additional information in the file, then this library
provide a hierarchy of folders and files for logging.
Folder hierarchy is created as follows: output_dir/test_log_folder_name/Test_Suite/Test_Suite/Test_Case/file.log
Log files and folders are not removed before the test, and overwritten of new files.
== Dependency: ==
| robot framework | http://robotframework.org |
-------
When initializing the library, you can define two optional arguments
| *Argument Name* | *Default value* | *Description* |
| output_dir | ${OUTPUT_DIR} | The directory in which create the folder with additional logs |
| test_log_folder_name | Advanced_Logs | Name of the folder from which to build a hierarchy of logs |
-------
== Example: ==
| *Settings* | *Value* | *Value* | *Value* |
| Library | AdvancedLogging | C:/Temp | LogFromServer |
| Library | SSHLibrary | | |
| *Test cases* | *Action* | *Argument* | *Argument* |
| Example_TestCase | ${out}= | Execute Command | grep error output.log |
| | Write advanced testlog | error.log | ${out} |
=>\n
File C:/Temp/LogFromServer/TestSuite name/Example_TestCase/error.log with content from variable ${out}
"""
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, output_dir: str = None, test_log_folder_name: str = 'Advanced_Logs') -> None:
""" Initialisation
*Args*:\n
_output_dir_: output directory.\n
_test_log_folder_name_: name for log folder.
"""
self.os = OperatingSystem()
self.bi = BuiltIn()
self.output_dir = output_dir
self.test_log_folder_name = test_log_folder_name
self.win_platform = 'Windows' in platform()
def _get_suite_names(self) -> Iterator[str]:
"""
Get List with the current suite name and all its parents names
*Returns:*\n
Iterator of the current suite name and all its parents names
"""
suite = EXECUTION_CONTEXTS.current.suite
result = [suite.name]
while suite.parent:
suite = suite.parent
result.append(suite.name)
return reversed(result)
@property
def _suite_folder(self) -> str:
""" Define variables that are initialized by a call 'TestSuite'
*Returns:*\n
Path to suite folder.
"""
output = self.output_dir
if output is None:
output = self.bi.get_variable_value('${OUTPUT_DIR}')
suite_name = path_join(*self._get_suite_names())
if self.win_platform:
# Look at MSDN knowledge base: https://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
long_path_support_prefix = '\\\\?\\'
output = long_path_support_prefix + output
suite_folder = path_join(output, self.test_log_folder_name, suite_name)
return normpath(suite_folder)
def write_advanced_testlog(self, filename: str, content: Union[bytes, str], content_encoding: str = 'UTF-8') -> str:
""" Inclusion content in additional log file
*Args:*\n
_filename_ - name of log file;
_content_ - content for logging;
_content_encoding_ - encoding of content (if it's in bytes).
*Returns:*\n
Path to filename.
*Example*:\n
| Write advanced testlog | log_for_test.log | test message |
=>\n
File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/<TestCase name>/log_for_test.log with content 'test message'
"""
if isinstance(content, bytes):
content = content.decode(content_encoding)
test_name = self.bi.get_variable_value('${TEST_NAME}', default='')
log_file_path = path_join(self._suite_folder, test_name, filename)
self.os.create_file(log_file_path, content)
return normpath(log_file_path)
def create_advanced_logdir(self) -> str:
""" Creating a folder hierarchy for TestSuite
*Returns:*\n
Path to folder.
*Example*:\n
| *Settings* | *Value* |
| Library | AdvancedLogging |
| Library | OperatingSystem |
| *Test Cases* | *Action* | *Argument* |
| ${ADV_LOGS_DIR}= | Create advanced logdir | |
| Create file | ${ADV_LOGS_DIR}/log_for_suite.log | test message |
=>\n
File ${OUTPUT_DIR}/Advanced_Logs/<TestSuite name>/log_for_suite.log with content 'test message'
"""
test_name = self.bi.get_variable_value('${TEST_NAME}', default='')
log_folder = path_join(self._suite_folder, test_name)
old_log_level = BuiltIn().set_log_level("ERROR")
self.os.create_directory(log_folder)
BuiltIn().set_log_level(old_log_level)
return normpath(log_folder) | /robotframework-advancedlogging-2.0.0.tar.gz/robotframework-advancedlogging-2.0.0/src/AdvancedLogging.py | 0.773002 | 0.429788 | AdvancedLogging.py | pypi |
from lxml import objectify
from namedlist import namedlist
from .utils import unicode_helper
def make_element(name, namespace):
return getattr(objectify.ElementMaker(annotate=False, namespace=namespace,), name)
class Rule(object):
_check = None
def if_(self, check):
self._check = check
return self
def check(self, data):
if self._check:
return self._check(data)
else:
return True
class Ignored(Rule):
def if_(self, check):
return False
class Element(Rule):
def __init__(self, name='', namespace=''):
self.name = name
self.namespace = namespace
def value(self, name, data):
return make_element(self.name or name, self.namespace)(unicode_helper(data))
class Attribute(Rule):
def value(self, name, data):
return unicode_helper(data)
class Nested(Rule):
def value(self, name, data):
return data.toxml()
class Many(Rule):
def __init__(self, rule, name='', namespace=''):
self.rule = rule
self.name = name
self.namespace = namespace
def value(self, name, data):
return [self.rule.value(name, x) for x in data]
class WrappedMany(Many):
def value(self, name, data):
values = super(WrappedMany, self).value(name, data)
return make_element(self.name or name, self.namespace)(*values)
def xmlfied(el_name, namespace='', fields=[], **kw):
items = fields + list(kw.items())
class Listener(namedlist('XMLFied', [(item[0], None) for item in items])):
def toxml(self):
el = make_element(el_name, namespace)
def entries(cl):
return [(name, rule.value(name, getattr(self, name)))
for (name, rule) in items
if isinstance(rule, cl) and rule.check(getattr(self, name))]
elements = entries(Element)
attributes = entries(Attribute)
nested = entries(Nested)
manys = sum([[(m[0], v) for v in m[1]] for m in entries(Many)], [])
return el(*([element for (_, element) in elements + nested + manys]),
**dict(attributes))
return Listener | /robotframework-allurereport-zajic-1.3.1.tar.gz/robotframework-allurereport-zajic-1.3.1/AllureReportLibrary/rules.py | 0.597138 | 0.299464 | rules.py | pypi |
r"""killableprocess - Subprocesses which can be reliably killed
This module is a subclass of the builtin "subprocess" module. It allows
processes that launch subprocesses to be reliably killed on Windows (via the Popen.kill() method.
It also adds a timeout argument to Wait() for a limited period of time before
forcefully killing the process.
Note: On Windows, this module requires Windows 2000 or higher (no support for
Windows 95, 98, or NT 4.0). It also requires ctypes, which is bundled with
Python 2.5+ or available from http://python.net/crew/theller/ctypes/
"""
import subprocess
import sys
import os
import time
import types
try:
from subprocess import CalledProcessError
except ImportError:
# Python 2.4 doesn't implement CalledProcessError
class CalledProcessError(Exception):
"""This exception is raised when a process run by check_call() returns
a non-zero exit status. The exit status will be stored in the
returncode attribute."""
def __init__(self, returncode, cmd):
self.returncode = returncode
self.cmd = cmd
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
mswindows = (sys.platform == "win32")
if mswindows:
import winprocess
else:
import signal
def call(*args, **kwargs):
waitargs = {}
if "timeout" in kwargs:
waitargs["timeout"] = kwargs.pop("timeout")
return Popen(*args, **kwargs).wait(**waitargs)
def check_call(*args, **kwargs):
"""Call a program with an optional timeout. If the program has a non-zero
exit status, raises a CalledProcessError."""
retcode = call(*args, **kwargs)
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = args[0]
raise CalledProcessError(retcode, cmd)
if not mswindows:
def DoNothing(*args):
pass
class Popen(subprocess.Popen):
if not mswindows:
# Override __init__ to set a preexec_fn
def __init__(self, *args, **kwargs):
if len(args) >= 7:
raise Exception("Arguments preexec_fn and after must be passed by keyword.")
real_preexec_fn = kwargs.pop("preexec_fn", None)
def setpgid_preexec_fn():
os.setpgid(0, 0)
if real_preexec_fn:
apply(real_preexec_fn)
kwargs['preexec_fn'] = setpgid_preexec_fn
subprocess.Popen.__init__(self, *args, **kwargs)
if mswindows:
def _execute_child(self, args, executable, preexec_fn, close_fds,
cwd, env, universal_newlines, startupinfo,
creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
if not isinstance(args, types.StringTypes):
args = subprocess.list2cmdline(args)
if startupinfo is None:
startupinfo = winprocess.STARTUPINFO()
if None not in (p2cread, c2pwrite, errwrite):
startupinfo.dwFlags |= winprocess.STARTF_USESTDHANDLES
startupinfo.hStdInput = int(p2cread)
startupinfo.hStdOutput = int(c2pwrite)
startupinfo.hStdError = int(errwrite)
if shell:
startupinfo.dwFlags |= winprocess.STARTF_USESHOWWINDOW
comspec = os.environ.get("COMSPEC", "cmd.exe")
args = comspec + " /c " + args
# We create a new job for this process, so that we can kill
# the process and any sub-processes
self._job = winprocess.CreateJobObject()
creationflags |= winprocess.CREATE_SUSPENDED
creationflags |= winprocess.CREATE_UNICODE_ENVIRONMENT
hp, ht, pid, tid = winprocess.CreateProcess(
executable, args,
None, None, # No special security
1, # Must inherit handles!
creationflags,
winprocess.EnvironmentBlock(env),
cwd, startupinfo)
self._child_created = True
self._handle = hp
self._thread = ht
self.pid = pid
winprocess.AssignProcessToJobObject(self._job, hp)
winprocess.ResumeThread(ht)
if p2cread is not None:
p2cread.Close()
if c2pwrite is not None:
c2pwrite.Close()
if errwrite is not None:
errwrite.Close()
def kill(self, group=True):
"""Kill the process. If group=True, all sub-processes will also be killed."""
if mswindows:
if group:
winprocess.TerminateJobObject(self._job, 127)
else:
winprocess.TerminateProcess(self._handle, 127)
self.returncode = 127
else:
if group:
os.killpg(self.pid, signal.SIGKILL)
else:
os.kill(self.pid, signal.SIGKILL)
self.returncode = -9
def wait(self, timeout=-1, group=True):
"""Wait for the process to terminate. Returns returncode attribute.
If timeout seconds are reached and the process has not terminated,
it will be forcefully killed. If timeout is -1, wait will not
time out."""
if self.returncode is not None:
return self.returncode
if mswindows:
if timeout != -1:
timeout = timeout * 1000
rc = winprocess.WaitForSingleObject(self._handle, timeout)
if rc == winprocess.WAIT_TIMEOUT:
self.kill(group)
else:
self.returncode = winprocess.GetExitCodeProcess(self._handle)
else:
if timeout == -1:
subprocess.Popen.wait(self)
return self.returncode
starttime = time.time()
# Make sure there is a signal handler for SIGCHLD installed
oldsignal = signal.signal(signal.SIGCHLD, DoNothing)
while time.time() < starttime + timeout - 0.01:
pid, sts = os.waitpid(self.pid, os.WNOHANG)
if pid != 0:
self._handle_exitstatus(sts)
signal.signal(signal.SIGCHLD, oldsignal)
return self.returncode
# time.sleep is interrupted by signals (good!)
newtimeout = timeout - time.time() + starttime
time.sleep(newtimeout)
self.kill(group)
signal.signal(signal.SIGCHLD, oldsignal)
subprocess.Popen.wait(self)
return self.returncode | /robotframework-androidlibrary-0.2.0.tar.gz/robotframework-androidlibrary-0.2.0/src/AndroidLibrary/killableprocess.py | 0.518302 | 0.233018 | killableprocess.py | pypi |
from base import *
import os
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
execfile(os.path.join(THIS_DIR, 'version.py'))
__version__ = VERSION
class AnywhereLibrary(
Element,
Util,
Logging,
RunOnFailure,
Screenshot,
Waiting,
JavaScript,
):
"""AnywhereLibrary is a cross platform(desktop browser,android,ios) testing library for Robot Framework.
It uses the Selenium 2 (WebDriver) libraries internally to control a web browser.
See http://seleniumhq.org/docs/03_webdriver.html for more information on Selenium 2
and WebDriver.
It uses appium as mobile test automation framework for use with native and hybrid app.
See http://appium.io/.
Best practice for using this library is for SPA(single page application) with design pattern which means you only need a set of scripts to cover all platform.
*Before running tests*
Prior to running test cases using AnywhereLibrary, AnywhereLibrary must be
imported into your Robot test suite , and the `Initial Driver` keyword must
be used to initial a driver to the desired location and `Tear Down Driver` driver after finishing executing test cases(see `initial driver`,`teardown driver` keyword).
*Locating elements*
All keywords in AnywhereLibrary that need to find an element on the page
take an argument, `locator`. AnywhereLibrary support a subset of the WebDriver locator strategies:
currently available locator strategies are using:
find by *"class"* (i.e., ui component type)
find by *"xpath"* (i.e., an abstract representation of a path to an element, with certain constraints)
Supported strategies are:
| *Strategy* | *Example* | *Description* |
| xpath | Click `|` //div[@id='my_element'] | Matches with arbitrary XPath expression |
| xpath | Click `|` xpath=//div[@id='my_element'] | Matches with arbitrary XPath expression |
| class | Click `|` class=android.widget.Button | Matches another element by their class name |
| ...... | Coming soon ...... | Coming soon..... |
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
def __init__(self,run_on_failure='Capture Page Screenshot'):
"""
| Library `|` AnywhereLibrary | # Import library into where you will use |
"""
for base in AnywhereLibrary.__bases__:
base.__init__(self)
self.register_keyword_to_run_on_failure(run_on_failure) | /robotframework-anywherelibrary-1.1.0.tar.gz/robotframework-anywherelibrary-1.1.0/src/AnywhereLibrary/__init__.py | 0.567457 | 0.264655 | __init__.py | pypi |
from robot.libraries import BuiltIn
from keywordgroup import KeywordGroup
BUILTIN = BuiltIn.BuiltIn()
class RunOnFailure(KeywordGroup):
def __init__(self):
self._run_on_failure_keyword = None
self._running_on_failure_routine = False
# Public
def register_keyword_to_run_on_failure(self, keyword):
"""Sets the keyword to execute when a AnywhereLibrary keyword fails.
*keyword_name* is the name of a keyword (from any available
libraries) that will be executed if a Selenium2Library keyword fails.
It is not possible to use a keyword that requires arguments.
Using the value "Nothing" will disable this feature altogether.
The initial keyword to use is set in `importing`, and the
keyword that is used by default is `Capture Page Screenshot`.
Taking a screenshot when something failed is a very useful
feature, but notice that it can slow down the execution.
This keyword returns the name of the previously registered
failure keyword. It can be used to restore the original
value later.
Example:
| Register Keyword To Run On Failure | Capture Page Screenshot | # Run `Capture Page Screenshot` on failure. |
| ${previous kw}= | Register Keyword To Run On Failure | Nothing | # Disables run-on-failure functionality and stores the previous kw name in a variable. |
| Register Keyword To Run On Failure | ${previous kw} | # Restore to the previous keyword. |
This run-on-failure functionality only works when running tests on Python/Jython 2.4
or newer and it does not work on IronPython at all.
"""
print keyword
old_keyword = self._run_on_failure_keyword
old_keyword_text = old_keyword if old_keyword is not None else "No keyword"
new_keyword = keyword if keyword.strip().lower() != "nothing" else None
new_keyword_text = new_keyword if new_keyword is not None else "No keyword"
self._run_on_failure_keyword = new_keyword
self._info('%s will be run on failure.' % new_keyword_text)
return old_keyword_text
# Private
def _run_on_failure(self):
if self._run_on_failure_keyword is None:
return
if self._running_on_failure_routine:
return
self._running_on_failure_routine = True
try:
BUILTIN.run_keyword(self._run_on_failure_keyword)
except Exception, err:
self._run_on_failure_error(err)
finally:
self._running_on_failure_routine = False
def _run_on_failure_error(self, err):
err = "Keyword '%s' could not be run on failure: %s" % (self._run_on_failure_keyword, err)
if hasattr(self, '_warn'):
self._warn(err)
return
raise Exception(err) | /robotframework-anywherelibrary-1.1.0.tar.gz/robotframework-anywherelibrary-1.1.0/src/AnywhereLibrary/base/runonfailure.py | 0.788461 | 0.188828 | runonfailure.py | pypi |
from util import Util
from keywordgroup import KeywordGroup
from elementfinder import ElementFinder
class Element(KeywordGroup):
def __init__(self):
self._element_finder=ElementFinder()
# Public
def element_find(self,locator,requireRaise=True):
""" General function to find single element, it will return this element.
If it matchs more than one element, it will return the first one.
*requireRaise* argument normally is not required.
Example:
| ${Element}= | Element Find | ${element_locator} |
"""
element=self._element_finder.find(locator)
if not requireRaise and len(element)==0:
return None
if requireRaise and len(element)==0:
raise ValueError("Element locator '%s' did not match any element."%locator)
return element[0]
def click(self,locator):
""" General click function which can be used for all platforms' elements.
Example:
| click | ${element_locator} |
"""
self._info("Clicking element '%s'." %locator)
self.wait_for_element_present(locator,10)
element=self.element_find(locator)
element.click()
if Util.captureScreenShot=="True":
self.capture_page_screenshot()
def type(self,locator,text):
"""General function for typing the given text into text field control.
*text* argument specifies the text which you want to input.
Example:
| type | ${element_locator} | ${Text} |
"""
self._info("Typing text '%s' into text field '%s'" % (text, locator))
self.wait_for_element_present(locator,10)
self._input_text_into_text_field(locator, text)
if Util.captureScreenShot=="True":
self.capture_page_screenshot()
def is_element_present(self,locator):
"""Return true or false if element presents in current page.
"""
return (self.element_find(locator,False) != None)
def page_should_contain_element(self,locator):
"""Verifies that current page contains element.
"""
if self.is_element_present(locator):
self._info('Current page contains element with locator %s'%locator)
else:
self._warn('Current page should not contain element with locator %s'%locator)
def page_should_not_contain_element(self,locator):
"""Verifies that current page should not contain element.
"""
if not self.is_element_present(locator):
self._info('Current page should not contain element with locator %s'%locator)
else:
self._warn('Current page contains element with locator %s'%locator)
def get_matching_element_count(self, locator):
"""Returns number of elements matching `locator`
"""
if self._element_finder.find(locator) is None:
count=0
else:
count = len(self._element_finder.find(locator))
return str(count)
def get_text(self,locator):
"""Returns the text value of element identified by `locator`.
"""
return self._get_text(locator)
def get_value(self,locator):
"""Returns the value attribute of element identified by `locator`.
"""
return self._get_value(locator)
def verify_text(self,locator,expectedText):
"""Compare the expectedText given to the actualText which get from the element.
*expectedText* argument specifies the expectedtext you want.
Example:
| Verify text | ${element_locator} | ${text} |
"""
try:
actualText=self._get_text(locator)
assert actualText==expectedText
self._info('Compare actual text(%s) with expected text(%s) passed'%(actualText,expectedText))
except AssertionError:
self._warn('Compare actual text(%s) with expected text(%s) failed'%(actualText,expectedText))
def verify_value(self,locator,expectedValue):
"""Compare the expectedValue given to the actualValue which get from the element
*expectedValue* argument specifies the expectedValue you want.
Example:
| Verify value | ${element_locator} | ${value} |
"""
try:
actualValue=self._get_value(locator)
assert actualValue==expectedValue
self._info('Compare actual value(%s) with expected value(%s) passed'%(actualValue,expectedValue))
except AssertionError:
self._warn('Compare actual value(%s) with expected value(%s) failed'%(actualValue,expectedValue))
def ie_certificate_error_handler(self):
Util.driver.get(('javascript:document.getElementById("overridelink").click()'))
# Private
def _input_text_into_text_field(self, locator, text):
element = self.element_find(locator)
element.send_keys(text)
def _get_text(self,locator):
element=self.element_find(locator)
return (element.text).strip()
def _get_value(self,locator):
element=self.element_find(locator)
return (element.get_attribute("value")).strip() | /robotframework-anywherelibrary-1.1.0.tar.gz/robotframework-anywherelibrary-1.1.0/src/AnywhereLibrary/base/element.py | 0.652574 | 0.24801 | element.py | pypi |
import os
from AppiumLibrary.keywords import *
from AppiumLibrary.version import VERSION
__version__ = VERSION
class AppiumLibrary(
_LoggingKeywords,
_RunOnFailureKeywords,
_ElementKeywords,
_ScreenshotKeywords,
_ApplicationManagementKeywords,
_WaitingKeywords,
_TouchKeywords,
_KeyeventKeywords,
_AndroidUtilsKeywords,
_ScreenrecordKeywords
):
"""AppiumLibrary is a Mobile App testing library for Robot Framework.
= Locating or specifying elements =
All keywords in AppiumLibrary that need to find an element on the page
take an argument, either a ``locator`` or a ``webelement``. ``locator``
is a string that describes how to locate an element using a syntax
specifying different location strategies. ``webelement`` is a variable that
holds a WebElement instance, which is a representation of the element.
== Using locators ==
By default, when a locator is provided, it is matched against the key attributes
of the particular element type. For iOS and Android, key attribute is ``id`` for
all elements and locating elements is easy using just the ``id``. For example:
| Click Element id=my_element
New in AppiumLibrary 1.4, ``id`` and ``xpath`` are not required to be specified,
however ``xpath`` should start with ``//`` else just use ``xpath`` locator as explained below.
For example:
| Click Element my_element
| Wait Until Page Contains Element //*[@type="android.widget.EditText"]
Appium additionally supports some of the [https://w3c.github.io/webdriver/webdriver-spec.html|Mobile JSON Wire Protocol] locator strategies.
It is also possible to specify the approach AppiumLibrary should take
to find an element by specifying a lookup strategy with a locator
prefix. Supported strategies are:
| *Strategy* | *Example* | *Description* | *Note* |
| identifier | Click Element `|` identifier=my_element | Matches by @id attribute | |
| id | Click Element `|` id=my_element | Matches by @resource-id attribute | |
| accessibility_id | Click Element `|` accessibility_id=button3 | Accessibility options utilize. | |
| xpath | Click Element `|` xpath=//UIATableView/UIATableCell/UIAButton | Matches with arbitrary XPath | |
| class | Click Element `|` class=UIAPickerWheel | Matches by class | |
| android | Click Element `|` android=UiSelector().description('Apps') | Matches by Android UI Automator | |
| ios | Click Element `|` ios=.buttons().withName('Apps') | Matches by iOS UI Automation | |
| nsp | Click Element `|` nsp=name=="login" | Matches by iOSNsPredicate | Check PR: #196 |
| chain | Click Element `|` chain=XCUIElementTypeWindow[1]/* | Matches by iOS Class Chain | |
| css | Click Element `|` css=.green_button | Matches by css in webview | |
| name | Click Element `|` name=my_element | Matches by @name attribute | *Only valid* for Selendroid |
== Using webelements ==
Starting with version 1.4 of the AppiumLibrary, one can pass an argument
that contains a WebElement instead of a string locator. To get a WebElement,
use the new `Get WebElements` or `Get WebElement` keyword.
For example:
| @{elements} Get Webelements class=UIAButton
| Click Element @{elements}[2]
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
def __init__(self, timeout=5, run_on_failure='Capture Page Screenshot'):
"""AppiumLibrary can be imported with optional arguments.
``timeout`` is the default timeout used to wait for all waiting actions.
It can be later set with `Set Appium Timeout`.
``run_on_failure`` specifies the name of a keyword (from any available
libraries) to execute when a AppiumLibrary keyword fails.
By default `Capture Page Screenshot` will be used to take a screenshot of the current page.
Using the value `No Operation` will disable this feature altogether. See
`Register Keyword To Run On Failure` keyword for more information about this
functionality.
Examples:
| Library | AppiumLibrary | 10 | # Sets default timeout to 10 seconds |
| Library | AppiumLibrary | timeout=10 | run_on_failure=No Operation | # Sets default timeout to 10 seconds and does nothing on failure |
"""
for base in AppiumLibrary.__bases__:
base.__init__(self)
self.set_appium_timeout(timeout)
self.register_keyword_to_run_on_failure(run_on_failure) | /robotframework-appiumlibrary-2.0.0b1.tar.gz/robotframework-appiumlibrary-2.0.0b1/AppiumLibrary/__init__.py | 0.718693 | 0.395105 | __init__.py | pypi |
from appium.webdriver.common.touch_action import TouchAction
from AppiumLibrary.locators import ElementFinder
from .keywordgroup import KeywordGroup
class _TouchKeywords(KeywordGroup):
def __init__(self):
self._element_finder = ElementFinder()
# Public, element lookups
def zoom(self, locator, percent="200%", steps=1):
"""
Zooms in on an element a certain amount.
"""
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.zoom(element=element, percent=percent, steps=steps)
def pinch(self, locator, percent="200%", steps=1):
"""
Pinch in on an element a certain amount.
"""
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.pinch(element=element, percent=percent, steps=steps)
def swipe(self, start_x, start_y, offset_x, offset_y, duration=1000):
"""
Swipe from one point to another point, for an optional duration.
Args:
- start_x - x-coordinate at which to start
- start_y - y-coordinate at which to start
- offset_x - x-coordinate distance from start_x at which to stop
- offset_y - y-coordinate distance from start_y at which to stop
- duration - (optional) time to take the swipe, in ms.
Usage:
| Swipe | 500 | 100 | 100 | 0 | 1000 |
_*NOTE: *_
Android 'Swipe' is not working properly, use ``offset_x`` and ``offset_y`` as if these are destination points.
"""
x_start = int(start_x)
x_offset = int(offset_x)
y_start = int(start_y)
y_offset = int(offset_y)
driver = self._current_application()
driver.swipe(x_start, y_start, x_offset, y_offset, duration)
def swipe_by_percent(self, start_x, start_y, end_x, end_y, duration=1000):
"""
Swipe from one percent of the screen to another percent, for an optional duration.
Normal swipe fails to scale for different screen resolutions, this can be avoided using percent.
Args:
- start_x - x-percent at which to start
- start_y - y-percent at which to start
- end_x - x-percent distance from start_x at which to stop
- end_y - y-percent distance from start_y at which to stop
- duration - (optional) time to take the swipe, in ms.
Usage:
| Swipe By Percent | 90 | 50 | 10 | 50 | # Swipes screen from right to left. |
_*NOTE: *_
This also considers swipe acts different between iOS and Android.
New in AppiumLibrary 1.4.5
"""
width = self.get_window_width()
height = self.get_window_height()
x_start = float(start_x) / 100 * width
x_end = float(end_x) / 100 * width
y_start = float(start_y) / 100 * height
y_end = float(end_y) / 100 * height
x_offset = x_end - x_start
y_offset = y_end - y_start
platform = self._get_platform()
if platform == 'android':
self.swipe(x_start, y_start, x_end, y_end, duration)
else:
self.swipe(x_start, y_start, x_offset, y_offset, duration)
def scroll(self, start_locator, end_locator):
"""
Scrolls from one element to another
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
el1 = self._element_find(start_locator, True, True)
el2 = self._element_find(end_locator, True, True)
driver = self._current_application()
driver.scroll(el1, el2)
def scroll_down(self, locator):
"""Scrolls down to element"""
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.execute_script("mobile: scroll", {"direction": 'down', 'elementid': element.id})
def scroll_up(self, locator):
"""Scrolls up to element"""
driver = self._current_application()
element = self._element_find(locator, True, True)
driver.execute_script("mobile: scroll", {"direction": 'up', 'elementid': element.id})
def long_press(self, locator, duration=1000):
"""*DEPRECATED!!* Since selenium v4, use other keywords.
Long press the element with optional duration """
driver = self._current_application()
element = self._element_find(locator, True, True)
action = TouchAction(driver)
action.press(element).wait(duration).release().perform()
def tap(self, locator, x_offset=None, y_offset=None, count=1):
"""*DEPRECATED!!* Since selenium v4, use other keywords.
Tap element identified by ``locator``.
Args:
- ``locator`` - (mandatory). Taps coordinates when set to ${None}.
- ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.
- ``y_offset`` - (optional) y coordinate. If y is used, x must also be set, and vice versa
- ``count`` - can be used for multiple times of tap on that element
"""
driver = self._current_application()
el = self._element_find(locator, True, True)
action = TouchAction(driver)
action.tap(el,x_offset,y_offset, count).perform()
def tap_with_number_of_taps(self, locator, number_of_taps, number_of_touches):
""" Sends one or more taps with one or more touch points.iOS only.
Args:
- ``number_of_taps`` - The number of taps.
- ``number_of_touches`` - The number of touch points.
"""
driver = self._current_application()
element = self._element_find(locator, True, True)
params = {'element': element, 'numberOfTaps': number_of_taps, 'numberOfTouches': number_of_touches}
driver.execute_script("mobile: tapWithNumberOfTaps", params)
def click_a_point(self, x=0, y=0, duration=100):
"""*DEPRECATED!!* Since selenium v4, use other keywords.
Click on a point"""
self._info("Clicking on a point (%s,%s)." % (x,y))
driver = self._current_application()
action = TouchAction(driver)
try:
action.press(x=float(x), y=float(y)).wait(float(duration)).release().perform()
except:
assert False, "Can't click on a point at (%s,%s)" % (x,y)
def click_element_at_coordinates(self, coordinate_X, coordinate_Y):
"""*DEPRECATED!!* Since selenium v4, use other keywords.
click element at a certain coordinate """
self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y))
driver = self._current_application()
action = TouchAction(driver)
action.press(x=coordinate_X, y=coordinate_Y).release().perform() | /robotframework-appiumlibrary-2.0.0b1.tar.gz/robotframework-appiumlibrary-2.0.0b1/AppiumLibrary/keywords/_touch.py | 0.892387 | 0.409752 | _touch.py | pypi |
import base64
from .keywordgroup import KeywordGroup
from selenium.common.exceptions import TimeoutException
from kitchen.text.converters import to_bytes
class _AndroidUtilsKeywords(KeywordGroup):
# Public
def open_notifications(self):
"""Opens and expands an Android device's notification drawer.
Android only.
"""
driver = self._current_application()
driver.open_notifications()
def get_network_connection_status(self):
"""Returns an integer bitmask specifying the network connection type.
Android only.
See `set network connection status` for more details.
"""
driver = self._current_application()
return driver.network_connection
def set_network_connection_status(self, connectionStatus):
"""Sets the network connection Status.
Android only.
Possible values:
| =Value= | =Alias= | =Data= | =Wifi= | =Airplane Mode= |
| 0 | (None) | 0 | 0 | 0 |
| 1 | (Airplane Mode) | 0 | 0 | 1 |
| 2 | (Wifi only) | 0 | 1 | 0 |
| 4 | (Data only) | 1 | 0 | 0 |
| 6 | (All network on) | 1 | 1 | 0 |
"""
driver = self._current_application()
return driver.set_network_connection(int(connectionStatus))
def pull_file(self, path, decode=False):
"""Retrieves the file at `path` and return it's content.
Android only.
- _path_ - the path to the file on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._current_application()
theFile = driver.pull_file(path)
if decode:
theFile = base64.b64decode(theFile)
return str(theFile)
def pull_folder(self, path, decode=False):
"""Retrieves a folder at `path`. Returns the folder's contents zipped.
Android only.
- _path_ - the path to the folder on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._current_application()
theFolder = driver.pull_folder(path)
if decode:
theFolder = base64.b64decode(theFolder)
return theFolder
def push_file(self, path, data, encode=False):
"""Puts the data in the file specified as `path`.
Android only.
- _path_ - the path on the device
- _data_ - data to be written to the file
- _encode_ - True/False encode the data as base64 before writing it to the file (default=False)
"""
driver = self._current_application()
data = to_bytes(data)
if encode:
data = base64.b64encode(data).decode('utf-8')
driver.push_file(path, data)
def delete_file(self, path, timeout=5000, include_stderr=True):
"""Delete the file specified as `path`.
Android only.
- _path_ - the path on the device
- _timeout_ - delete command timeout
- _includeStderr_ - whether exception will be thrown if the command's
return code is not zero
"""
driver = self._current_application()
driver.execute_script('mobile: shell', {
'command': 'rm',
'args': [path],
'includeStderr': include_stderr,
'timeout': timeout
})
def get_activity(self):
"""Retrieves the current activity on the device.
Android only.
"""
driver = self._current_application()
return driver.current_activity
def start_activity(self, appPackage, appActivity, **opts):
"""Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
Android only.
- _appPackage_ - The package containing the activity to start.
- _appActivity_ - The activity to start.
- _appWaitPackage_ - Begin automation after this package starts (optional).
- _appWaitActivity_ - Begin automation after this activity starts (optional).
- _intentAction_ - Intent to start (opt_ional).
- _intentCategory_ - Intent category to start (optional).
- _intentFlags_ - Flags to send to the intent (optional).
- _optionalIntentArguments_ - Optional arguments to the intent (optional).
- _dontStopAppOnReset_ - Should the app be stopped on reset (optional)?
"""
# Almost the same code as in appium's start activity,
# just to keep the same keyword names as in open application
arguments = {
'app_wait_package': 'appWaitPackage',
'app_wait_activity': 'appWaitActivity',
'intent_action': 'intentAction',
'intent_category': 'intentCategory',
'intent_flags': 'intentFlags',
'optional_intent_arguments': 'optionalIntentArguments',
'dont_stop_app_on_reset': 'dontStopAppOnReset'
}
data = {}
for key, value in arguments.items():
if value in opts:
data[key] = opts[value]
driver = self._current_application()
driver.start_activity(app_package=appPackage, app_activity=appActivity, **data)
def wait_activity(self, activity, timeout, interval=1):
"""Wait for an activity: block until target activity presents
or time out.
Android only.
- _activity_ - target activity
- _timeout_ - max wait time, in seconds
- _interval_ - sleep interval between retries, in seconds
"""
if not activity.startswith('.'):
activity = ".%s" % activity
driver = self._current_application()
if not driver.wait_activity(activity=activity, timeout=float(timeout), interval=float(interval)):
raise TimeoutException(msg="Activity %s never presented, current activity: %s" % (activity, self.get_activity()))
def install_app(self, app_path, app_package):
""" Install App via Appium
Android only.
- app_path - path to app
- app_package - package of install app to verify
"""
driver = self._current_application()
driver.install_app(app_path)
return driver.is_app_installed(app_package)
def set_location(self, latitude, longitude, altitude=10):
""" Set location
- _latitute_
- _longitude_
- _altitude_ = 10 [optional]
Android only.
New in AppiumLibrary 1.5
"""
driver = self._current_application()
driver.set_location(latitude,longitude,altitude) | /robotframework-appiumlibrary-2.0.0b1.tar.gz/robotframework-appiumlibrary-2.0.0b1/AppiumLibrary/keywords/_android_utils.py | 0.681409 | 0.25682 | _android_utils.py | pypi |
from robot.libraries import BuiltIn
from .keywordgroup import KeywordGroup
BUILTIN = BuiltIn.BuiltIn()
class _RunOnFailureKeywords(KeywordGroup):
def __init__(self):
self._run_on_failure_keyword = None
self._running_on_failure_routine = False
# Public
def register_keyword_to_run_on_failure(self, keyword):
"""Sets the keyword to execute when a AppiumLibrary keyword fails.
`keyword_name` is the name of a keyword (from any available
libraries) that will be executed if a AppiumLibrary keyword fails.
It is not possible to use a keyword that requires arguments.
Using the value "Nothing" will disable this feature altogether.
The initial keyword to use is set in `importing`, and the
keyword that is used by default is `Capture Page Screenshot`.
Taking a screenshot when something failed is a very useful
feature, but notice that it can slow down the execution.
This keyword returns the name of the previously registered
failure keyword. It can be used to restore the original
value later.
Example:
| Register Keyword To Run On Failure | Log Source | # Run `Log Source` on failure. |
| ${previous kw}= | Register Keyword To Run On Failure | Nothing | # Disables run-on-failure functionality and stores the previous kw name in a variable. |
| Register Keyword To Run On Failure | ${previous kw} | # Restore to the previous keyword. |
This run-on-failure functionality only works when running tests on Python/Jython 2.4
or newer and it does not work on IronPython at all.
"""
old_keyword = self._run_on_failure_keyword
old_keyword_text = old_keyword if old_keyword is not None else "Nothing"
new_keyword = keyword if keyword.strip().lower() != "nothing" else None
new_keyword_text = new_keyword if new_keyword is not None else "Nothing"
self._run_on_failure_keyword = new_keyword
self._info('%s will be run on failure.' % new_keyword_text)
return old_keyword_text
# Private
def _run_on_failure(self):
if self._run_on_failure_keyword is None:
return
if self._running_on_failure_routine:
return
self._running_on_failure_routine = True
try:
BUILTIN.run_keyword(self._run_on_failure_keyword)
except Exception as err:
self._run_on_failure_error(err)
finally:
self._running_on_failure_routine = False
def _run_on_failure_error(self, err):
err = "Keyword '%s' could not be run on failure: %s" % (self._run_on_failure_keyword, err)
if hasattr(self, '_warn'):
self._warn(err)
return
raise Exception(err) | /robotframework-appiumlibrary-2.0.0b1.tar.gz/robotframework-appiumlibrary-2.0.0b1/AppiumLibrary/keywords/_runonfailure.py | 0.797517 | 0.187672 | _runonfailure.py | pypi |
import time
import robot
from .keywordgroup import KeywordGroup
class _WaitingKeywords(KeywordGroup):
def wait_until_element_is_visible(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` is visible.
Fails if `timeout` expires before the element is visible. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains
Element`, `Wait For Condition` and BuiltIn keyword `Wait Until Keyword
Succeeds`.
"""
def check_visibility():
visible = self._is_visible(locator)
if visible:
return
elif visible is None:
return error or "Element locator '%s' did not match any elements after %s" % (locator, self._format_timeout(timeout))
else:
return error or "Element '%s' was not visible in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_visibility)
def wait_until_page_contains(self, text, timeout=None, error=None):
"""Waits until `text` appears on current page.
Fails if `timeout` expires before the text appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Does Not Contain`,
`Wait Until Page Contains Element`,
`Wait Until Page Does Not Contain Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
if not error:
error = "Text '%s' did not appear in <TIMEOUT>" % text
self._wait_until(timeout, error, self._is_text_present, text)
def wait_until_page_does_not_contain(self, text, timeout=None, error=None):
"""Waits until `text` disappears from current page.
Fails if `timeout` expires before the `text` disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Contains Element`,
`Wait Until Page Does Not Contain Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
def check_present():
present = self._is_text_present(text)
if not present:
return
else:
return error or "Text '%s' did not disappear in %s" % (text, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present)
def wait_until_page_contains_element(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` appears on current page.
Fails if `timeout` expires before the element appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Does Not Contain`
`Wait Until Page Does Not Contain Element`
and BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
if not error:
error = "Element '%s' did not appear in <TIMEOUT>" % locator
self._wait_until(timeout, error, self._is_element_present, locator)
def wait_until_page_does_not_contain_element(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` disappears from current page.
Fails if `timeout` expires before the element disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Does Not Contain`,
`Wait Until Page Contains Element` and
BuiltIn keyword `Wait Until Keyword Succeeds`.
"""
def check_present():
present = self._is_element_present(locator)
if not present:
return
else:
return error or "Element '%s' did not disappear in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present)
# Private
def _wait_until(self, timeout, error, function, *args):
error = error.replace('<TIMEOUT>', self._format_timeout(timeout))
def wait_func():
return None if function(*args) else error
self._wait_until_no_error(timeout, wait_func)
def _wait_until_no_error(self, timeout, wait_func, *args):
timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
maxtime = time.time() + timeout
while True:
timeout_error = wait_func(*args)
if not timeout_error:
return
if time.time() > maxtime:
self.log_source()
raise AssertionError(timeout_error)
time.sleep(0.2)
def _format_timeout(self, timeout):
timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
return robot.utils.secs_to_timestr(timeout) | /robotframework-appiumlibrary-2.0.0b1.tar.gz/robotframework-appiumlibrary-2.0.0b1/AppiumLibrary/keywords/_waiting.py | 0.742702 | 0.187411 | _waiting.py | pypi |
import importlib
from AppiumLibrary import AppiumLibrary
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
try:
AppiumCommon = importlib.import_module('Helpers.AppiumCommon', package='Helpers')
except ModuleNotFoundError:
AppiumCommon = importlib.import_module('.Helpers.AppiumCommon', package='ApplicationLibrary')
appLib = BuiltIn()
class MobileLibrary(AppiumLibrary):
"""ApplicationLibrary Mobile Library
This class is the base Library used to generate automated Mobile Tests in the Robot Automation Framework using
Appium. This Library uses and extends the robotframework-appiumlibrary.
= Locating or Specifying Elements =
All keywords in MobileLibrary that need to find an element on the page take an argument, either a
``locator`` or a ``webelement``. ``locator`` is a string that describes how to locate an element using a syntax
specifying different location strategies. ``webelement`` is a variable that
holds a WebElement instance, which is a representation of the element.
== Using locators ==
By default, when a locator is provided, it is matched against the key attributes
of the particular element type. For iOS and Android, key attribute is ``id`` for
all elements and locating elements is easy using just the ``id``. For example:
| Click Element id=my_element
``id`` and ``xpath`` are not required to be specified,
however ``xpath`` should start with ``//`` else just use ``xpath`` locator as explained below.
For example:
| Click Element my_element
| Wait Until Page Contains Element //*[@type="android.widget.EditText"]
Appium additionally supports some of the [https://w3c.github.io/webdriver/webdriver-spec.html|Mobile JSON Wire Protocol] locator strategies.
It is also possible to specify the approach MobileLibrary should take
to find an element by specifying a lookup strategy with a locator
prefix. Supported strategies are:
| *Strategy* | *Example* | *Description* | *Note* |
| identifier | Click Element `|` identifier=my_element | Matches by @id attribute | |
| id | Click Element `|` id=my_element | Matches by @resource-id attribute | |
| accessibility_id | Click Element `|` accessibility_id=button3 | Accessibility options utilize. | |
| xpath | Click Element `|` xpath=//UIATableView/UIATableCell/UIAButton | Matches with arbitrary XPath | |
| class | Click Element `|` class=UIAPickerWheel | Matches by class | |
| android | Click Element `|` android=UiSelector().description('Apps') | Matches by Android UI Automator | |
| ios | Click Element `|` ios=.buttons().withName('Apps') | Matches by iOS UI Automation | |
| nsp | Click Element `|` nsp=name=="login" | Matches by iOSNsPredicate | |
| css | Click Element `|` css=.green_button | Matches by css in webview | |
| name | Click Element `|` name=my_element | Matches by @name attribute | *Only valid* for Selendroid |
== Using webelements ==
One can pass an argument that contains a WebElement instead of a string locator.
To get a WebElement, use the new `Get WebElements` or `Get WebElement` keyword.
For example:
| @{elements} Get Webelements class=UIAButton
| Click Element @{elements}[2]
"""
def __init__(self, timeout=5, run_on_failure='Save Appium Screenshot'):
"""MobileLibrary can be imported with optional arguments.
``timeout`` is the default timeout used to wait for all waiting actions.
It can be later set with `Set Appium Timeout`.
``run_on_failure`` specifies the name of a keyword (from any available
libraries) to execute when a MobileLibrary keyword fails.
By default `Save Appium Screenshot` will be used to take a screenshot of the current page.
Using the value `No Operation` will disable this feature altogether. See
`Register Keyword To Run On Failure` keyword for more information about this
functionality.
Examples:
| Library | MobileLibrary | 10 | # Sets default timeout to 10 seconds |
| Library | MobileLibrary | timeout=10 | run_on_failure=No Operation | # Sets default timeout to 10 seconds and does nothing on failure |
"""
super().__init__(timeout, run_on_failure)
@keyword("Wait For And Clear Text")
def wait_for_and_clear_text(self, locator, timeout=None, error=None):
"""Wait for and then clear the text field identified by ``locator``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.clear_text(locator)
@keyword("Wait For And Click Element")
def wait_for_and_click_element(self, locator, timeout=None, error=None):
"""Wait for and click the element identified by ``locator``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.click_element(locator)
@keyword("Wait For And Click Text")
def wait_for_and_click_text(self, text, exact_match=False, timeout=None, error=None):
"""Wait for and click text identified by ``text``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
By default tries to click first text involves given ``text``. If you would
like to click exactly matching text, then set ``exact_match`` to `True`."""
self._wait_until_page_contains(text, timeout, error)
self.click_text(text, exact_match)
@keyword("Wait For And Click Button")
def wait_for_and_click_button(self, locator, timeout=None, error=None):
"""Wait for and click the button identified by ``locator``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.click_button(locator)
@keyword("Wait For And Input Password")
def wait_for_and_input_password(self, locator, text, timeout=None, error=None):
"""Wait for and type the given password into the text field identified by ``locator``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
The difference between this keyword and `Wait For And Input Text` is that this keyword
does not log the given password. See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.input_password(locator, text)
@keyword("Wait For And Input Text")
def wait_for_and_input_text(self, locator, text, timeout=None, error=None):
"""Wait for and type the given ``locator`` into text field identified by ``locator``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.input_text(locator, text)
@keyword("Wait For And Input Value")
def wait_for_and_input_value(self, locator, value, timeout=None, error=None):
"""Wait for and set the given ``value`` into the text field identified by ``locator``.
This is an IOS only keyword, input value makes use of set_value.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
The difference between this keyword and `Wait For And Input Text` is that this keyword
does not log the given password. See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.input_value(locator, value)
@keyword("Wait For And Long Press")
def wait_for_and_long_press(self, locator, duration=5000, timeout=None, error=None):
"""Wait for and long press the element identified by ``locator`` with optional duration.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See `introduction` for details about locating elements."""
self._wait_until_page_contains_element(locator, timeout, error)
self.long_press(locator, duration)
@keyword("Wait Until Element Contains")
def wait_until_element_contains(self, locator, text, timeout=None, error=None):
"""Waits until element specified with ``locator`` contains ``text``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See also `Wait Until Page Contains`,
`Wait Until Page Does Not Contain`
`Wait Until Page Does Not Contain Element`
"""
self._wait_until_page_contains_element(locator, timeout, error)
self.element_should_contain_text(locator, text, error)
@keyword("Wait Until Element Does Not Contain")
def wait_until_element_does_not_contain(self, locator, text, timeout=None, error=None):
"""Waits until element specified with ``locator`` does not contain ``text``.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See also `Wait Until Element Contains`,
`Wait Until Page Contains`,
`Wait Until Page Does Not Contain`
`Wait Until Page Does Not Contain Element`
"""
self._wait_until_page_contains_element(locator, timeout, error)
self.element_should_not_contain_text(locator, text, error)
@keyword("Wait Until Element Is Enabled")
def wait_until_element_is_enabled(self, locator, timeout=None, error=None):
"""Waits until element specified with ``locator`` is enabled.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See also `Wait Until Element Is Disabled`
"""
self._wait_until_page_contains_element(locator, timeout, error)
self.element_should_be_enabled(locator)
@keyword("Wait Until Element Is Disabled")
def wait_until_element_is_disabled(self, locator, timeout=None, error=None):
"""Waits until element specified with ``locator`` is disabled.
Fails if ``timeout`` expires before the element appears.
``error`` can be used to override the default error message.
See also `Wait Until Element Is Disabled`
"""
self._wait_until_page_contains_element(locator, timeout, error)
self.element_should_be_disabled(locator)
@keyword("Drag And Drop")
def drag_and_drop(self, source, target, delay=1500):
"""Drags the element found with the locator ``source`` to the element found with the
locator ``target``.
``Delay`` (iOS Only): Delay between initial button press and dragging, defaults to 1500ms."""
AppiumCommon.drag_and_drop(self, source, target, delay)
@keyword("Drag And Drop By Offset")
def drag_and_drop_by_offset(self, locator, x_offset=0, y_offset=0, delay=1500):
"""Drags the element found with ``locator`` to the given ``x_offset`` and ``y_offset``
coordinates.
``Delay`` (iOS Only): Delay between initial button press and dragging, defaults to 1500ms."""
AppiumCommon.drag_and_drop_by_offset(self, locator, x_offset, y_offset, delay)
@keyword("Scroll Down To Text")
def scroll_down_to_text(self, text, exact_match=False, swipe_count=10):
"""Scrolls down to ``text``.
In some instances the default scroll behavior does not work. In this case the keyword will use small swipes
to find the element. The ``swipe_count`` limits the number of these swipes before the keyword gives up,
defaults to 10."""
try:
driver = self._current_application()
element = self._element_find_by_text(text, exact_match)
if not self.get_current_context().startswith("NATIVE"):
element._execute("getElementLocationOnceScrolledIntoView")
else:
driver.execute_script("mobile: scroll", {"direction": 'down', 'elementid': element})
except ValueError:
self._scroll_to_text(text, 'down', swipe_count)
@keyword("Scroll Up To Text")
def scroll_up_to_text(self, text, exact_match=False, swipe_count=10):
"""Scrolls down to ``text``.
In some instances the default scroll behavior does not work. In this case the keyword will use small swipes
to find the element. The ``swipe_count`` limits the number of these swipes before the keyword gives up,
defaults to 10."""
try:
driver = self._current_application()
element = self._element_find_by_text(text, exact_match)
if not self.get_current_context().startswith("NATIVE"):
element._execute("getElementLocationOnceScrolledIntoView")
else:
driver.execute_script("mobile: scroll", {"direction": 'up', 'elementid': element})
except ValueError:
self._scroll_to_text(text, 'up', swipe_count)
def scroll_down(self, locator):
"""Scrolls down to an element identified by ``locator``."""
driver = self._current_application()
element = self._element_find(locator, True, True)
if not self.get_current_context().startswith("NATIVE"):
element._execute("getElementLocationOnceScrolledIntoView")
else:
driver.execute_script("mobile: scroll", {"toVisible": 'down', 'elementid': element})
def scroll_up(self, locator):
"""Scrolls up to an element identified by ``locator``."""
driver = self._current_application()
element = self._element_find(locator, True, True)
if not self.get_current_context().startswith("NATIVE"):
element._execute("getElementLocationOnceScrolledIntoView")
else:
driver.execute_script("mobile: scroll", {"direction": 'up', 'elementid': element})
@keyword("Wait For And Tap")
def wait_for_and_tap(self, locator, x_offset=None, y_offset=None, count=1, timeout=None,
error=None):
""" Wait for and then Tap element identified by ``locator``.
Args:
- ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.
- ``y_offset`` - (optional) y coordinate. If y is used, x must also be set, and vice versa
- ``count`` - can be used to tap multiple times
- ``timeout`` - time in seconds to locate the element, defaults to global timeout
- ``error`` - (optional) used to override the default error message.
"""
self._wait_until_page_contains_element(locator, timeout, error)
self.tap(locator, x_offset, y_offset, count)
def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page and embeds it into the log.
`filename` argument specifies the name of the file to write the
screenshot into. If no `filename` is given, the screenshot is saved into file
`appium-screenshot-<counter>.png` under the directory where
the Robot Framework log file is written into. The `filename` is
also considered relative to the same directory, if it is not
given in absolute format.
`css` can be used to modify how the screenshot is taken. By default
the bakground color is changed to avoid possible problems with
background leaking when the page layout is somehow broken.
See `Save Appium Screenshot` for a screenshot that will be unique across reports
"""
return AppiumCommon.capture_page_screenshot(self, filename)
@keyword("Save Appium Screenshot")
def save_appium_screenshot(self):
"""Takes a screenshot with a unique filename to be stored in Robot Framework compiled
reports."""
return AppiumCommon.save_appium_screenshot(self)
# Private
def _wait_until_page_contains(self, text, timeout=None, error=None):
"""Internal version to avoid duplicate screenshots"""
AppiumCommon.wait_until_page_contains(self, text, timeout, error)
def _wait_until_page_contains_element(self, locator, timeout=None, error=None):
"""Internal version to avoid duplicate screenshots"""
if not error:
error = "Element '%s' did not appear in <TIMEOUT>" % locator
self._wait_until(timeout, error, self._is_element_present, locator)
def _platform_dependant_press(self, actions, element, delay=1500):
"""Decide press action based on platform"""
AppiumCommon._platform_dependant_press(self, actions, element, delay)
def _element_find_by_text(self, text, exact_match=False):
if self._is_ios():
element = self._element_find(text, True, False)
if element:
return element
if exact_match:
_xpath = u'//*[@value="{}" or @label="{}"]'.format(text, text)
else:
_xpath = u'//*[contains(@label,"{}") or contains(@value, "{}") or contains(text(), "{}")]'.format(text, text, text)
elif self._is_android():
if exact_match:
_xpath = u'//*[@{}="{}"]'.format('text', text)
else:
_xpath = u'//*[contains(@text,"{}")]'.format(text)
return self._element_find(_xpath, True, True)
def _is_text_visible(self, text, exact_match=False):
element = self._element_find_by_text(text, exact_match)
if element is not None:
return element.is_displayed()
return None
def _scroll_to_text(self, text, swipe_direction, swipe_count=10):
"""This is a more manual attempt in case the first scroll does not work."""
for _ in range(swipe_count):
if self._is_android() and self._is_text_present(text):
return True
if self._is_ios() and self._is_text_visible(text):
return True
if swipe_direction.lower() == 'up':
self.swipe_by_percent(50, 25, 50, 75) # use swipe by direction if its ever implemented
elif swipe_direction.lower() == 'down':
self.swipe_by_percent(50, 75, 50, 25) # use swipe by direction if its ever implemented
else:
appLib.fail("Swipe_direction: " + swipe_direction + "is not implemented.")
appLib.fail("Text: " + text + " was not found after " + str(swipe_count) + " swipes") | /robotframework_applicationlibrary-1.2.1-py3-none-any.whl/ApplicationLibrary/MobileLibrary.py | 0.809464 | 0.379493 | MobileLibrary.py | pypi |
import itertools
from time import time
from appium.webdriver.common.touch_action import TouchAction
from robot.libraries.BuiltIn import BuiltIn
SCREENSHOT_COUNTER = itertools.count()
appLib = BuiltIn()
def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page and embeds it into the log.
`filename` argument specifies the name of the file to write the
screenshot into. If no `filename` is given, the screenshot is saved into file
`appium-screenshot-<counter>.png` under the directory where
the Robot Framework log file is written into. The `filename` is
also considered relative to the same directory, if it is not
given in absolute format.
`css` can be used to modify how the screenshot is taken. By default
the bakground color is changed to avoid possible problems with
background leaking when the page layout is somehow broken.
See `Save Appium Screenshot` for a screenshot that will be unique across reports
"""
path, link = self._get_screenshot_paths(filename)
if hasattr(self._current_application(), 'get_screenshot_as_file'):
self._current_application().get_screenshot_as_file(path)
else:
self._current_application().save_screenshot(path)
# Image is shown on its own row and thus prev row is closed on purpose
self._html('</td></tr><tr><td colspan="3"><a href="%s">'
'<img src="%s" width="800px"></a>' % (link, link))
return link
def save_appium_screenshot(self):
"""Takes a screenshot with a unique filename to be stored
in Robot Framework compiled reports."""
timestamp = time()
filename = 'appium-screenshot-' + str(timestamp) + '-' + str(next(SCREENSHOT_COUNTER)) + '.png'
return self.capture_page_screenshot(filename)
def wait_until_page_contains(self, text, timeout=None, error=None):
"""Internal version to avoid duplicate screenshots"""
if not error:
error = "Text '%s' did not appear in <TIMEOUT>" % text
self._wait_until(timeout, error, self._is_text_present, text)
def drag_and_drop(self, source, target, delay=1500):
"""Drags the element found with the locator ``source`` to the element found with the
locator ``target``.
``Delay`` (iOS Only): Delay between initial button press and dragging, defaults to 1500ms."""
source_element = self._element_find(source, True, True)
target_element = self._element_find(target, True, True)
appLib.log('Dragging source element "%s" to target element "%s".' % (source, target))
actions = TouchAction(self._current_application())
self._platform_dependant_press(actions, source_element, delay)
actions.move_to(target_element)
actions.release().perform()
def drag_and_drop_by_offset(self, locator, x_offset=0, y_offset=0, delay=1500):
"""Drags the element found with ``locator`` to the given ``x_offset`` and ``y_offset``
coordinates.
``Delay`` (iOS Only): Delay between initial button press and dragging, defaults to 1500ms."""
element = self._element_find(locator, True, True)
appLib.log('Dragging element "%s" by offset (%s, %s).' % (locator, x_offset, y_offset))
x_center = element.location['x'] + element.size['width'] / 2
y_center = element.location['y'] + element.size['height'] / 2
actions = TouchAction(self._current_application())
self._platform_dependant_press(actions, element, delay)
actions.move_to(x=x_center + x_offset, y=y_center + y_offset)
actions.release().perform()
def _platform_dependant_press(self, actions, element, delay):
if self._is_ios():
actions.long_press(element, duration=2000)
actions.wait(delay)
else:
actions.press(element) | /robotframework_applicationlibrary-1.2.1-py3-none-any.whl/ApplicationLibrary/Helpers/AppiumCommon.py | 0.776538 | 0.260519 | AppiumCommon.py | pypi |
# robotframework-apprise
[](https://www.gnu.org/licenses/gpl-3.0) [](https://github.com/psf/black) [](https://github.com/joergschultzelutter/robotframework-apprise/actions/workflows/codeql.yml) [](https://pypi.python.org/pypi/robotframework-apprise)
```robotframework-apprise``` is a [Robot Framework](https://www.robotframework.org) keyword collection for the [Apprise](https://github.com/caronc/apprise) push message library. It enables Robot Framework users to send push/email messages to every message service supported by Apprise.

## Installation
The easiest way is to install this package is from pypi:
pip install robotframework-apprise
## Robot Framework Library Example
In order to run the example code, you need to provide at least one valid target messenger. Have a look at [Apprise's list of supported messenger platforms](https://github.com/caronc/apprise/wiki)
- [send_apprise_message.robot](https://github.com/joergschultzelutter/robotframework-apprise/blob/master/test/send_apprise_message.robot)
## Library usage and supported keywords
| Keyword | Description |
|-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ``Send Apprise Message`` | Sends a push message through Apprise |
| ``Set Clients`` and ``Set Attachments`` | Sets a new value list and replace the previous values |
| ``Add Client`` and ``Add Attachment`` | Adds a value to an existing list |
| ``Remove Client`` and ``Remove Attachment`` | Removes a value from an existing list (if present). Trying to remove a non-existing entry will NOT result in an error |
| ``Clear All Clients`` and ``Clear All Attachments`` | Completely removes the current values from the respective list |
| ``Set Attachment Delimiter`` | Optional delimiter reconfiguration - see details below |
| ``Set Notify Type`` | Sets one of Apprise's [supported notify types](https://github.com/caronc/apprise/wiki/Development_API#message-types-and-themes). Valid values are ``info``,``success``,``warning``, and ``failure``. Default notify type is ``info`` |
| ``Set Body Format`` | Sets one of Apprise's [supported body formats](https://github.com/caronc/apprise/wiki/Development_API#notify--send-notifications). Valid values are ``html``,``text``, and ``markdown``. Default body format is ``html`` |
| ``Set Config File`` | Allows you to specify a single Apprise [config file](https://github.com/caronc/apprise#configuration-files) in YAML or Text format |
Both ``clients`` and ``attachments`` options can be passed as a ``List`` type variable __or__ as a ``string``. If you use a ``string``, the default delimiter is a comma ``,``. Use the ``Set Attachment Delimiter`` keyword in case you need to use a different delimiter for your attachments.
All ``Set ...`` keywords provide corresponding ``Get ...`` keywords.
``Attachments`` are purely optional. Providing at least one ``Client`` is mandatory, though.
Examples:
```robot
# Send a message with one client and a List which contains our images
@{IMAGE_LIST}= Create List http://www.mysite.com/image1.jpg http://www.mysite.com/image2.jpg
Send Apprise Message title=Robot Framework Apprise Demo body=Connect to Apprise with your Robot Framework Tests! clients=<apprise_client> attachments=${IMAGE_LIST}
```
```robot
# Send a message with one client. Our attachments use a comma-separated string (default)
Send Apprise Message title=Robot Framework Apprise Demo body=Connect to Apprise with your Robot Framework Tests! clients=<apprise_client> attachments=http://www.mysite.com/image1.jpg,http://www.mysite.com/image2.jpg
```
```robot
# Send a message with one client. Our attachments use a custom delimiter ^
Set Attachment Delimiter ^
Send Apprise Message title=Robot Framework Apprise Demo body=Connect to Apprise with your Robot Framework Tests! clients=<apprise_client> attachments=http://www.mysite.com/image1.jpg^http://www.mysite.com/image2.jpg
```
```robot
# Send a message with one client and a List which contains our images
@{IMAGE_LIST}= Create List http://www.mysite.com/image1.jpg http://www.mysite.com/image2.jpg
Set Test Variable ${CONFIG_FILE} config.yaml
Send Apprise Message title=Robot Framework Apprise Demo body=Connect to Apprise with your Robot Framework Tests! config_file=${CONFIG_FILE} attachments=${IMAGE_LIST}
```
## Known issues
- The current version of this library does not support Apprise's whole feature set. Options such as tagging are not implemented (but may work if you use a [config file](https://github.com/caronc/apprise#configuration-files)-based setting)
- Unlike the original Apprise API, only one YAML config file is currently supported with this Robot Framework keyword library.
| /robotframework-apprise-0.3.1.tar.gz/robotframework-apprise-0.3.1/README.md | 0.487795 | 0.899254 | README.md | pypi |
import os
import tarfile
import zipfile
from robot.libraries.Collections import Collections
from robot.libraries.OperatingSystem import OperatingSystem
from .utils import Unzip, Untar, return_files_lists
class ArchiveKeywords:
ROBOT_LIBRARY_SCOPE = 'Global'
compressions = {
"stored": zipfile.ZIP_STORED,
"deflated": zipfile.ZIP_DEFLATED,
"bzip2": zipfile.ZIP_BZIP2,
"lzma": zipfile.ZIP_LZMA
}
tars = ['.tar', '.tar.bz2', '.tar.gz', '.tgz', '.tz2']
zips = ['.docx', '.egg', '.jar', '.odg', '.odp', '.ods', '.xlsx', '.odt',
'.pptx', 'zip']
def __init__(self):
self.oslib = OperatingSystem()
self.collections = Collections()
def extract_zip_file(self, zip_file, dest=None):
""" Extract a ZIP file
`zip_file` the path to the ZIP file
`dest` optional destination folder. Assumes current working directory if it is none
It will be created if It doesn't exist.
"""
if dest:
self.oslib.create_directory(dest)
self.oslib.directory_should_exist(dest)
else:
dest = os.getcwd()
cwd = os.getcwd()
# Dont know why I a have `gotta catch em all` exception handler here
try:
Unzip().extract(zip_file, dest)
except:
raise
finally:
os.chdir(cwd)
def extract_tar_file(self, tar_file, dest=None):
""" Extract a TAR file
`tar_file` the path to the TAR file
`dest` optional destination folder. Assumes current working directory if it is none
It will be created if It doesn't exist.
"""
if dest:
self.oslib.create_directory(dest)
else:
dest = os.getcwd()
self.oslib.file_should_exist(tar_file)
Untar().extract(tar_file, dest)
def archive_should_contain_file(self, zip_file, filename):
""" Check if a file exists in the ZIP file without extracting it
`zip_file` the path to the ZIP file
`filename` name of the file to search for in `zip_file`
"""
self.oslib.file_should_exist(zip_file)
files = zipfile.ZipFile(zip_file).namelist() if zipfile.is_zipfile(zip_file) else tarfile.open(
zip_file).getnames()
files = [os.path.normpath(item) for item in files]
self.collections.list_should_contain_value(files, filename)
def create_tar_from_files_in_directory(self, directory, filename, sub_directories=True, tgz=False):
""" Take all files in a directory and create a tar package from them
`directory` Path to the directory that holds our files
`filename` Path to our destination TAR package.
`sub_directories` Shall files in sub-directories be included - True by default.
`tgz` Creates a .tgz / .tar.gz archive (compressed tar package) instead of a regular tar - False by default.
"""
if tgz:
tar = tarfile.open(filename, "w:gz")
else:
tar = tarfile.open(filename, "w")
files = return_files_lists(directory, sub_directories)
for filepath, name in files:
tar.add(filepath, arcname=name)
tar.close()
@classmethod
def create_zip_from_files_in_directory(cls, directory, filename, sub_directories=False, compression="stored"):
""" Take all files in a directory and create a zip package from them
`directory` Path to the directory that holds our files
`filename` Path to our destination ZIP package.
`sub_directories` Shall files in sub-directories be included - False by default.
`compression` stored (default; no compression), deflated, bzip2 (with python >= 3.3), lzma (with python >= 3.3)
"""
if cls.compressions.get(compression) is None:
raise ValueError("Unknown compression method")
comp_method = cls.compressions.get(compression)
the_zip = zipfile.ZipFile(filename, "w", comp_method)
files = return_files_lists(directory, sub_directories)
for filepath, name in files:
the_zip.write(filepath, arcname=name)
the_zip.close()
if __name__ == '__main__':
al = ArchiveKeywords()
al.extract('test.zip') | /robotframework_archivelibrary-0.4.2-py3-none-any.whl/ArchiveLibrary/keywords.py | 0.5 | 0.229298 | keywords.py | pypi |
Assertion Engine
================
Generic way to create meaningful and easy to use assertions for the `Robot Framework`_
libraries. This tools is spin off from `Browser library`_ project, where the Assertion
Engine was developed as part of the of library.
.. image:: https://github.com/MarketSquare/AssertionEngine/actions/workflows/on-push.yml/badge.svg
:target: https://github.com/MarketSquare/AssertionEngine
.. image:: https://img.shields.io/badge/License-Apache%202.0-blue.svg
:target: https://opensource.org/licenses/Apache-2.0
Supported Assertions
--------------------
Currently supported assertion operators are:
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| Operator | Alternative Operators | Description | Validate Equivalent |
+==========+===========================+====================================================================================+==================================+
| == | equal, equals, should be | Checks if returned value is equal to expected value. | value == expected |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| != | inequal, should not be | Checks if returned value is not equal to expected value. | value != expected |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| > | greater than | Checks if returned value is greater than expected value. | value > expected |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| >= | | Checks if returned value is greater than or equal to expected value. | value >= expected |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| < | less than | Checks if returned value is less than expected value. | value < expected |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| <= | | Checks if returned value is less than or equal to expected value. | value <= expected |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| \*= | contains | Checks if returned value contains expected value as substring. | expected in value |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| | not contains | Checks if returned value does not contain expected value as substring. | expected not in value |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| ^= | should start with, starts | Checks if returned value starts with expected value. | re.search(f"^{expected}", value) |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| $= | should end with, ends | Checks if returned value ends with expected value. | re.search(f"{expected}$", value) |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| matches | | Checks if given RegEx matches minimum once in returned value. | re.search(expected, value) |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| validate | | Checks if given Python expression evaluates to True. | |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
| evaluate | then | When using this operator, the keyword does return the evaluated Python expression. | |
+----------+---------------------------+------------------------------------------------------------------------------------+----------------------------------+
Supported formatters:
+-------------------+------------------------------------------------------------+
| Formatter | Description |
+===================+============================================================+
| normalize spaces | Substitutes multiple spaces to single space from the value |
+-------------------+------------------------------------------------------------+
| strip | Removes spaces from the beginning and end of the value |
+-------------------+------------------------------------------------------------+
| apply to expected | Applies rules also for the expected value |
+-------------------+------------------------------------------------------------+
| case insensitive | Converts value to lower case |
+-------------------+------------------------------------------------------------+
Usage
-----
When keywords needs to do an assertion
.. _Robot Framework: http://robotframework.org
.. _Browser library: https://robotframework-browser.org/
| /robotframework_assertion_engine-2.0.0.tar.gz/robotframework_assertion_engine-2.0.0/README.rst | 0.949118 | 0.772144 | README.rst | pypi |
import re
from typing import Dict, List
from robot.api.deco import keyword # type: ignore
def _strip(value: str) -> str:
return value.strip()
def _normalize_spaces(value: str) -> str:
return re.sub(r"\s+", " ", value)
def _apply_to_expected(value: str) -> str:
return value
def _case_insensitive(value: str) -> str:
return value.lower()
FormatRules = {
"normalize spaces": _normalize_spaces,
"strip": _strip,
"apply to expected": _apply_to_expected,
"case insensitive": _case_insensitive,
}
FormatterTypes = Dict[str, List[str]]
class Formatter:
def __init__(self, ctx):
self.ctx = ctx
@property
def keyword_formatters(self):
return self.ctx._keyword_formatters
@keyword_formatters.setter
def keyword_formatters(self, formatters: dict):
self.ctx._keyword_formatters = formatters
@property
def keywords(self) -> dict:
return self.ctx.keywords
@keyword
def set_assertion_formatters(self, formatters: FormatterTypes):
"""Set keywords formatters for assertions.
``formatters`` is dictionary, where key is the keyword name
where formatters are applied. Dictionary value is a list of
formatter which are applied. Using keywords always replaces
existing formatters for keywords.
Supported formatter are: `normalize space`, `strip` and
`apply to expected`.
Example:
| `Set Assertion Formatters` {"Keyword Name": ["strip", "normalize spaces"]}
"""
if not self._are_library_keywords(formatters):
raise AssertionError("Could not find keyword from library.")
formatters_with_methods = {}
for formatter in formatters:
formatters_with_methods[
self._get_library_keyword(formatter)
] = self._get_formatters(formatters[formatter])
self.keyword_formatters = formatters_with_methods
def _are_library_keywords(self, formatters: dict) -> bool:
return all([self._library_keyword(item) for item in formatters])
def _library_keyword(self, name: str) -> bool:
name = self._normalize_keyword(name)
if self._get_library_keyword(name):
return True
return False
def _get_library_keyword(self, name: str):
name = self._normalize_keyword(name)
for kw in self.keywords:
kw_normalized = self._normalize_keyword(kw)
if kw_normalized == name:
return self.keywords[kw]
def _normalize_keyword(self, name: str):
return name.lower().replace(" ", "_")
def _get_formatters(self, kw_formatter: List) -> List:
return [FormatRules[formatter] for formatter in kw_formatter] | /robotframework_assertion_engine-2.0.0.tar.gz/robotframework_assertion_engine-2.0.0/assertionengine/formatter.py | 0.877713 | 0.401893 | formatter.py | pypi |
import ast
import re
from enum import Enum, Flag, IntFlag
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union, cast
from robot.libraries.BuiltIn import BuiltIn # type: ignore
from .type_converter import is_truthy, type_converter
__version__ = "2.0.0"
AssertionOperator = Enum(
"AssertionOperator",
{
"equal": "==",
"equals": "==",
"==": "==",
"should be": "==",
"inequal": "!=",
"!=": "!=",
"should not be": "!=",
"less than": "<",
"<": "<",
"greater than": ">",
">": ">",
"<=": "<=",
">=": ">=",
"contains": "*=",
"not contains": "not contains",
"*=": "*=",
"starts": "^=",
"^=": "^=",
"should start with": "^=",
"ends": "$=",
"should end with": "$=",
"$=": "$=",
"matches": "$",
"validate": "validate",
"then": "then",
"evaluate": "then",
},
)
AssertionOperator.__doc__ = """
Currently supported assertion operators are:
| = Operator = | = Alternative Operators = | = Description = | = Validate Equivalent = |
| ``==`` | ``equal``, ``equals``, ``should be`` | Checks if returned value is equal to expected value. | ``value == expected`` |
| ``!=`` | ``inequal``, ``should not be`` | Checks if returned value is not equal to expected value. | ``value != expected`` |
| ``>`` | ``greater than`` | Checks if returned value is greater than expected value. | ``value > expected`` |
| ``>=`` | | Checks if returned value is greater than or equal to expected value. | ``value >= expected`` |
| ``<`` | ``less than`` | Checks if returned value is less than expected value. | ``value < expected`` |
| ``<=`` | | Checks if returned value is less than or equal to expected value. | ``value <= expected`` |
| ``*=`` | ``contains`` | Checks if returned value contains expected value as substring. | ``expected in value`` |
| | ``not contains`` | Checks if returned value does not contain expected value as substring. | ``expected in value`` |
| ``^=`` | ``should start with``, ``starts`` | Checks if returned value starts with expected value. | ``re.search(f"^{expected}", value)`` |
| ``$=`` | ``should end with``, ``ends`` | Checks if returned value ends with expected value. | ``re.search(f"{expected}$", value)`` |
| ``matches`` | | Checks if given RegEx matches minimum once in returned value. | ``re.search(expected, value)`` |
| ``validate`` | | Checks if given Python expression evaluates to ``True``. | |
| ``evaluate`` | ``then`` | When using this operator, the keyword does return the evaluated Python expression. | |
Currently supported formatters for assertions are:
| = Formatter = | = Description = |
| ``normalize spaces`` | Substitutes multiple spaces to single space from the value |
| ``strip`` | Removes spaces from the beginning and end of the value |
| ``case insensitive`` | Converts value to lower case before comparing |
| ``apply to expected`` | Applies rules also for the expected value |
Formatters are applied to the value before assertion is performed and keywords returns a value where rule is
applied. Formatter is only applied to the value which keyword returns and not all rules are valid for all assertion
operators. If ``apply to expected`` formatter is defined, then formatters are then formatter are also applied to
expected value.
"""
NumericalOperators = [
AssertionOperator["=="],
AssertionOperator["!="],
AssertionOperator[">="],
AssertionOperator[">"],
AssertionOperator["<="],
AssertionOperator["<"],
]
SequenceOperators = [
AssertionOperator["*="],
AssertionOperator["validate"],
AssertionOperator["then"],
AssertionOperator["=="],
AssertionOperator["!="],
]
EvaluationOperators = [
AssertionOperator["validate"],
AssertionOperator["then"],
]
handlers: Dict[AssertionOperator, Tuple[Callable, str]] = {
AssertionOperator["=="]: (lambda a, b: a == b, "should be"),
AssertionOperator["!="]: (lambda a, b: a != b, "should not be"),
AssertionOperator["<"]: (lambda a, b: a < b, "should be less than"),
AssertionOperator[">"]: (lambda a, b: a > b, "should be greater than"),
AssertionOperator["<="]: (lambda a, b: a <= b, "should be less than or equal"),
AssertionOperator[">="]: (lambda a, b: a >= b, "should be greater than or equal"),
AssertionOperator["*="]: (lambda a, b: b in a, "should contain"),
AssertionOperator["not contains"]: (lambda a, b: b not in a, "should not contain"),
AssertionOperator["matches"]: (lambda a, b: re.search(b, a), "should match"),
AssertionOperator["^="]: (
lambda a, b: re.search(f"^{re.escape(b)}", a),
"should start with",
),
AssertionOperator["$="]: (
lambda a, b: re.search(f"{re.escape(b)}$", a),
"should end with",
),
AssertionOperator["validate"]: (
lambda a, b: BuiltIn().evaluate(b, namespace={"value": a}),
"should validate to true with",
),
}
set_handlers: Dict[AssertionOperator, Tuple[Callable, str]] = {
AssertionOperator["=="]: (lambda a, b: a == b, "should be"),
AssertionOperator["!="]: (lambda a, b: a != b, "should not be"),
AssertionOperator["*="]: (lambda a, b: b.issubset(a), "should contain"),
AssertionOperator["not contains"]: (
lambda a, b: not b.issubset(a),
"should not contain",
),
}
T = TypeVar("T")
def apply_formatters(value: T, formatters: Optional[List[Any]]) -> Any:
if not formatters:
return value
for formatter in formatters:
value = formatter(value)
return value
def apply_to_expected(expected: Any, formatters: Optional[List[Any]]) -> Any:
if not formatters:
return expected
for formatter in formatters:
if formatter.__name__ == "_apply_to_expected":
return apply_formatters(expected, formatters)
return expected
def verify_assertion(
value: T,
operator: Optional[AssertionOperator],
expected: Any,
message: str = "",
custom_message: Optional[str] = None,
formatters: Optional[list] = None,
) -> Any:
if operator is None and expected:
raise ValueError(
"Invalid validation parameters. Assertion operator is mandatory when specifying expected value."
)
if operator is None:
return value
expected = apply_to_expected(expected, formatters)
value = apply_formatters(value, formatters)
if operator is AssertionOperator["then"]:
return cast(T, BuiltIn().evaluate(expected, namespace={"value": value}))
handler = handlers.get(operator)
filler = " " if message else ""
if handler is None:
raise RuntimeError(
f"{message}{filler}`{operator}` is not a valid assertion operator"
)
validator, text = handler
if not validator(value, expected):
raise_error(custom_message, expected, filler, message, text, value)
return value
def flag_verify_assertion(
value: Union[IntFlag, Flag],
operator: Optional[AssertionOperator],
expected: Any,
message: str = "",
custom_message: Optional[str] = None,
) -> Any:
if not isinstance(value, Flag):
raise TypeError(f"Verified value was not of type Flag. It was {type(value)}")
if (operator is None and expected) or (operator and not expected):
raise ValueError(
"Invalid validation parameters. Assertion operator and expected value can only be used together."
)
if operator is None:
return value
if operator is AssertionOperator["then"]:
return eval_flag(expected[0], value)
filler = " " if message else ""
if operator is AssertionOperator["validate"]:
if not eval_flag(expected[0], value):
raise_error(
custom_message,
expected[0],
filler,
message,
"should validate to true with",
value,
)
else:
value_set = set([flag.name for flag in type(value) if flag in value])
expected_set = set(expected)
handler = set_handlers.get(operator)
if handler is None:
raise RuntimeError(
f"{message}{filler}`{operator}` is not a valid assertion operator"
)
validator, text = handler
if not validator(value_set, expected_set):
raise_error(
custom_message,
sorted(expected_set),
filler,
message,
text,
sorted(value_set),
)
return value
def eval_flag(expected, value) -> Any:
return BuiltIn().evaluate(
expected, namespace={"value": value, **value._member_map_}
)
def raise_error(custom_message, expected, filler, message, text, value):
type_value, type_expected = type_converter(value), type_converter(expected)
value_quotes, expected_quotes = "'", "'"
if isinstance(value, str):
value = repr(value)
value_quotes = ""
if isinstance(expected, str):
expected = repr(expected)
expected_quotes = ""
if not custom_message:
error_msg = (
f"{message}{filler}{value_quotes}{value}{value_quotes} ({type_value}) "
f"{text} {expected_quotes}{expected}{expected_quotes} ({type_expected})"
)
else:
error_msg = custom_message.format(
value=value,
value_type=type_value,
expected=expected,
expected_type=type_expected,
)
raise AssertionError(error_msg)
def float_str_verify_assertion(
value: T,
operator: Optional[AssertionOperator],
expected: Any,
message="",
custom_message="",
):
if operator is None:
return value
elif operator in NumericalOperators:
expected = float(expected)
elif operator in [
AssertionOperator["validate"],
AssertionOperator["then"],
]:
expected = str(expected)
else:
raise ValueError(f"Operator '{operator.name}' is not allowed.")
return verify_assertion(value, operator, expected, message, custom_message)
def bool_verify_assertion(
value: T,
operator: Optional[AssertionOperator],
expected: Any,
message="",
custom_message="",
):
if operator and operator not in [
AssertionOperator["=="],
AssertionOperator["!="],
]:
raise ValueError(f"Operators '==' and '!=' are allowed, not '{operator.name}'.")
expected_bool = is_truthy(expected)
return verify_assertion(value, operator, expected_bool, message, custom_message)
def map_list(selected: List):
if not selected or len(selected) == 0:
return None
elif len(selected) == 1:
return selected[0]
else:
return selected
def list_verify_assertion(
value: List,
operator: Optional[AssertionOperator],
expected: List,
message="",
custom_message="",
):
if operator is None:
return value
if operator:
if operator not in SequenceOperators:
raise AttributeError(
f"Operator '{operator.name}' is not allowed in this Keyword."
f"Allowed operators are: '{SequenceOperators}'"
)
if operator in [
AssertionOperator["=="],
AssertionOperator["!="],
]:
expected.sort()
value.sort()
elif operator == AssertionOperator["contains"]:
if not BuiltIn().evaluate(
"all(item in value for item in expected)",
namespace={"value": value, "expected": expected},
):
raise_error(
custom_message,
expected,
" " if message else "",
message,
"should contain",
value,
)
return value
elif operator in [
AssertionOperator["then"],
AssertionOperator["validate"],
]:
expected = expected[0]
return verify_assertion(value, operator, expected, message, custom_message)
def dict_verify_assertion(
value: Dict,
operator: Optional[AssertionOperator],
expected: Optional[Dict],
message="",
custom_message="",
):
if operator and operator not in SequenceOperators:
raise AttributeError(
f"Operator '{operator.name}' is not allowed in this Keyword."
f"Allowed operators are: {SequenceOperators}"
)
else:
return verify_assertion(value, operator, expected, message, custom_message)
def int_dict_verify_assertion(
value: Dict[str, int],
operator: Optional[AssertionOperator],
expected: Optional[Dict[str, int]],
message="",
custom_message="",
):
if not operator:
return value
elif operator in SequenceOperators:
if operator not in EvaluationOperators and isinstance(expected, str):
evaluated_expected = ast.literal_eval(expected)
else:
evaluated_expected = expected
return verify_assertion(
value, operator, evaluated_expected, message, custom_message
)
elif expected and operator in NumericalOperators:
for k, v in value.items():
exp = expected[k]
verify_assertion(v, operator, exp, message, custom_message)
return value
else:
raise AttributeError(
f"Operator '{operator.name}' is not allowed in this Keyword."
f"Allowed operators are: {NumericalOperators} and {SequenceOperators}"
) | /robotframework_assertion_engine-2.0.0.tar.gz/robotframework_assertion_engine-2.0.0/assertionengine/assertion_engine.py | 0.879199 | 0.575856 | assertion_engine.py | pypi |
import time
import inspect
import asyncio
from robot.libraries.BuiltIn import BuiltIn
from robot.utils.robottime import timestr_to_secs, secs_to_timestr
from robot.errors import DataError, ExecutionPassed, ExecutionFailed, ExecutionFailures
class AsyncioUtils:
def __init__(self) -> None:
try:
self.builtIn = BuiltIn()
except Exception:
self.builtIn = None
async def async_gather_keywords(self, *keywords):
"""Executes all the given keywords concurrently.
This keyword is mainly useful to run multiple keywords concurrently
just like calling asyncio.gather() in python.
The keywords passed need to be async, else an error is raised.
By default all arguments are expected to be keywords to be executed.
Examples:
| `Run Keywords` | `Initialize database` | `Start servers` | `Clear logs` |
| `Run Keywords` | ${KW 1} | ${KW 2} |
| `Run Keywords` | @{KEYWORDS} |
Keywords can also be run with arguments using upper case ``AND`` as
a separator between keywords. The keywords are executed so that the
first argument is the first keyword and proceeding arguments until
the first ``AND`` are arguments to it. First argument after the first
``AND`` is the second keyword and proceeding arguments until the next
``AND`` are its arguments. And so on.
Examples:
| `Run Keywords` | `Initialize database` | db1 | AND | `Start servers` | server1 | server2 |
| `Run Keywords` | `Initialize database` | ${DB NAME} | AND | `Start servers` | @{SERVERS} | AND | `Clear logs` |
| `Run Keywords` | ${KW} | AND | @{KW WITH ARGS} |
Notice that the ``AND`` control argument must be used explicitly and
cannot itself come from a variable. If you need to use literal ``AND``
string as argument, you can either use variables or escape it with
a backslash like ``\\AND``.
"""
return await self._async_gather_keywords(
self.builtIn._split_run_keywords(list(keywords))
)
async def _async_gather_keywords(self, iterable):
tasks = []
errors = []
try:
for kw, args in iterable:
try:
task = self.builtIn.run_keyword(kw, *args)
if not inspect.iscoroutine(task):
raise DataError(f"Keyword '{kw}' is not async")
tasks.append(task)
except ExecutionPassed as err:
err.set_earlier_failures(errors)
raise err
except ExecutionFailed as err:
errors.extend(err.get_errors())
if not err.can_continue(self.builtIn._context):
break
if errors:
raise ExecutionFailures(errors)
except Exception as err:
for t in tasks:
t.close()
raise err
return await asyncio.gather(*tasks)
async def async_sleep(self, time_, reason=None):
"""
Pauses the test executed for the given time asynchronously.
This is useful for allowing other coroutines to continue running in the
backgroud. Normal sleep blocks all execution.
``time`` may be either a number or a time string. Time strings are in
a format such as ``1 day 2 hours 3 minutes 4 seconds 5milliseconds`` or
``1d 2h 3m 4s 5ms``, and they are fully explained in an appendix of
Robot Framework User Guide. Providing a value without specifying minutes
or seconds, defaults to seconds.
Optional `reason` can be used to explain why
sleeping is necessary. Both the time slept and the reason are logged.
Examples:
| Sleep | 42 |
| Sleep | 1.5 |
| Sleep | 2 minutes 10 seconds |
| Sleep | 10s | Wait for a reply |
"""
seconds = timestr_to_secs(time_)
# Python hangs with negative values
if seconds < 0:
seconds = 0
await self._async_sleep_in_parts(seconds)
self.builtIn.log("Slept %s" % secs_to_timestr(seconds))
if reason:
self.builtIn.log(reason)
async def _async_sleep_in_parts(self, seconds):
"""
time.sleep can't be stopped in windows
to ensure that we can signal stop (with timeout)
split sleeping to small pieces
"""
endtime = time.time() + float(seconds)
while True:
remaining = endtime - time.time()
if remaining <= 0:
break
await asyncio.sleep(min(remaining, 0.01))
async def async_create_task(self, name, *args):
"""
Schedules an async keyword to run in background.
If keyword is not async, DataError will be raised.
Because the name of the keyword to execute is given as an argument, it
can be a variable and thus set dynamically, e.g. from a return value of
another keyword or from the command line.
"""
task = self.builtIn.run_keyword(name, *args)
if not inspect.iscoroutine(task):
raise DataError(f"Keyword '{name}' is not async")
return asyncio.create_task(task)
async def async_await_task(self, task):
"""
Get the result from a scheduled async task.
If obj is not a task, DataError will be raised.
"""
if not inspect.isawaitable(task):
raise DataError("Obj is not an async Task")
return await task | /robotframework_asyncio_utils-0.1.6.tar.gz/robotframework_asyncio_utils-0.1.6/AsyncioUtils/AsyncioUtils.py | 0.793906 | 0.619932 | AsyncioUtils.py | pypi |
from robot.running import context
from .listener import AutoRecorderListener
class AutoRecorder(AutoRecorderListener):
'''
AutoRecorder for Robot Framework
RobotFramework library allowing to automatically start video recording of desktop when test or (and) suite starts. Based on [ScreenCapLibrary](https://github.com/mihaiparvu/ScreenCapLibrary)
Usage
------------
To work with the library only importing it is needed. By default video for each test case is created, but it is possible to create video per whole suite or create videos for test cases and for whole suite.
SRAKA
Import arguments can be also used for tuning underlaying ScreenCapLibrary.
------------
TestRecorder.robot
| *** Settings ***
| Documentation This example demonstrates how to use current library. Basic use-case
| Library AutoRecorder
| Library SeleniumLibrary
|
| *** Test Cases ***
| Example Test
| Open Browser http://example.local gc
| Sleep 5s
SuiteRecorder.robot
| *** Settings ***
| Documentation One recording is going to be created for suite
| Library AutoRecorder mode=suite
| Library SeleniumLibrary
|
| *** Test Cases ***
| Example Test
| Open Browser http://example.local gc
| Sleep 5s
SuiteAndTestRecorder.robot
| *** Settings ***
| Documentation One recording will span whole suite, also recordings are going to be created per test
| Library AutoRecorder mode=suite,test
| Library SeleniumLibrary
|
| *** Test Cases ***
| Example Test
| Open Browser http://example.local gc
| Sleep 5s
|
| Example Test 2
| Open Browser http://example.local gc
| Sleep 5s
Choose Tags.robot
| *** Settings ***
| Documentation Only Example Test is going to be recorded, while Example Test 2 not
| Library AutoRecorder mode=test include_tags=record
| Library SeleniumLibrary
|
| *** Test Cases ***
| Example Test
| [Tags] record
| Open Browser http://example.local gc
| Sleep 5s
|
| Example Test 2
| Open Browser http://example.local gc
| Sleep 5s
Exclude Tags.robot
| *** Settings ***
| Documentation Example Test 2 will not be recorded
| Library AutoRecorder mode=test exclude_tags=dont
| Library SeleniumLibrary
|
| *** Test Cases ***
| Example Test
| [Tags] record
| Open Browser http://example.local gc
| Sleep 5s
|
| Example Test 2
| [Tags] dont
| Open Browser http://example.local gc
| Sleep 5s
Set Location.robot
| *** Settings ***
| Documentation Recordings will be located in /tmp directory (built in variables like ${CURDIR}, ${TEST_NAME}, etc can be used here)
| Library AutoRecorder mode=suite screenshot_directory=/tmp
| Library SeleniumLibrary
|
| *** Test Cases ***
| Example Test
| [Tags] record
| Open Browser http://example.local gc
| Sleep 5s
|
| Example Test 2
| [Tags] dont
| Open Browser http://example.local gc
| Sleep 5s
'''
def __init__(self, mode="test", monitor=0, name="recording",
fps=None, size_percentage=1, embed=True, embed_width="800px", screenshot_directory=None,
included_tags=None, excluded_tags=None):
'''
Import Arguments:
mode:
test - for recording opne video per test
suite - for one video per whole suite
suite,test - for both
screenshot_directory - where to put recordings
included_tags - choose tags to record
excluded_tags - choose tags to not to record
monitor, name, fps, size_percentage, embed, embed_with - configuration of underlaying ScreenCapLibrary - see documentation -
https://mihaiparvu.github.io/ScreenCapLibrary/ScreenCapLibrary.html#Start%20Video%20Recording
'''
if context.EXECUTION_CONTEXTS.current:
if context.EXECUTION_CONTEXTS.current.dry_run is False:
super().__init__(mode, monitor, fps, size_percentage, embed, embed_width, screenshot_directory, included_tags, excluded_tags) | /robotframework-autorecorder-0.1.4.tar.gz/robotframework-autorecorder-0.1.4/AutoRecorder/__init__.py | 0.649356 | 0.468851 | __init__.py | pypi |
from AWSLibrary.base.robotlibcore import keyword
from AWSLibrary.base import LibraryComponent, KeywordError, ContinuableError
from botocore.exceptions import ClientError
from robot.api import logger
import botocore
class S3Keywords(LibraryComponent):
@keyword('Create Bucket')
def create_bucket(self, bucket, region=None):
""" Creates S3 Bucket with the name given @param: ```bucket```
in the specified @param: ```region```.
If Bucket already exists, an exception will be thrown.
Example:
| Create Bucket | randomBucketName | us-west-2 |
"""
client = self.state.session.client('s3')
try:
client.create_bucket(Bucket=bucket)
self.logger.debug(f"Created new bucket: {bucket}")
except botocore.exceptions.ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "BucketAlreadyExists":
self.logger.debug(f"Keyword Failed: {error_code}")
raise ContinuableError(f"Keyword Failed: {error_code}")
elif error_code == 'BucketAlreadyOwnedByYou':
self.logger.debug("Bucket Already Exists")
raise ContinuableError("Bucket Already Exists")
else:
self.logger.debug(f"Error Code: {e.response['Error']['Code']}")
@keyword('Delete File')
def delete_file(self, bucket, key):
""" Delete File
Requires: @param ```bucket``` which is the bucket name:
@param: ```key``` which is the bucket location/path name.
Example:
| Delete File | bucket | key |
"""
client = self.state.session.client('s3')
try:
response = client.delete_object(
Bucket=bucket,
Key=key
)
if response['ResponseMetadata']['HTTPStatusCode'] != 204:
raise ContinuableError(f"Error {response['ResponseMetadata']}")
except botocore.exceptions.ClientError as e:
raise KeywordError(e)
@keyword('Download File')
def download_file_from_s3(self, bucket, key, path):
""" Downloads File from S3 Bucket
Requires: @param ```bucket``` which is the bucket name:
@param: ```key``` which is the bucket location/path name.
@param: ```path``` which is the local path of file.
Example:
| Download File | bucket | path | key |
"""
client = self.state.session.client('s3')
try:
client.download_file(bucket, key, path)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == '404':
raise KeywordError(f"Keyword: {bucket} does not exist")
else:
logger.debug(e)
@keyword('Upload File')
def upload_file(self, bucket, key, path):
""" Uploads File from S3 Bucket
Requires: @param ```bucket``` which is the bucket name:
@param: ```key``` which is the bucket location/path name.
@param: ```path``` which is the local path of file.
Example:
| Upload File | bucket | path | key |
"""
client = self.state.session.client('s3')
try:
client.upload_file(path, bucket, key)
response = client.head_object(
Bucket=bucket,
Key=key
)
self.logger.info(response)
except botocore.exceptions.ClientError as e:
if e.response['Error']:
raise KeywordError(e)
else:
raise ContinuableError(e)
@keyword('Key Should Exist')
def key_should_exist(self, bucket, key):
""" Key Should Exist
Description: Checks to see if the file on the s3 bucket exist. If so, the keyword will not fail.
Requires: @param ```bucket``` which is the bucket name:
@param: ```key``` which is the bucket location/path name.
Example:
| Key Should Exist | bucket | key |
"""
client = self.state.session.client("s3")
res = client.head_object(Bucket=bucket, Key=key)
try:
if res['ResponseMetadata']['HTTPStatusCode'] == 404:
raise KeywordError("Key: {}, does not exist".format(key))
except ClientError as e:
raise ContinuableError(e.response['Error'])
return True
@keyword('Key Should Not Exist')
def key_should_not_exist(self, bucket, key):
""" Verifies Key on S3 Bucket Does Not Exist
Description: Checks to see if the file on the s3 bucket exist. If so, the keyword will fail.
Requires: @param ```bucket``` which is the bucket name:
@param: ```key``` which is the bucket location/path name.
Example:
| Key Should Not Exist | bucket | key |
"""
client = self.state.session.client('s3')
self.rb_logger.info(f"Retrieve Client Hanlder: {client}")
try:
res = client.head_object(Bucket=bucket, Key=key)
if res['ResponseMetadata']['HTTPStatusCode'] == 200:
raise KeywordError("Key: {}, already exists".format(key))
except ClientError as e:
raise ContinuableError(e.response['Error'])
return True
@keyword('Allowed Methods')
def allowed_methods(self, bucket, methods=[]):
client = self.state.session.client("s3")
self.rb_logger.info(f"Retrieve Client Hanlder: {client}")
try:
response = client.get_bucket_cors(Bucket=bucket)
obj = response['CORSRules'][0]
aws_methods = obj['AllowedMethods']
assert set(aws_methods) == set(methods)
except ClientError as e:
raise KeywordError(e) | /robotframework-aws-0.0.4.tar.gz/robotframework-aws-0.0.4/src/AWSLibrary/keywords/s3.py | 0.781831 | 0.352118 | s3.py | pypi |
import string
import sys
import random
from .iban import *
from .version import VERSION
class BankAccountNumber:
"""
The Bank Account Number library provides keywords to generate NL specific
bank account numbers that are 9 digits long and comply with the Elf Proef.
Before the introduction of IBAN most of the Dutch bank account numbers adhered
to a mod 11 check, called the Elf proef. This check ensured that simple
mistakes while inputting a bank account number were prevented.
With the introduction of IBAN the mod 11 check became obsolete, as it has
its own mod 97 check. The keywords in this library can generate the old style
account number, or include it in the IBAN format.
This library depends on the work done by Thomas Gunther <tom@toms-cafe.de>
that is able to create the IBAN check digit from it's components: Country
Code, Bank Code and Account Number. This completes the IBAN format:
[Country Code] [Check Digit] [Bank Code] [Account Number]
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
NL_BANK_CODES = ['ABNA', 'ASNB', 'INGB', 'KNAB', 'FVLB', 'RABO', 'TRIO', 'BUNQ', 'RBRB', 'AEGO', 'ASNB']
def generate_NL_Bank_Account_Number(self, total=1):
"""
Generate one or more NL Bank account numbers
This keyword is able to generate one or more Elf Proef compliant account
numbers. This can be of use for systems that have not yet complied with
the SEPA and IBAN standards. It also aids with those systems who may
still have this check in place for the IBAN account number part.
The keyword can be called without any arguments when only a single account
is needed. When multiple account numbers are required the `total` argument
allows to specify the number of accounts that need to be returned. In
this case a list is returned, otherwise a string.
"""
count = 0
accountNumbers = []
"""
This loop is needed even when generating 1 number because the generated
randomly generate number may not be mod 11 valid and a second try is needed.
"""
while (count < int(total)):
bankAccountNumber = ""
bankAccountNumber += str(random.randint(000000000, 999999999))
if bankAccountNumber:
if self.NL_Bank_Account_Check(bankAccountNumber):
count += 1
accountNumbers.append(bankAccountNumber)
"""
Return number as a string, or the list when more than one.
"""
if(len(accountNumbers) > 1):
return accountNumbers
elif(len(accountNumbers)==1):
return accountNumbers[0]
def NL_Bank_Account_Check(self, bankAccountNumber):
"""
Check if a provided number is a valid pre-IBAN Dutch bank account number.
The performed check is a Mod 11 check that is used on bank account
number of 9 or 10 digit length. Account numbers that do not have this
length can not be checked, as the issuing bank did not use this check.
Examples:
Valid: NL Bank Account Check 824043006
Invalid: NL Bank Account Check 824043008
"""
if(len(bankAccountNumber)>8) and (len(bankAccountNumber)<11):
checkDigit = len(bankAccountNumber)
else:
return False
sum = 0
for number in bankAccountNumber:
if number in string.digits:
sum = sum + int(number) * checkDigit
checkDigit = checkDigit - 1
if divmod(sum, 11)[1] == 0:
return True
return False
def generate_IBAN_account_number(self, countryCode='NL', bankCode=None, accountNumber=None):
"""
Generate the IBAN compliant number.
This keyword generates the IBAN check digit from it's components: Country
Code, Bank Code and Account Number and return the result in the IBAN format:
[Country Code] [Check Digit] [Bank Code] [Account Number]
All three arguments are optional. In case none are provided default values
for the Country code and Bank Code are used, and the internal NL account
generator creates the account number. The following examples are all valid
Examples:
Generate IBAN Account Number
Generate IBAN Account Number DE
Generate IBAN Account Number DE 37040044
Generate IBAN Account Number accountNumber=362202583
Generate IBAN Account Number bankCode=INGB
"""
if(accountNumber==None):
accountNumber = str(self.generate_NL_Bank_Account_Number())
if(bankCode==None):
bankCode = random.choice(self.NL_BANK_CODES)
iban = create_iban(countryCode, bankCode, accountNumber)
return iban
def check_IBAN_account_number(self, ibanNumber):
"""
Check if the provided IBAN account number is a valid one.
This keyword takes one input in the form of an IBAN account number. The
response will be either True or False. It checks to see if:
- Country Code: valid code
- Account Number: Length
- Bank Account Number: Length
- Check Digit: validates the check digit calculated across values.
Examples:
Valid: NL67INGB0763159700 True
Invalid: NL68INGB0763159700 False
"""
try:
check_iban(ibanNumber)
return True
except IBANError:
return False | /robotframework_bankaccountnumber-0.3-py3-none-any.whl/BankAccountNumber/BankAccountNumber.py | 0.461017 | 0.458409 | BankAccountNumber.py | pypi |
from functools import reduce
"""iban.py 1.5 - Create or check International Bank Account Numbers (IBAN).
Copyright (C) 2002-2010, Thomas Günther <tom@toms-cafe.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Usage as module:
from iban import *
code, bank, account = "DE", "12345678", "123456789"
try:
iban = create_iban(code, bank, account)
except IBANError, err:
print err
else:
print " Correct IBAN: %s << %s ?? %s %s" % (iban, code, bank, account)
iban = "DE58123456780123456789"
try:
code, checksum, bank, account = check_iban(iban)
except IBANError, err:
print err
else:
print " Correct IBAN: %s >> %s %s %s %s" % (iban, code, checksum,
bank, account)
"""
__all__ = ["create_iban", "check_iban", "IBANError"]
usage = \
"""Create or check International Bank Account Numbers (IBAN).
Usage: iban <iban>
iban <country> <bank/branch> <account>
iban -h | -f | -e | -t
e.g.: iban DE58123456780123456789
iban DE 12345678 123456789
<iban> is the International Bank Account Number (IBAN)
<country> is the Country Code from ISO 3166
<bank/branch> is the Bank/Branch Code part of the IBAN from ISO 13616
<account> is the Account Number including check digits
iban -h prints this message
iban -f prints a table with the country specific iban format
iban -e prints an example for each country
iban -t prints some test data
Information about IBAN are from European Committee for Banking Standards
(www.ecbs.org/iban.htm). IBAN is an ISO standard (ISO 13616: 1997).
"""
class Country:
"""Class for country specific iban data."""
def __init__(self, name, code, bank_form, acc_form):
"""Constructor for Country objects.
Arguments:
name - Name of the country
code - Country Code from ISO 3166
bank_form - Format of bank/branch code part (e.g. "0 4a 0 ")
acc_form - Format of account number part (e.g. "0 11 2n")
"""
self.name = name
self.code = code
self.bank = self._decode_format(bank_form)
self.acc = self._decode_format(acc_form)
def bank_lng(self):
return reduce(lambda sum, part: sum + part[0], self.bank, 0)
def acc_lng(self):
return reduce(lambda sum, part: sum + part[0], self.acc, 0)
def total_lng(self):
return 4 + self.bank_lng() + self.acc_lng()
def _decode_format(self, form):
form_list = []
for part in form.split(" "):
if part:
typ = part[-1]
if typ in ("a", "n"):
part = part[:-1]
else:
typ = "c"
lng = int(part)
form_list.append((lng, typ))
return tuple(form_list)
# BBAN data from ISO 13616, Country codes from ISO 3166 (www.iso.org).
iban_data = (Country("Andorra", "AD", "0 4n 4n", "0 12 0 "),
Country("Albania", "AL", "0 8n 0 ", "0 16 0 "),
Country("Austria", "AT", "0 5n 0 ", "0 11n 0 "),
Country("Bosnia and Herzegovina",
"BA", "0 3n 3n", "0 8n 2n"),
Country("Belgium", "BE", "0 3n 0 ", "0 7n 2n"),
Country("Bulgaria", "BG", "0 4a 4n", "2n 8 0 "),
Country("Switzerland", "CH", "0 5n 0 ", "0 12 0 "),
Country("Cyprus", "CY", "0 3n 5n", "0 16 0 "),
Country("Czech Republic", "CZ", "0 4n 0 ", "0 16n 0 "),
Country("Germany", "DE", "0 8n 0 ", "0 10n 0 "),
Country("Denmark", "DK", "0 4n 0 ", "0 9n 1n"),
Country("Estonia", "EE", "0 2n 0 ", "2n 11n 1n"),
Country("Spain", "ES", "0 4n 4n", "2n 10n 0 "),
Country("Finland", "FI", "0 6n 0 ", "0 7n 1n"),
Country("Faroe Islands", "FO", "0 4n 0 ", "0 9n 1n"),
Country("France", "FR", "0 5n 5n", "0 11 2n"),
Country("United Kingdom", "GB", "0 4a 6n", "0 8n 0 "),
Country("Georgia", "GE", "0 2a 0 ", "0 16n 0 "),
Country("Gibraltar", "GI", "0 4a 0 ", "0 15 0 "),
Country("Greenland", "GL", "0 4n 0 ", "0 9n 1n"),
Country("Greece", "GR", "0 3n 4n", "0 16 0 "),
Country("Croatia", "HR", "0 7n 0 ", "0 10n 0 "),
Country("Hungary", "HU", "0 3n 4n", "1n 15n 1n"),
Country("Ireland", "IE", "0 4a 6n", "0 8n 0 "),
Country("Israel", "IL", "0 3n 3n", "0 13n 0 "),
Country("Iceland", "IS", "0 4n 0 ", "2n 16n 0 "),
Country("Italy", "IT", "1a 5n 5n", "0 12 0 "),
Country("Kuwait", "KW", "0 4a 0 ", "0 22 0 "),
Country("Kazakhstan", "KZ", "0 3n 0 ", "0 13 0 "),
Country("Lebanon", "LB", "0 4n 0 ", "0 20 0 "),
Country("Liechtenstein", "LI", "0 5n 0 ", "0 12 0 "),
Country("Lithuania", "LT", "0 5n 0 ", "0 11n 0 "),
Country("Luxembourg", "LU", "0 3n 0 ", "0 13 0 "),
Country("Latvia", "LV", "0 4a 0 ", "0 13 0 "),
Country("Monaco", "MC", "0 5n 5n", "0 11 2n"),
Country("Montenegro", "ME", "0 3n 0 ", "0 13n 2n"),
Country("Macedonia, Former Yugoslav Republic of",
"MK", "0 3n 0 ", "0 10 2n"),
Country("Mauritania", "MR", "0 5n 5n", "0 11n 2n"),
Country("Malta", "MT", "0 4a 5n", "0 18 0 "),
Country("Mauritius", "MU", "0 4a 4n", "0 15n 3a"),
Country("Netherlands", "NL", "0 4a 0 ", "0 10n 0 "),
Country("Norway", "NO", "0 4n 0 ", "0 6n 1n"),
Country("Poland", "PL", "0 8n 0 ", "0 16n 0 "),
Country("Portugal", "PT", "0 4n 4n", "0 11n 2n"),
Country("Romania", "RO", "0 4a 0 ", "0 16 0 "),
Country("Serbia", "RS", "0 3n 0 ", "0 13n 2n"),
Country("Saudi Arabia", "SA", "0 2n 0 ", "0 18 0 "),
Country("Sweden", "SE", "0 3n 0 ", "0 16n 1n"),
Country("Slovenia", "SI", "0 5n 0 ", "0 8n 2n"),
Country("Slovak Republic",
"SK", "0 4n 0 ", "0 16n 0 "),
Country("San Marino", "SM", "1a 5n 5n", "0 12 0 "),
Country("Tunisia", "TN", "0 2n 3n", "0 13n 2n"),
Country("Turkey", "TR", "0 5n 0 ", "1 16 0 "))
def country_data(code):
"""Search the country code in the iban_data list."""
for country in iban_data:
if country.code == code:
return country
return None
def mod97(digit_string):
"""Modulo 97 for huge numbers given as digit strings.
This function is a prototype for a JavaScript implementation.
In Python this can be done much easier: long(digit_string) % 97.
"""
m = 0
for d in digit_string:
m = (m * 10 + int(d)) % 97
return m
def fill0(s, l):
"""Fill the string with leading zeros until length is reached."""
return str.zfill(s, l)
def strcmp(s1, s2):
"""Compare two strings respecting german umlauts."""
chars = "AaÄäBbCcDdEeFfGgHhIiJjKkLlMmNnOoÖöPpQqRrSsßTtUuÜüVvWwXxYyZz"
lng = min(len(s1), len(s2))
for i in range(lng):
d = chars.find(s1[i]) - chars.find(s2[i]);
if d != 0:
return d
return len(s1) - len(s2)
def country_index_table():
"""Create an index table of the iban_data list sorted by country names."""
tab = range(len(iban_data))
for i in range(len(tab) - 1, 0, -1):
for j in range(i):
if strcmp(iban_data[tab[j]].name, iban_data[tab[j+1]].name) > 0:
t = tab[j]; tab[j] = tab[j+1]; tab[j+1] = t
return tab
def checksum_iban(iban):
"""Calculate 2-digit checksum of an IBAN."""
code = iban[:2]
checksum = iban[2:4]
bban = iban[4:]
# Assemble digit string
digits = ""
for ch in bban.upper():
if ch.isdigit():
digits += ch
else:
digits += str(ord(ch) - ord("A") + 10)
for ch in code:
digits += str(ord(ch) - ord("A") + 10)
digits += checksum
# Calculate checksum
checksum = 98 - mod97(digits)
return fill0(str(checksum), 2)
def fill_account(country, account):
"""Fill the account number part of IBAN with leading zeros."""
return fill0(account, country.acc_lng())
def invalid_part(form_list, iban_part):
"""Check if syntax of the part of IBAN is invalid."""
for lng, typ in form_list:
if lng > len(iban_part):
lng = len(iban_part)
for ch in iban_part[:lng]:
a = ("A" <= ch <= "Z")
n = ch.isdigit()
c = n or a or ("a" <= ch <= "z")
if (not c and typ == "c") or \
(not a and typ == "a") or \
(not n and typ == "n"):
return 1
iban_part = iban_part[lng:]
return 0
def invalid_bank(country, bank):
"""Check if syntax of the bank/branch code part of IBAN is invalid."""
return len(bank) != country.bank_lng() or \
invalid_part(country.bank, bank)
def invalid_account(country, account):
"""Check if syntax of the account number part of IBAN is invalid."""
return len(account) > country.acc_lng() or \
invalid_part(country.acc, fill_account(country, account))
def calc_iban(country, bank, account, alternative = 0):
"""Calculate the checksum and assemble the IBAN."""
account = fill_account(country, account)
checksum = checksum_iban(country.code + "00" + bank + account)
if alternative:
checksum = fill0(str(mod97(checksum)), 2)
return country.code + checksum + bank + account
def iban_okay(iban):
"""Check the checksum of an IBAN."""
return checksum_iban(iban) == "97"
class IBANError(Exception):
def __init__(self, errmsg):
Exception.__init__(self, errmsg)
def create_iban(code, bank, account, alternative = 0):
"""Check the input, calculate the checksum and assemble the IBAN.
Return the calculated IBAN.
Return the alternative IBAN if alternative is true.
Raise an IBANError exception if the input is not correct.
"""
err = None
country = country_data(code)
if not country:
err = "Unknown Country Code: %s" % code
elif len(bank) != country.bank_lng():
err = "Bank/Branch Code length %s is not correct for %s (%s)" % \
(len(bank), country.name, country.bank_lng())
elif invalid_bank(country, bank):
err = "Bank/Branch Code %s is not correct for %s" % \
(bank, country.name)
elif len(account) > country.acc_lng():
err = "Account Number length %s is not correct for %s (%s)" % \
(len(account), country.name, country.acc_lng())
elif invalid_account(country, account):
err = "Account Number %s is not correct for %s" % \
(account, country.name)
if err:
raise IBANError(err)
return calc_iban(country, bank, account, alternative)
def check_iban(iban):
"""Check the syntax and the checksum of an IBAN.
Return the parts of the IBAN: Country Code, Checksum, Bank/Branch Code and
Account number.
Raise an IBANError exception if the input is not correct.
"""
err = None
code = iban[:2]
checksum = iban[2:4]
bban = iban[4:]
country = country_data(code)
if not country:
err = "Unknown Country Code: %s" % code
elif len(iban) != country.total_lng():
err = "IBAN length %s is not correct for %s (%s)" % \
(len(iban), country.name, country.total_lng())
else:
bank_lng = country.bank_lng()
bank = bban[:bank_lng]
account = bban[bank_lng:]
if invalid_bank(country, bank):
err = "Bank/Branch Code %s is not correct for %s" % \
(bank, country.name)
elif invalid_account(country, account):
err = "Account Number %s is not correct for %s" % \
(account, country.name)
elif not(checksum.isdigit()):
err = "IBAN Checksum %s is not numeric" % checksum
elif not iban_okay(iban):
err = "Incorrect IBAN: %s >> %s %s %s %s" % \
(iban, code, checksum, bank, account)
if err:
raise IBANError(err)
return code, checksum, bank, account
def print_new_iban(code, bank, account):
"""Check the input, calculate the checksum, assemble and print the IBAN."""
try:
iban = create_iban(code, bank, account)
except IBANError as err:
print(err)
return ""
print(" Correct IBAN: %s << %s ?? %s %s" % (iban, code, bank, account))
return iban
def print_iban_parts(iban):
"""Check the syntax and the checksum of an IBAN and print the parts."""
try:
code, checksum, bank, account = check_iban(iban)
except IBANError as err:
print(err)
return ()
print(" Correct IBAN: %s >> %s %s %s %s" % (iban, code, checksum,
bank, account))
return code, checksum, bank, account
def print_format():
"""Print a table with the country specific iban format."""
print("IBAN-Format (a = A-Z, n = 0-9, c = A-Z/a-z/0-9):")
print( " | Bank/Branch-Code | Account Number")
print( " Country Code | check1 bank branch |" + \
" check2 number check3")
print("--------------------|-----------------------|" + \
"---------------------")
for idx in country_index_table():
country = iban_data[idx]
if len(country.name) <= 14:
print(country.name.ljust(14), "|", country.code, "|",)
else:
print(country.name)
print(" |", country.code, "|",)
for lng, typ in country.bank:
if lng:
print(str(lng).rjust(3), typ.ljust(2),)
else:
print(" - ",)
print(" |",)
for lng, typ in country.acc:
if lng:
print(str(lng).rjust(3), typ.ljust(2),)
else:
print(" - ",)
print
def print_test_data(*data):
"""Print a table with iban test data."""
for code, bank, account, checksum in data:
created_iban = print_new_iban(code, bank, account)
if created_iban:
iban = code + checksum + bank + \
fill_account(country_data(code), account)
print_iban_parts(iban)
if iban != created_iban:
if iban == create_iban(code, bank, account, 1):
print(" Alternative IBAN")
else:
print(" Changed IBAN")
def print_examples():
print("IBAN-Examples:")
print_test_data(("AD", "00012030", "200359100100", "12"),
("AL", "21211009", "0000000235698741", "47"),
("AT", "19043", "00234573201", "61"),
("BA", "129007", "9401028494", "39"),
("BE", "539", "007547034", "68"),
("BG", "BNBG9661", "1020345678", "80"),
("CH", "00762", "011623852957", "93"),
("CY", "00200128", "0000001200527600", "17"),
("CZ", "0800", "0000192000145399", "65"),
("DE", "37040044", "0532013000", "89"),
("DK", "0040", "0440116243", "50"),
("EE", "22", "00221020145685", "38"),
("ES", "21000418", "450200051332", "91"),
("FI", "123456", "00000785", "21"),
("FO", "6460", "0001631634", "62"),
("FR", "2004101005", "0500013M02606", "14"),
("GB", "NWBK601613", "31926819", "29"),
("GE", "NB", "0000000101904917", "29"),
("GI", "NWBK", "000000007099453", "75"),
("GL", "6471", "0001000206", "89"),
("GR", "0110125", "0000000012300695", "16"),
("HR", "1001005", "1863000160", "12"),
("HU", "1177301", "61111101800000000", "42"),
("IE", "AIBK931152", "12345678", "29"),
("IL", "010800", "0000099999999", "62"),
("IS", "0159", "260076545510730339", "14"),
("IT", "X0542811101", "000000123456", "60"),
("KW", "CBKU", "0000000000001234560101", "81"),
("KZ", "125", "KZT5004100100", "86"),
("LB", "0999", "00000001001901229114", "62"),
("LI", "08810", "0002324013AA", "21"),
("LT", "10000", "11101001000", "12"),
("LU", "001", "9400644750000", "28"),
("LV", "BANK", "0000435195001", "80"),
("MC", "1273900070", "0011111000h79", "11"),
("ME", "505", "000012345678951", "25"),
("MK", "250", "120000058984", "07"),
("MR", "0002000101", "0000123456753", "13"),
("MT", "MALT01100", "0012345MTLCAST001S", "84"),
("MU", "BOMM0101", "101030300200000MUR", "17"),
("NL", "ABNA", "0417164300", "91"),
("NO", "8601", "1117947", "93"),
("PL", "10901014", "0000071219812874", "61"),
("PT", "00020123", "1234567890154", "50"),
("RO", "AAAA", "1B31007593840000", "49"),
("RS", "260", "005601001611379", "35"),
("SA", "80", "000000608010167519", "03"),
("SE", "500", "00000058398257466", "45"),
("SI", "19100", "0000123438", "56"),
("SK", "1200", "0000198742637541", "31"),
("SM", "U0322509800", "000000270100", "86"),
("TN", "10006", "035183598478831", "59"),
("TR", "00061", "00519786457841326", "33"))
def print_test():
print("IBAN-Test:")
print_test_data(("XY", "1", "2", "33"),
("AD", "11112222", "C3C3C3C3C3C3", "11"),
("AD", "1111222", "C3C3C3C3C3C3", "11"),
("AD", "X1112222", "C3C3C3C3C3C3", "11"),
("AD", "111@2222", "C3C3C3C3C3C3", "11"),
("AD", "1111X222", "C3C3C3C3C3C3", "11"),
("AD", "1111222@", "C3C3C3C3C3C3", "11"),
("AD", "11112222", "@3C3C3C3C3C3", "11"),
("AD", "11112222", "C3C3C3C3C3C@", "11"),
("AL", "11111111", "B2B2B2B2B2B2B2B2", "54"),
("AL", "1111111", "B2B2B2B2B2B2B2B2", "54"),
("AL", "X1111111", "B2B2B2B2B2B2B2B2", "54"),
("AL", "1111111@", "B2B2B2B2B2B2B2B2", "54"),
("AL", "11111111", "@2B2B2B2B2B2B2B2", "54"),
("AL", "11111111", "B2B2B2B2B2B2B2B@", "54"),
("AT", "11111", "22222222222", "17"),
("AT", "1111", "22222222222", "17"),
("AT", "X1111", "22222222222", "17"),
("AT", "1111@", "22222222222", "17"),
("AT", "11111", "X2222222222", "17"),
("AT", "11111", "2222222222@", "17"),
("BA", "111222", "3333333344", "79"),
("BA", "11122", "3333333344", "79"),
("BA", "X11222", "3333333344", "79"),
("BA", "11@222", "3333333344", "79"),
("BA", "111X22", "3333333344", "79"),
("BA", "11122@", "3333333344", "79"),
("BA", "111222", "X333333344", "79"),
("BA", "111222", "3333333@44", "79"),
("BA", "111222", "33333333X4", "79"),
("BA", "111222", "333333334@", "79"),
("BE", "111", "222222233", "93"),
("BE", "11", "222222233", "93"),
("BE", "X11", "222222233", "93"),
("BE", "11@", "222222233", "93"),
("BE", "111", "X22222233", "93"),
("BE", "111", "222222@33", "93"),
("BE", "111", "2222222X3", "93"),
("BE", "111", "22222223@", "93"),
("BG", "AAAA2222", "33D4D4D4D4", "20"),
("BG", "AAAA222", "33D4D4D4D4", "20"),
("BG", "8AAA2222", "33D4D4D4D4", "20"),
("BG", "AAA@2222", "33D4D4D4D4", "20"),
("BG", "AAAAX222", "33D4D4D4D4", "20"),
("BG", "AAAA222@", "33D4D4D4D4", "20"),
("BG", "AAAA2222", "X3D4D4D4D4", "20"),
("BG", "AAAA2222", "3@D4D4D4D4", "20"),
("BG", "AAAA2222", "33@4D4D4D4", "20"),
("BG", "AAAA2222", "33D4D4D4D@", "20"),
("CH", "11111", "B2B2B2B2B2B2", "60"),
("CH", "1111", "B2B2B2B2B2B2", "60"),
("CH", "X1111", "B2B2B2B2B2B2", "60"),
("CH", "1111@", "B2B2B2B2B2B2", "60"),
("CH", "11111", "@2B2B2B2B2B2", "60"),
("CH", "11111", "B2B2B2B2B2B@", "60"),
("CY", "11122222", "C3C3C3C3C3C3C3C3", "29"),
("CY", "1112222", "C3C3C3C3C3C3C3C3", "29"),
("CY", "X1122222", "C3C3C3C3C3C3C3C3", "29"),
("CY", "11@22222", "C3C3C3C3C3C3C3C3", "29"),
("CY", "111X2222", "C3C3C3C3C3C3C3C3", "29"),
("CY", "1112222@", "C3C3C3C3C3C3C3C3", "29"),
("CY", "11122222", "@3C3C3C3C3C3C3C3", "29"),
("CY", "11122222", "C3C3C3C3C3C3C3C@", "29"),
("CZ", "1111", "2222222222222222", "68"),
("CZ", "111", "2222222222222222", "68"),
("CZ", "X111", "2222222222222222", "68"),
("CZ", "111@", "2222222222222222", "68"),
("CZ", "1111", "X222222222222222", "68"),
("CZ", "1111", "222222222222222@", "68"),
("DE", "11111111", "2222222222", "16"),
("DE", "1111111", "2222222222", "16"),
("DE", "X1111111", "2222222222", "16"),
("DE", "1111111@", "2222222222", "16"),
("DE", "11111111", "X222222222", "16"),
("DE", "11111111", "222222222@", "16"),
("DK", "1111", "2222222223", "79"),
("DK", "111", "2222222223", "79"),
("DK", "X111", "2222222223", "79"),
("DK", "111@", "2222222223", "79"),
("DK", "1111", "X222222223", "79"),
("DK", "1111", "22222222@3", "79"),
("DK", "1111", "222222222X", "79"),
("EE", "11", "22333333333334", "96"),
("EE", "1", "22333333333334", "96"),
("EE", "X1", "22333333333334", "96"),
("EE", "1@", "22333333333334", "96"),
("EE", "11", "X2333333333334", "96"),
("EE", "11", "2@333333333334", "96"),
("EE", "11", "22X33333333334", "96"),
("EE", "11", "223333333333@4", "96"),
("EE", "11", "2233333333333X", "96"),
("ES", "11112222", "334444444444", "71"),
("ES", "1111222", "334444444444", "71"),
("ES", "X1112222", "334444444444", "71"),
("ES", "111@2222", "334444444444", "71"),
("ES", "1111X222", "334444444444", "71"),
("ES", "1111222@", "334444444444", "71"),
("ES", "11112222", "X34444444444", "71"),
("ES", "11112222", "3@4444444444", "71"),
("ES", "11112222", "33X444444444", "71"),
("ES", "11112222", "33444444444@", "71"),
("FI", "111111", "22222223", "68"),
("FI", "11111", "22222223", "68"),
("FI", "X11111", "22222223", "68"),
("FI", "11111@", "22222223", "68"),
("FI", "111111", "X2222223", "68"),
("FI", "111111", "222222@3", "68"),
("FI", "111111", "2222222X", "68"),
("FO", "1111", "2222222223", "49"),
("FO", "111", "2222222223", "49"),
("FO", "X111", "2222222223", "49"),
("FO", "111@", "2222222223", "49"),
("FO", "1111", "X222222223", "49"),
("FO", "1111", "22222222@3", "49"),
("FO", "1111", "222222222X", "49"),
("FR", "1111122222", "C3C3C3C3C3C44", "44"),
("FR", "111112222", "C3C3C3C3C3C44", "44"),
("FR", "X111122222", "C3C3C3C3C3C44", "44"),
("FR", "1111@22222", "C3C3C3C3C3C44", "44"),
("FR", "11111X2222", "C3C3C3C3C3C44", "44"),
("FR", "111112222@", "C3C3C3C3C3C44", "44"),
("FR", "1111122222", "@3C3C3C3C3C44", "44"),
("FR", "1111122222", "C3C3C3C3C3@44", "44"),
("FR", "1111122222", "C3C3C3C3C3CX4", "44"),
("FR", "1111122222", "C3C3C3C3C3C4@", "44"),
("GB", "AAAA222222", "33333333", "45"),
("GB", "AAAA22222", "33333333", "45"),
("GB", "8AAA222222", "33333333", "45"),
("GB", "AAA@222222", "33333333", "45"),
("GB", "AAAAX22222", "33333333", "45"),
("GB", "AAAA22222@", "33333333", "45"),
("GB", "AAAA222222", "X3333333", "45"),
("GB", "AAAA222222", "3333333@", "45"),
("GE", "AA", "2222222222222222", "98"),
("GE", "A", "2222222222222222", "98"),
("GE", "8A", "2222222222222222", "98"),
("GE", "A@", "2222222222222222", "98"),
("GE", "AA", "X222222222222222", "98"),
("GE", "AA", "222222222222222@", "98"))
print_test_data(("GI", "AAAA", "B2B2B2B2B2B2B2B", "72"),
("GI", "AAA", "B2B2B2B2B2B2B2B", "72"),
("GI", "8AAA", "B2B2B2B2B2B2B2B", "72"),
("GI", "AAA@", "B2B2B2B2B2B2B2B", "72"),
("GI", "AAAA", "@2B2B2B2B2B2B2B", "72"),
("GI", "AAAA", "B2B2B2B2B2B2B2@", "72"),
("GL", "1111", "2222222223", "49"),
("GL", "111", "2222222223", "49"),
("GL", "X111", "2222222223", "49"),
("GL", "111@", "2222222223", "49"),
("GL", "1111", "X222222223", "49"),
("GL", "1111", "22222222@3", "49"),
("GL", "1111", "222222222X", "49"),
("GR", "1112222", "C3C3C3C3C3C3C3C3", "61"),
("GR", "111222", "C3C3C3C3C3C3C3C3", "61"),
("GR", "X112222", "C3C3C3C3C3C3C3C3", "61"),
("GR", "11@2222", "C3C3C3C3C3C3C3C3", "61"),
("GR", "111X222", "C3C3C3C3C3C3C3C3", "61"),
("GR", "111222@", "C3C3C3C3C3C3C3C3", "61"),
("GR", "1112222", "@3C3C3C3C3C3C3C3", "61"),
("GR", "1112222", "C3C3C3C3C3C3C3C@", "61"),
("HR", "1111111", "2222222222", "94"),
("HR", "111111", "2222222222", "94"),
("HR", "X111111", "2222222222", "94"),
("HR", "111111@", "2222222222", "94"),
("HR", "1111111", "X222222222", "94"),
("HR", "1111111", "222222222@", "94"),
("HU", "1112222", "34444444444444445", "35"),
("HU", "111222", "34444444444444445", "35"),
("HU", "X112222", "34444444444444445", "35"),
("HU", "11@2222", "34444444444444445", "35"),
("HU", "111X222", "34444444444444445", "35"),
("HU", "111222@", "34444444444444445", "35"),
("HU", "1112222", "X4444444444444445", "35"),
("HU", "1112222", "3X444444444444445", "35"),
("HU", "1112222", "344444444444444@5", "35"),
("HU", "1112222", "3444444444444444X", "35"),
("IE", "AAAA222222", "33333333", "18"),
("IE", "AAAA22222", "33333333", "18"),
("IE", "8AAA222222", "33333333", "18"),
("IE", "AAA@222222", "33333333", "18"),
("IE", "AAAAX22222", "33333333", "18"),
("IE", "AAAA22222@", "33333333", "18"),
("IE", "AAAA222222", "X3333333", "18"),
("IE", "AAAA222222", "3333333@", "18"),
("IL", "111222", "3333333344", "64"),
("IL", "11122", "3333333344", "64"),
("IL", "X11222", "3333333344", "64"),
("IL", "11@222", "3333333344", "64"),
("IL", "111X22", "3333333344", "64"),
("IL", "11122@", "3333333344", "64"),
("IL", "111222", "X333333333333", "64"),
("IL", "111222", "333333333333@", "64"),
("IS", "1111", "223333333333333333", "12"),
("IS", "111", "223333333333333333", "12"),
("IS", "X111", "223333333333333333", "12"),
("IS", "111@", "223333333333333333", "12"),
("IS", "1111", "X23333333333333333", "12"),
("IS", "1111", "2@3333333333333333", "12"),
("IS", "1111", "22X333333333333333", "12"),
("IS", "1111", "22333333333333333@", "12"),
("IT", "A2222233333", "D4D4D4D4D4D4", "43"),
("IT", "A222223333", "D4D4D4D4D4D4", "43"),
("IT", "82222233333", "D4D4D4D4D4D4", "43"),
("IT", "AX222233333", "D4D4D4D4D4D4", "43"),
("IT", "A2222@33333", "D4D4D4D4D4D4", "43"),
("IT", "A22222X3333", "D4D4D4D4D4D4", "43"),
("IT", "A222223333@", "D4D4D4D4D4D4", "43"),
("IT", "A2222233333", "@4D4D4D4D4D4", "43"),
("IT", "A2222233333", "D4D4D4D4D4D@", "43"),
("KW", "AAAA", "B2B2B2B2B2B2B2B2B2B2B2", "93"),
("KW", "AAA", "B2B2B2B2B2B2B2B2B2B2B2", "93"),
("KW", "8AAA", "B2B2B2B2B2B2B2B2B2B2B2", "93"),
("KW", "AAA@", "B2B2B2B2B2B2B2B2B2B2B2", "93"),
("KW", "AAAA", "@2B2B2B2B2B2B2B2B2B2B2", "93"),
("KW", "AAAA", "B2B2B2B2B2B2B2B2B2B2B@", "93"),
("KZ", "111", "B2B2B2B2B2B2B", "21"),
("KZ", "11", "B2B2B2B2B2B2B", "21"),
("KZ", "X11", "B2B2B2B2B2B2B", "21"),
("KZ", "11@", "B2B2B2B2B2B2B", "21"),
("KZ", "111", "@2B2B2B2B2B2B", "21"),
("KZ", "111", "B2B2B2B2B2B2@", "21"),
("LB", "1111", "B2B2B2B2B2B2B2B2B2B2", "88"),
("LB", "111", "B2B2B2B2B2B2B2B2B2B2", "88"),
("LB", "X111", "B2B2B2B2B2B2B2B2B2B2", "88"),
("LB", "111@", "B2B2B2B2B2B2B2B2B2B2", "88"),
("LB", "1111", "@2B2B2B2B2B2B2B2B2B2", "88"),
("LB", "1111", "B2B2B2B2B2B2B2B2B2B@", "88"),
("LI", "11111", "B2B2B2B2B2B2", "73"),
("LI", "1111", "B2B2B2B2B2B2", "73"),
("LI", "X1111", "B2B2B2B2B2B2", "73"),
("LI", "1111@", "B2B2B2B2B2B2", "73"),
("LI", "11111", "@2B2B2B2B2B2", "73"),
("LI", "11111", "B2B2B2B2B2B@", "73"),
("LT", "11111", "22222222222", "15"),
("LT", "1111", "22222222222", "15"),
("LT", "X1111", "22222222222", "15"),
("LT", "1111@", "22222222222", "15"),
("LT", "11111", "X2222222222", "15"),
("LT", "11111", "2222222222@", "15"),
("LU", "111", "B2B2B2B2B2B2B", "27"),
("LU", "11", "B2B2B2B2B2B2B", "27"),
("LU", "X11", "B2B2B2B2B2B2B", "27"),
("LU", "11@", "B2B2B2B2B2B2B", "27"),
("LU", "111", "@2B2B2B2B2B2B", "27"),
("LU", "111", "B2B2B2B2B2B2@", "27"),
("LV", "AAAA", "B2B2B2B2B2B2B", "86"),
("LV", "AAA", "B2B2B2B2B2B2B", "86"),
("LV", "8AAA", "B2B2B2B2B2B2B", "86"),
("LV", "AAA@", "B2B2B2B2B2B2B", "86"),
("LV", "AAAA", "@2B2B2B2B2B2B", "86"),
("LV", "AAAA", "B2B2B2B2B2B2@", "86"),
("MC", "1111122222", "C3C3C3C3C3C44", "26"),
("MC", "111112222", "C3C3C3C3C3C44", "26"),
("MC", "X111122222", "C3C3C3C3C3C44", "26"),
("MC", "1111@22222", "C3C3C3C3C3C44", "26"),
("MC", "11111X2222", "C3C3C3C3C3C44", "26"),
("MC", "111112222@", "C3C3C3C3C3C44", "26"),
("MC", "1111122222", "@3C3C3C3C3C44", "26"),
("MC", "1111122222", "C3C3C3C3C3@44", "26"),
("MC", "1111122222", "C3C3C3C3C3CX4", "26"),
("MC", "1111122222", "C3C3C3C3C3C4@", "26"),
("ME", "111", "222222222222233", "38"),
("ME", "11", "222222222222233", "38"),
("ME", "X11", "222222222222233", "38"),
("ME", "11@", "222222222222233", "38"),
("ME", "111", "X22222222222233", "38"),
("ME", "111", "222222222222@33", "38"),
("ME", "111", "2222222222222X3", "38"),
("ME", "111", "22222222222223@", "38"),
("MK", "111", "B2B2B2B2B233", "41"),
("MK", "11", "B2B2B2B2B233", "41"),
("MK", "X11", "B2B2B2B2B233", "41"),
("MK", "11@", "B2B2B2B2B233", "41"),
("MK", "111", "@2B2B2B2B233", "41"),
("MK", "111", "B2B2B2B2B@33", "41"),
("MK", "111", "B2B2B2B2B2X3", "41"),
("MK", "111", "B2B2B2B2B23@", "41"),
("MR", "1111122222", "3333333333344", "21"),
("MR", "111112222", "3333333333344", "21"),
("MR", "X111122222", "3333333333344", "21"),
("MR", "1111@22222", "3333333333344", "21"),
("MR", "11111X2222", "3333333333344", "21"),
("MR", "111112222@", "3333333333344", "21"),
("MR", "1111122222", "X333333333344", "21"),
("MR", "1111122222", "3333333333@44", "21"),
("MR", "1111122222", "33333333333X4", "21"),
("MR", "1111122222", "333333333334@", "21"),
("MT", "AAAA22222", "C3C3C3C3C3C3C3C3C3", "39"),
("MT", "AAAA2222", "C3C3C3C3C3C3C3C3C3", "39"),
("MT", "8AAA22222", "C3C3C3C3C3C3C3C3C3", "39"),
("MT", "AAA@22222", "C3C3C3C3C3C3C3C3C3", "39"),
("MT", "AAAAX2222", "C3C3C3C3C3C3C3C3C3", "39"),
("MT", "AAAA2222@", "C3C3C3C3C3C3C3C3C3", "39"),
("MT", "AAAA22222", "@3C3C3C3C3C3C3C3C3", "39"),
("MT", "AAAA22222", "C3C3C3C3C3C3C3C3C@", "39"))
print_test_data(("MU", "AAAA2222", "333333333333333DDD", "37"),
("MU", "AAAA222", "333333333333333DDD", "37"),
("MU", "8AAA2222", "333333333333333DDD", "37"),
("MU", "AAA@2222", "333333333333333DDD", "37"),
("MU", "AAAAX222", "333333333333333DDD", "37"),
("MU", "AAAA222@", "333333333333333DDD", "37"),
("MU", "AAAA2222", "X33333333333333DDD", "37"),
("MU", "AAAA2222", "33333333333333@DDD", "37"),
("MU", "AAAA2222", "3333333333333338DD", "37"),
("MU", "AAAA2222", "333333333333333DD@", "37"),
("NL", "AAAA", "2222222222", "57"),
("NL", "AAA", "2222222222", "57"),
("NL", "8AAA", "2222222222", "57"),
("NL", "AAA@", "2222222222", "57"),
("NL", "AAAA", "X222222222", "57"),
("NL", "AAAA", "222222222@", "57"),
("NO", "1111", "2222223", "40"),
("NO", "111", "2222223", "40"),
("NO", "X111", "2222223", "40"),
("NO", "111@", "2222223", "40"),
("NO", "1111", "X222223", "40"),
("NO", "1111", "22222@3", "40"),
("NO", "1111", "222222X", "40"),
("PL", "11111111", "2222222222222222", "84"),
("PL", "1111111", "2222222222222222", "84"),
("PL", "X1111111", "2222222222222222", "84"),
("PL", "1111111@", "2222222222222222", "84"),
("PL", "11111111", "X222222222222222", "84"),
("PL", "11111111", "222222222222222@", "84"),
("PT", "11112222", "3333333333344", "59"),
("PT", "1111222", "3333333333344", "59"),
("PT", "X1112222", "3333333333344", "59"),
("PT", "111@2222", "3333333333344", "59"),
("PT", "1111X222", "3333333333344", "59"),
("PT", "1111222@", "3333333333344", "59"),
("PT", "11112222", "X333333333344", "59"),
("PT", "11112222", "3333333333@44", "59"),
("PT", "11112222", "33333333333X4", "59"),
("PT", "11112222", "333333333334@", "59"),
("RO", "AAAA", "B2B2B2B2B2B2B2B2", "91"),
("RO", "AAA", "B2B2B2B2B2B2B2B2", "91"),
("RO", "8AAA", "B2B2B2B2B2B2B2B2", "91"),
("RO", "AAA@", "B2B2B2B2B2B2B2B2", "91"),
("RO", "AAAA", "@2B2B2B2B2B2B2B2", "91"),
("RO", "AAAA", "B2B2B2B2B2B2B2B@", "91"),
("RS", "111", "222222222222233", "48"),
("RS", "11", "222222222222233", "48"),
("RS", "X11", "222222222222233", "48"),
("RS", "11@", "222222222222233", "48"),
("RS", "111", "X22222222222233", "48"),
("RS", "111", "222222222222@33", "48"),
("RS", "111", "2222222222222X3", "48"),
("RS", "111", "22222222222223@", "48"),
("SA", "11", "B2B2B2B2B2B2B2B2B2", "46"),
("SA", "1", "B2B2B2B2B2B2B2B2B2", "46"),
("SA", "X1", "B2B2B2B2B2B2B2B2B2", "46"),
("SA", "1@", "B2B2B2B2B2B2B2B2B2", "46"),
("SA", "11", "@2B2B2B2B2B2B2B2B2", "46"),
("SA", "11", "B2B2B2B2B2B2B2B2B@", "46"),
("SE", "111", "22222222222222223", "32"),
("SE", "11", "22222222222222223", "32"),
("SE", "X11", "22222222222222223", "32"),
("SE", "11@", "22222222222222223", "32"),
("SE", "111", "X2222222222222223", "32"),
("SE", "111", "222222222222222@3", "32"),
("SE", "111", "2222222222222222X", "32"),
("SI", "11111", "2222222233", "92"),
("SI", "1111", "2222222233", "92"),
("SI", "X1111", "2222222233", "92"),
("SI", "1111@", "2222222233", "92"),
("SI", "11111", "X222222233", "92"),
("SI", "11111", "2222222@33", "92"),
("SI", "11111", "22222222X3", "92"),
("SI", "11111", "222222223@", "92"),
("SK", "1111", "2222222222222222", "66"),
("SK", "111", "2222222222222222", "66"),
("SK", "X111", "2222222222222222", "66"),
("SK", "111@", "2222222222222222", "66"),
("SK", "1111", "X222222222222222", "66"),
("SK", "1111", "222222222222222@", "66"),
("SM", "A2222233333", "D4D4D4D4D4D4", "71"),
("SM", "A222223333", "D4D4D4D4D4D4", "71"),
("SM", "82222233333", "D4D4D4D4D4D4", "71"),
("SM", "AX222233333", "D4D4D4D4D4D4", "71"),
("SM", "A2222@33333", "D4D4D4D4D4D4", "71"),
("SM", "A22222X3333", "D4D4D4D4D4D4", "71"),
("SM", "A222223333@", "D4D4D4D4D4D4", "71"),
("SM", "A2222233333", "@4D4D4D4D4D4", "71"),
("SM", "A2222233333", "D4D4D4D4D4D@", "71"),
("TN", "11222", "333333333333344", "23"),
("TN", "1122", "333333333333344", "23"),
("TN", "X1222", "333333333333344", "23"),
("TN", "1@222", "333333333333344", "23"),
("TN", "11X22", "333333333333344", "23"),
("TN", "1122@", "333333333333344", "23"),
("TN", "11222", "X33333333333344", "23"),
("TN", "11222", "333333333333@44", "23"),
("TN", "11222", "3333333333333X4", "23"),
("TN", "11222", "33333333333334@", "23"),
("TR", "11111", "BC3C3C3C3C3C3C3C3", "95"),
("TR", "1111", "BC3C3C3C3C3C3C3C3", "95"),
("TR", "X1111", "BC3C3C3C3C3C3C3C3", "95"),
("TR", "1111@", "BC3C3C3C3C3C3C3C3", "95"),
("TR", "11111", "@C3C3C3C3C3C3C3C3", "95"),
("TR", "11111", "B@3C3C3C3C3C3C3C3", "95"),
("TR", "11111", "BC3C3C3C3C3C3C3C@", "95"),
("DE", "12345678", "5", "06"),
("DE", "12345678", "16", "97"),
("DE", "12345678", "16", "00"),
("DE", "12345678", "95", "98"),
("DE", "12345678", "95", "01"))
# Main program (executed unless imported as module)
if __name__ == "__main__":
import sys
if len(sys.argv) == 4:
print_new_iban(sys.argv[1], sys.argv[2], sys.argv[3])
elif len(sys.argv) == 2 and sys.argv[1][0] != "-":
print_iban_parts(sys.argv[1])
elif "-f" in sys.argv[1:2]:
print_format()
elif "-e" in sys.argv[1:2]:
print_examples()
elif "-t" in sys.argv[1:2]:
print_test()
else:
print(usage) | /robotframework_bankaccountnumber-0.3-py3-none-any.whl/BankAccountNumber/iban.py | 0.600774 | 0.186929 | iban.py | pypi |
import os
import robot
import robot.utils
from BJRobot.utilities.system import System
from keywordgroup import KeywordGroup
class Screenshot(KeywordGroup):
def __init__(self):
self._screenshot_index = {}
self._screenshot_path_stack = []
self.screenshot_root_directory = None
# Public
def capture_page_screenshot(self, filename='selenium-screenshot-{index}.png'):
"""Takes a screenshot of the current page and embeds it into the log.
``filename`` argument specifies the name of the file to write the
screenshot into. If no ``filename`` is given, the screenshot is saved
into file _selenium-screenshot-{index}.png_ under the directory where
the Robot Framework log file is written into. The ``filename`` is
also considered relative to the same directory, if it is not
given in absolute format. If an absolute or relative path is given
but the path does not exist it will be created.
Example 1:
| ${file1} = | Capture Page Screenshot |
| File Should Exist | ${OUTPUTDIR}${/}selenium-screenshot-1.png |
| Should Be Equal | ${file1} | ${OUTPUTDIR}${/}selenium-screenshot-1.png |
| ${file2} = | Capture Page Screenshot |
| File Should Exist | ${OUTPUTDIR}${/}selenium-screenshot-2.png |
| Should Be Equal | ${file2} | ${OUTPUTDIR}${/}selenium-screenshot-2.png |
Example 2:
| ${file1} = | Capture Page Screenshot | ${OTHER_DIR}${/}other-{index}-name.png |
| ${file2} = | Capture Page Screenshot | ${OTHER_DIR}${/}some-other-name-{index}.png |
| ${file3} = | Capture Page Screenshot | ${OTHER_DIR}${/}other-{index}-name.png |
| File Should Exist | ${OTHER_DIR}${/}other-1-name.png |
| Should Be Equal | ${file1} | ${OTHER_DIR}${/}other-1-name.png |
| File Should Exist | ${OTHER_DIR}${/}some-other-name-1.png |
| Should Be Equal | ${file2} | ${OTHER_DIR}${/}some-other-name-1.png |
| File Should Exist | ${OTHER_DIR}${/}other-2-name.png |
| Should Be Equal | ${file3} | ${OTHER_DIR}${/}other-2-name.png |
Example 3:
| Capture Page Screenshot | ${OTHER_DIR}${/}sc-{index:06}.png |
| File Should Exist | ${OTHER_DIR}${/}sc-000001.png |
"""
path, link = self._get_screenshot_paths(filename)
System.create_directory(path)
if hasattr(self._current_browser(), 'get_screenshot_as_file'):
if not self._current_browser().get_screenshot_as_file(path):
raise RuntimeError('Failed to save screenshot ' + link)
else:
if not self._current_browser().save_screenshot(path):
raise RuntimeError('Failed to save screenshot ' + link)
# Image is shown on its own row and thus prev row is closed on purpose
self._html('</td></tr><tr><td colspan="3"><a href="%s">'
'<img src="%s" width="800px"></a>' % (link, link))
return path
# Private
def _get_screenshot_directory(self):
# Use screenshot root directory if set
if self.screenshot_root_directory is not None:
return self.screenshot_root_directory
# Otherwise use RF's log directory
return self._get_log_dir()
# should only be called by set_screenshot_directory
def _restore_screenshot_directory(self):
self.screenshot_root_directory = self._screenshot_path_stack.pop()
def _get_screenshot_paths(self, filename):
filename = filename.format(
index=self._get_screenshot_index(filename))
filename = filename.replace('/', os.sep)
screenshotdir = self._get_screenshot_directory()
logdir = self._get_log_dir()
path = os.path.join(screenshotdir, filename)
link = robot.utils.get_link_path(path, logdir)
return path, link
def _get_screenshot_index(self, filename):
if filename not in self._screenshot_index:
self._screenshot_index[filename] = 0
self._screenshot_index[filename] += 1
return self._screenshot_index[filename] | /robotframework-bjrobot-0.6.4.zip/robotframework-bjrobot-0.6.4/src/BJRobot/keywords/screenshot.py | 0.630799 | 0.172764 | screenshot.py | pypi |
from robot.libraries import BuiltIn
from keywordgroup import KeywordGroup
BUILTIN = BuiltIn.BuiltIn()
class RunOnFailure(KeywordGroup):
def __init__(self):
self._run_on_failure_keyword = None
self._running_on_failure_routine = False
# Public
def register_keyword_to_run_on_failure(self, keyword):
"""Sets the keyword to execute when a keyword fails.
`keyword_name` is the name of a keyword (from any available
libraries) that will be executed if a keyword fails.
It is not possible to use a keyword that requires arguments.
Using the value "Nothing" will disable this feature altogether.
The initial keyword to use is set in `importing`, and the
keyword that is used by default is `Capture Page Screenshot`.
Taking a screenshot when something failed is a very useful
feature, but notice that it can slow down the execution.
This keyword returns the name of the previously registered
failure keyword. It can be used to restore the original
value later.
Example:
| Register Keyword To Run On Failure | Log Source | # Run `Log Source` on failure. |
| ${previous kw}= | Register Keyword To Run On Failure | Nothing | # Disables run-on-failure functionality
and stores the previous kw name in a variable. |
| Register Keyword To Run On Failure | ${previous kw} | # Restore to the previous keyword. |
This run-on-failure functionality only works when running tests on Python/Jython 2.4
or newer and it does not work on IronPython at all.
"""
old_keyword = self._run_on_failure_keyword
old_keyword_text = old_keyword if old_keyword is not None else "No keyword"
new_keyword = keyword if keyword.strip().lower() != "nothing" else None
new_keyword_text = new_keyword if new_keyword is not None else "No keyword"
self._run_on_failure_keyword = new_keyword
self._info('%s will be run on failure.' % new_keyword_text)
return old_keyword_text
# Private
def _run_on_failure(self):
if self._run_on_failure_keyword is None:
return
if self._running_on_failure_routine:
return
self._running_on_failure_routine = True
try:
BUILTIN.run_keyword(self._run_on_failure_keyword)
except Exception, err:
self._run_on_failure_error(err)
finally:
self._running_on_failure_routine = False
def _run_on_failure_error(self, err):
err = "Keyword '%s' could not be run on failure: %s" % (self._run_on_failure_keyword, err)
if hasattr(self, '_warn'):
self._warn(err)
return
raise Exception(err) | /robotframework-bjrobot-0.6.4.zip/robotframework-bjrobot-0.6.4/src/BJRobot/keywords/runonfailure.py | 0.810704 | 0.204223 | runonfailure.py | pypi |
import base64
from .keywordgroup import KeywordGroup
from appium.webdriver.connectiontype import ConnectionType
from selenium.common.exceptions import TimeoutException
class AndroidUtils(KeywordGroup):
# Public
def get_network_connection_status(self):
"""Returns an integer bitmask specifying the network connection type.
Android only.
See `set network connection status` for more details.
"""
driver = self._current_application()
return driver.network_connection
def set_network_connection_status(self, connectionStatus):
"""Sets the network connection Status.
Android only.
Possible values:
| =Value= | =Alias= | =Data= | =Wifi= | =Airplane Mode= |
| 0 | (None) | 0 | 0 | 0 |
| 1 | (Airplane Mode) | 0 | 0 | 1 |
| 2 | (Wifi only) | 0 | 1 | 0 |
| 4 | (Data only) | 1 | 0 | 0 |
| 6 | (All network on) | 1 | 1 | 0 |
"""
driver = self._current_application()
return driver.set_network_connection(int(connectionStatus))
def pull_file(self, path, decode=False):
"""Retrieves the file at `path` and return it's content.
Android only.
- _path_ - the path to the file on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._current_application()
theFile = driver.pull_file(path)
if decode:
theFile = base64.b64decode(theFile)
return theFile
def pull_folder(self, path, decode=False):
"""Retrieves a folder at `path`. Returns the folder's contents zipped.
Android only.
- _path_ - the path to the folder on the device
- _decode_ - True/False decode the data (base64) before returning it (default=False)
"""
driver = self._current_application()
theFolder = driver.pull_folder(path)
if decode:
theFolder = base64.b64decode(theFolder)
return theFolder
def push_file(self, path, data, encode=False):
"""Puts the data in the file specified as `path`.
Android only.
- _path_ - the path on the device
- _data_ - data to be written to the file
- _encode_ - True/False encode the data as base64 before writing it to the file (default=False)
"""
driver = self._current_application()
if encode:
data = base64.b64encode(data)
driver.push_file(path, data)
def get_activity(self):
"""Retrieves the current activity on the device.
Android only.
"""
driver = self._current_application()
return driver.current_activity
def start_activity(self, appPackage, appActivity, **opts):
"""Opens an arbitrary activity during a test. If the activity belongs to
another application, that application is started and the activity is opened.
Android only.
- _appPackage_ - The package containing the activity to start.
- _appActivity_ - The activity to start.
- _appWaitPackage_ - Begin automation after this package starts (optional).
- _appWaitActivity_ - Begin automation after this activity starts (optional).
- _intentAction_ - Intent to start (opt_ional).
- _intentCategory_ - Intent category to start (optional).
- _intentFlags_ - Flags to send to the intent (optional).
- _optionalIntentArguments_ - Optional arguments to the intent (optional).
- _stopAppOnReset_ - Should the app be stopped on reset (optional)?
"""
# Almost the same code as in appium's start activity,
# just to keep the same keyword names as in open application
arguments = {
'app_wait_package': 'appWaitPackage',
'app_wait_activity': 'appWaitActivity',
'intent_action': 'intentAction',
'intent_category': 'intentCategory',
'intent_flags': 'intentFlags',
'optional_intent_arguments': 'optionalIntentArguments',
'stop_app_on_reset': 'stopAppOnReset'
}
data = {}
for key, value in arguments.items():
if value in opts:
data[key] = opts[value]
driver = self._current_application()
driver.start_activity(app_package=appPackage, app_activity=appActivity, **data)
def wait_activity(self, activity, timeout, interval=1):
"""Wait for an activity: block until target activity presents
or time out.
Android only.
- _activity_ - target activity
- _timeout_ - max wait time, in seconds
- _interval_ - sleep interval between retries, in seconds
"""
if not activity.startswith('.'):
activity = ".%s" % activity
driver = self._current_application()
if not driver.wait_activity(activity=activity, timeout=float(timeout), interval=float(interval)):
raise TimeoutException(msg="Activity %s never presented, current activity: %s" % (activity, self.get_activity())) | /robotframework-bjrobot-0.6.4.zip/robotframework-bjrobot-0.6.4/src/BJRobot/keywords/android_utils.py | 0.67971 | 0.269981 | android_utils.py | pypi |
from appium.webdriver.common.touch_action import TouchAction
from .keywordgroup import KeywordGroup
class Touch(KeywordGroup):
def __init__(self):
pass
# Public, element lookups
def zoom(self, locator, percent="200%", steps=1):
"""
Zooms in on an element a certain amount.
For mobile application testing only
"""
driver = self._current_application()
element = self.find_element(locator)
driver.zoom(element=element, percent=percent, steps=steps)
def pinch(self, locator, percent="200%", steps=1):
"""
Pinch in on an element a certain amount.
"""
driver = self._current_application()
element = self.find_element(locator)
action = TouchAction(driver)
driver.pinch(element=element, percent=percent, steps=steps)
def swipe(self, start_x, start_y, offset_x, offset_y, duration=1000):
"""
Swipe from one point to another point, for an optional duration.
For mobile application testing only
Args:
- start_x - x-coordinate at which to start
- start_y - y-coordinate at which to start
- offset_x - x-coordinate distance from start_x at which to stop
- offset_y - y-coordinate distance from start_y at which to stop
- duration - (optional) time to take the swipe, in ms.
Usage:
| Swipe | 500 | 100 | 100 | 0 | 1000 |
*!Important Note:* Android `Swipe` is not working properly, use ``offset_x`` and ``offset_y``
as if these are destination points.
"""
driver = self._current_application()
driver.swipe(start_x, start_y, offset_x, offset_y, duration)
def scroll(self, start_locator, end_locator):
"""
Scrolls from one element to another
For mobile application testing only
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
el1 = self.find_element(start_locator)
el2 = self.find_element(end_locator)
driver = self._current_application()
driver.scroll(el1, el2)
def scroll_down(self, locator):
"""Scrolls down to element
For mobile application testing only
"""
driver = self._current_application()
element = self.find_element(locator)
driver.execute_script("mobile: scroll", {"direction": 'down', 'element': element.id})
def scroll_up(self, locator):
"""Scrolls up to element"""
driver = self._current_application()
element = self.find_element(locator)
driver.execute_script("mobile: scroll", {"direction": 'up', 'element': element.id})
def long_press(self, locator):
""" Long press the element
For mobile application testing only
"""
driver = self._current_application()
element = self.find_element(locator)
long_press = TouchAction(driver).long_press(element)
long_press.perform()
def tap(self, locator):
""" Tap on element
For mobile application testing only
"""
driver = self._current_application()
el = self.find_element(locator)
action = TouchAction(driver)
action.tap(el).perform()
def click_a_point(self, x=0, y=0, duration=100):
""" Click on a point
For mobile application testing only
"""
self._info("Clicking on a point (%s,%s)." % (x,y))
driver = self._current_application()
action = TouchAction(driver)
try:
action.press(x=float(x), y=float(y)).wait(float(duration)).release().perform()
except:
assert False, "Can't click on a point at (%s,%s)" % (x,y)
def click_element_at_coordinates_mobile(self, coordinate_X, coordinate_Y):
""" click element at a certain coordinate
For mobile application testing only
"""
self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y))
driver = self._current_application()
action = TouchAction(driver)
action.press(x=coordinate_X, y=coordinate_Y).release().perform() | /robotframework-bjrobot-0.6.4.zip/robotframework-bjrobot-0.6.4/src/BJRobot/keywords/touch.py | 0.835819 | 0.407333 | touch.py | pypi |
import time
from typing import Optional, Union
import wrapt # type: ignore
from assertionengine import AssertionOperator
from typing_extensions import get_args, get_origin
from .utils import logger
def assertion_operator_is_set(wrapped, args, kwargs):
assertion_operator = None
assertion_op_name = None
assertion_op_index = None
for index, (_arg, typ) in enumerate(wrapped.__annotations__.items()):
if get_origin(typ) is Union and AssertionOperator in get_args(typ):
assertion_op_index = index
break
if typ is AssertionOperator:
assertion_op_index = index
break
if assertion_op_index is not None:
if len(args) > assertion_op_index:
assertion_operator = args[assertion_op_index]
elif assertion_op_name in kwargs:
assertion_operator = kwargs[assertion_op_name]
return assertion_operator
@wrapt.decorator
def with_assertion_polling(wrapped, instance, args, kwargs):
start = time.time()
timeout = instance.timeout / 1000
retry_assertions_until = instance.retry_assertions_for / 1000
retries_start: Optional[float] = None
tries = 1
try:
logger.stash_this_thread()
while True:
try:
return wrapped(*args, **kwargs)
except AssertionError as e:
if retries_start is None:
retries_start = time.time()
elapsed = time.time() - start
elapsed_retries = time.time() - retries_start
if elapsed >= timeout or elapsed_retries >= retry_assertions_until:
raise e
tries += 1
if timeout - elapsed > 0.01: # noqa: PLR2004
time.sleep(0.01)
logger.clear_thread_stash()
finally:
logger.flush_and_delete_thread_stash()
if retry_assertions_until and assertion_operator_is_set(wrapped, args, kwargs):
now = time.time()
logger.debug(
f"Assertion polling statistics:\n"
f"First element asserted in: {(retries_start or now) - start} seconds\n"
f"Total tries: {tries}\n"
f"Elapsed time in retries {now - (retries_start or now)} seconds"
) | /robotframework_browser-17.4.0-py3-none-any.whl/Browser/assertion_engine.py | 0.619356 | 0.29432 | assertion_engine.py | pypi |
import urllib.parse
from typing import List, Optional, Set, Tuple
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
from Browser.base import LibraryComponent
from ..utils import logger
class Crawling(LibraryComponent):
@keyword(tags=["Crawling"])
def crawl_site(
self,
url: Optional[str] = None,
page_crawl_keyword="take_screenshot",
max_number_of_page_to_crawl: int = 1000,
max_depth_to_crawl: int = 50,
):
"""
Web crawler is a tool to go through all the pages on a specific URL domain.
This happens by finding all links going to the same site and opening those.
returns list of crawled urls.
| =Arguments= | =Description= |
| ``url`` | is the page to start crawling from. |
| ``page_crawl_keyword`` | is the keyword that will be executed on every page. By default it will take a screenshot on every page. |
| ``max_number_of_page_to_crawl`` | is the upper limit of pages to crawl. Crawling will stop if the number of crawled pages goes over this. |
| ``max_depth_to_crawl`` | is the upper limit of consecutive links followed from the start page. Crawling will stop if there are no more links under this depth. |
[https://forum.robotframework.org/t//4243|Comment >>]
"""
if url:
self.library.new_page(url)
return list(
self._crawl(
self.library.get_url() or "",
page_crawl_keyword,
max_number_of_page_to_crawl,
max_depth_to_crawl,
)
)
def _crawl(
self,
start_url: str,
page_crawl_keyword: str,
max_number_of_page_to_crawl: int,
max_depth_to_crawl: int,
):
hrefs_to_crawl: List[Tuple[str, int]] = [(start_url, 0)]
url_parts = urllib.parse.urlparse(start_url)
baseurl = url_parts.scheme + "://" + url_parts.netloc
crawled: Set[str] = set()
while hrefs_to_crawl and len(crawled) < max_number_of_page_to_crawl:
href, depth = hrefs_to_crawl.pop()
if not href.startswith(baseurl):
continue
if href in crawled:
continue
logger.info(f"Crawling url {href}")
logger.console(
f"{len(crawled) + 1} / {len(crawled) + 1 + len(hrefs_to_crawl)} : Crawling url {href}"
)
try:
self.library.go_to(href)
except Exception as e:
logger.warn(f"Exception while crawling {href}: {e}")
continue
BuiltIn().run_keyword(page_crawl_keyword)
child_hrefs = self._gather_links(depth)
crawled.add(href)
hrefs_to_crawl = self._build_urls_to_crawl(
child_hrefs, hrefs_to_crawl, crawled, baseurl, max_depth_to_crawl
)
return crawled
def _gather_links(self, parent_depth: int) -> List[Tuple[str, int]]:
link_elements = self.library.get_elements("//a[@href]")
links: Set[str] = set()
depth = parent_depth + 1
for link_element in link_elements:
href, normal_link = self.library.evaluate_javascript(
link_element, "(e) => [e.href, !e.download]"
)
if normal_link:
links.add(href)
return [(c, depth) for c in links]
def _build_urls_to_crawl(
self,
new_hrefs_to_crawl: List[Tuple[str, int]],
old_hrefs_to_crawl: List[Tuple[str, int]],
crawled: Set[str],
baseurl: str,
max_depth: int,
) -> List[Tuple[str, int]]:
new_hrefs = []
for href, depth in new_hrefs_to_crawl:
if depth > max_depth:
continue
if href in [h[0] for h in old_hrefs_to_crawl]:
continue
if href in crawled:
continue
if not href.startswith(baseurl):
continue
logger.debug(f"Adding link to {href}")
new_hrefs.append((href, depth))
return new_hrefs + old_hrefs_to_crawl | /robotframework_browser-17.4.0-py3-none-any.whl/Browser/keywords/crawling.py | 0.742702 | 0.32981 | crawling.py | pypi |
from typing import Optional
from ..base import LibraryComponent
from ..utils import keyword, logger
from ..utils.data_types import DelayedKeyword, Scope
class RunOnFailureKeywords(LibraryComponent):
@keyword(tags=("Config",))
def register_keyword_to_run_on_failure(
self, keyword: Optional[str], *args: str, scope: Scope = Scope.Global
) -> DelayedKeyword:
"""Sets the keyword to execute, when a Browser keyword fails.
| =Arguments= | =Description= |
| ``keyword`` | The name of a keyword that will be executed if a Browser keyword fails. It is possible to use any available keyword, including user keywords or keywords from other libraries. |
| ``*args`` | The arguments to the keyword if any. |
| ``scope`` | Scope defines the live time of this setting. Available values are ``Global``, ``Suite`` or ``Test`` / ``Task``. See `Scope Settings` for more details. |
The initial keyword to use is set when `importing` the library, and
the keyword that is used by default is `Take Screenshot`.
Taking a screenshot when something failed is a very useful
feature, but notice that it can slow down the execution.
It is possible to use string ``NONE`` or any other robot falsy name,
case-insensitively, as well as Python ``None`` to disable this
feature altogether.
This keyword returns an object which contains the the previously
registered failure keyword. The return value can be always used to
restore the original value later. The returned object contains
keyword name and the possible arguments used to for the keyword.
Example:
| `Register Keyword To Run On Failure` Take Screenshot
| ${previous kw}= `Register Keyword To Run On Failure` NONE
| `Register Keyword To Run On Failure` ${previous kw}
| `Register Keyword To Run On Failure` Take Screenshot fullPage=True
| `Register Keyword To Run On Failure` Take Screenshot failure-{index} fullPage=True
[https://forum.robotframework.org/t//4316|Comment >>]
"""
old_keyword = self.run_on_failure_keyword
new_keyword = self.parse_run_on_failure_keyword(
f"{keyword} {' '.join(args)}".strip()
)
self.run_on_failure_keyword_stack.set(new_keyword, scope)
if new_keyword.name:
logger.info(f"'{new_keyword}' will be run on failure.")
else:
logger.info("Keyword will not be run on failure.")
return old_keyword | /robotframework_browser-17.4.0-py3-none-any.whl/Browser/keywords/runonfailure.py | 0.890954 | 0.21429 | runonfailure.py | pypi |
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
from .data_types import Scope
if TYPE_CHECKING:
from ..browser import Browser
@dataclass
class ScopedSetting:
typ: Scope
setting: Any
class SettingsStack:
def __init__(
self,
global_setting: Any,
ctx: "Browser",
setter_function: Optional[Callable] = None,
):
self.library = ctx
self.setter_function = setter_function
self._stack: Dict[str, ScopedSetting] = {
"g": ScopedSetting(Scope.Global, global_setting)
}
@property
def _last_id(self) -> str:
return list(self._stack.keys())[-1]
@property
def _last_setting(self) -> ScopedSetting:
return list(self._stack.values())[-1]
def start(self, identifier: str, typ: Scope):
parent_setting = self._last_setting.setting
self._stack[identifier] = ScopedSetting(typ, parent_setting)
def end(self, identifier):
previous = self._stack.pop(identifier, None)
if self.setter_function and previous != self._last_setting:
self.setter_function(self._last_setting.setting)
def set(self, setting: Any, scope: Optional[Scope] = Scope.Global): # noqa: A003
original = self.get()
if scope == Scope.Global:
for value in self._stack.values():
value.setting = setting
elif scope == Scope.Suite:
if self._last_setting.typ == Scope.Test:
self._stack.popitem()
self._stack[self._last_id] = ScopedSetting(Scope.Suite, setting)
elif scope == Scope.Test:
if not self.library.is_test_case_running:
raise ValueError("Setting for test/task can not be set on suite level}")
self._stack[self._last_id] = ScopedSetting(Scope.Test, setting)
else:
self._stack[self._last_id] = ScopedSetting(self._last_setting.typ, setting)
if self.setter_function and original != setting:
self.setter_function(setting)
return original
def get(self):
return self._last_setting.setting | /robotframework_browser-17.4.0-py3-none-any.whl/Browser/utils/settings_stack.py | 0.871932 | 0.239527 | settings_stack.py | pypi |
import re
from datetime import timedelta
from enum import Enum, IntFlag, auto
from typing import Dict, Union
from typing_extensions import TypedDict
class TypedDictDummy(TypedDict):
pass
def convert_typed_dict(function_annotations: Dict, params: Dict) -> Dict: # noqa: C901
for arg_name, arg_type in function_annotations.items():
if arg_name not in params or params[arg_name] is None:
continue
arg_value = params[arg_name]
if getattr(arg_type, "__origin__", None) is Union:
for union_type in arg_type.__args__:
if arg_value is None or not isinstance(
union_type, type(TypedDictDummy)
):
continue
arg_type = union_type # noqa: PLW2901
break
if isinstance(arg_type, type(TypedDictDummy)):
if not isinstance(arg_value, dict):
raise TypeError(
f"Argument '{arg_name}' expects a dictionary like object but did get '{type(arg_value)} instead.'"
)
lower_case_dict = {k.lower(): v for k, v in arg_value.items()}
struct = arg_type.__annotations__
typed_dict = arg_type()
for req_key in arg_type.__required_keys__: # type: ignore
if req_key.lower() not in lower_case_dict:
raise RuntimeError(
f"`{lower_case_dict}` cannot be converted to {arg_type.__name__} for argument '{arg_name}'."
f"\nThe required key '{req_key}' in not set in given value."
f"\nExpected types: {arg_type.__annotations__}"
)
typed_dict[req_key] = struct[req_key](lower_case_dict[req_key.lower()]) # type: ignore
for opt_key in arg_type.__optional_keys__: # type: ignore
if opt_key.lower() not in lower_case_dict:
continue
typed_dict[opt_key] = struct[opt_key](lower_case_dict[opt_key.lower()]) # type: ignore
params[arg_name] = typed_dict
return params
class Deprecated:
def __str__(self) -> str:
return ""
deprecated = Deprecated()
class SelectionStrategy(Enum):
"""SelectionStrategy to be used. Refers to Playwrights ``page.getBy***`` functions. See [https://playwright.dev/docs/locators|Playwright Locators]
== AltText ==
All images should have an alt attribute that describes the image. You can locate an image based on the text alternative using page.getByAltText().
For example, consider the following DOM structure.
| <img alt="playwright logo" src="/img/playwright-logo.svg" width="100" />
== Label ==
Allows locating input elements by the text of the associated ``<label>`` or ``aria-labelledby`` element, or by the ``aria-label`` attribute.
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
| <input aria-label="Username">
| <label for="password-input">Password:</label>
| <input id="password-input">
== Placeholder ==
Allows locating input elements by the placeholder text.
Example:
| <input type="email" placeholder="name@example.com" />
== TestId ==
Locate element by the test id.
Currently only the exact attribute ``data-testid`` is supported.
Example:
| <button data-testid="directions">Itinéraire</button>
== Text ==
Allows locating elements that contain given text.
Matching by text always normalizes whitespace, even with exact match.
For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type button and submit are matched by their value instead of the text content.
For example, locating by text "Log in" matches <input type=button value="Log in">.
== Title ==
Allows locating elements by their title attribute.
Example:
| <img alt="playwright logo" src="/img/playwright-logo.svg" title="Playwright" width="100" />
"""
AltText = "AltText"
Label = "Label"
Placeholder = "Placeholder"
TestID = "TestId"
Text = "Text"
Title = "Title"
class RegExp(str):
@classmethod
def from_string(cls, string: str) -> "RegExp":
"""Create a (JavaScript) RegExp object from a string.
The matcher must start with a slash and end with a slash and can be followed by flags.
Example: ``/hello world/gi``
Which is equivalent to ``new RegExp("hello world", "gi")`` in JavaScript.
Following flags are supported:
| =Flag= | =Description= |
| g | Global search. |
| i | Case-insensitive search. |
| m | Allows ``^`` and ``$`` to match newline characters. |
| s | Allows ``.`` to match newline characters. |
| u | "unicode"; treat a pattern as a sequence of unicode code points. |
| y | Perform a "sticky" search that matches starting at the current position in the target string. |
See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp|RegExp Object]
and [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions|RegExp Guide] for more information.
"""
match = re.fullmatch(r"\/(?<matcher>.*)\/(?<flags>[gimsuy]+)?", string)
if not match:
raise ValueError("Invalid JavaScript RegExp string")
return cls(string)
class ElementRole(Enum):
"""Role selector does not replace accessibility audits and conformance tests,
but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly
[https://w3c.github.io/html-aam/#html-element-role-mappings|defined role]
that is recognized by the role selector.
You can find all the [https://www.w3.org/TR/wai-aria-1.2/#role_definitions|supported roles] here.
ARIA guidelines do not recommend duplicating implicit roles and attributes
by setting role and/or aria-* attributes to default values."""
ALERT = auto()
ALERTDIALOG = auto()
APPLICATION = auto()
ARTICLE = auto()
BANNER = auto()
BLOCKQUOTE = auto()
BUTTON = auto()
CAPTION = auto()
CELL = auto()
CHECKBOX = auto()
CODE = auto()
COLUMNHEADER = auto()
COMBOBOX = auto()
COMPLEMENTARY = auto()
CONTENTINFO = auto()
DEFINITION = auto()
DELETION = auto()
DIALOG = auto()
DIRECTORY = auto()
DOCUMENT = auto()
EMPHASIS = auto()
FEED = auto()
FIGURE = auto()
FORM = auto()
GENERIC = auto()
GRID = auto()
GRIDCELL = auto()
GROUP = auto()
HEADING = auto()
IMG = auto()
INSERTION = auto()
LINK = auto()
LIST = auto()
LISTBOX = auto()
LISTITEM = auto()
LOG = auto()
MAIN = auto()
MARQUEE = auto()
MATH = auto()
METER = auto()
MENU = auto()
MENUBAR = auto()
MENUITEM = auto()
MENUITEMCHECKBOX = auto()
MENUITEMRADIO = auto()
NAVIGATION = auto()
NONE = auto()
NOTE = auto()
OPTION = auto()
PARAGRAPH = auto()
PRESENTATION = auto()
PROGRESSBAR = auto()
RADIO = auto()
RADIOGROUP = auto()
REGION = auto()
ROW = auto()
ROWGROUP = auto()
ROWHEADER = auto()
SCROLLBAR = auto()
SEARCH = auto()
SEARCHBOX = auto()
SEPARATOR = auto()
SLIDER = auto()
SPINBUTTON = auto()
STATUS = auto()
STRONG = auto()
SUBSCRIPT = auto()
SUPERSCRIPT = auto()
SWITCH = auto()
TAB = auto()
TABLE = auto()
TABLIST = auto()
TABPANEL = auto()
TERM = auto()
TEXTBOX = auto()
TIME = auto()
TIMER = auto()
TOOLBAR = auto()
TOOLTIP = auto()
TREE = auto()
TREEGRID = auto()
TREEITEM = auto()
class DelayedKeyword:
def __init__(
self,
name: Union[str, None],
original_name: Union[str, None],
args: tuple,
kwargs: dict,
):
self.name = name
self.original_name = original_name
self.args = args
self.kwargs = kwargs
def __str__(self):
args = [str(arg) for arg in self.args]
kwargs = [f"{key}={value}" for key, value in self.kwargs.items()]
return f"{self.original_name} {' '.join(args)} {' '.join(kwargs)}".strip()
class BoundingBox(TypedDict, total=False):
x: float
y: float
width: float
height: float
class Coordinates(TypedDict, total=False):
x: float
y: float
class MouseOptionsDict(TypedDict, total=False):
x: float
y: float
options: dict
class ViewportDimensions(TypedDict):
width: int
height: int
class RecordVideo(TypedDict, total=False):
"""Enables Video recording
Examples:
| New Context recordVideo={'dir':'videos', 'size':{'width':400, 'height':200}}
| New Context recordVideo={'dir': 'd:/automation/video'}
"""
dir: str
size: ViewportDimensions
class RecordHar(TypedDict, total=False):
"""Enables HAR recording for all pages into to a file.
If not specified, the HAR is not recorded. Make sure to await context to close for the
[http://www.softwareishard.com/blog/har-12-spec/|HAR] to be saved.
`omitContent`: Optional setting to control whether to omit request content
from the HAR. Default is False
`path`: Path on the filesystem to write the HAR file to.
Example:
| ${har} = Create Dictionary path=/path/to/har.file omitContent=True
| New Context recordHar=${har}
"""
omitContent: bool
path: str
class _HttpCredentials(TypedDict):
username: str
password: str
class HttpCredentials(_HttpCredentials, total=False):
"""Sets the credentials for http basic-auth.
``origin``:
Restrain sending http credentials on specific origin (scheme://host:port).
Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.
Can be defined as robot dictionary or as string literal. Does not reveal secrets
in Robot Framework logs. Instead, username and password values are resolved internally.
Please note that if ``enable_playwright_debug`` is enabled in the library import,
secret will be always visible as plain text in the playwright debug logs, regardless
of the Robot Framework log level.
Example as literal:
| ${pwd} = Set Variable 1234
| ${username} = Set Variable admin
| `New Context`
| ... httpCredentials={'username': '$username', 'password': '$pwd'}
Example as robot variable
| ***** *Variables* *****
| ${username}= admin
| ${pwd}= 1234
| ${credentials}= username=$username password=$pwd
|
| ***** *Keywords* *****
| Open Context
| `New Context` httpCredentials=${credentials}
"""
origin: str
class _GeoCoordinated(TypedDict):
longitude: float
latitude: float
class GeoLocation(_GeoCoordinated, total=False):
"""Defines the geolocation.
- ``latitude`` Latitude between -90 and 90.
- ``longitude`` Longitude between -180 and 180.
- ``accuracy`` *Optional* Non-negative accuracy value. Defaults to 0.
Example usage: ``{'latitude': 59.95, 'longitude': 30.31667}``"""
accuracy: float
class _Server(TypedDict):
server: str
class Proxy(_Server, total=False):
"""Network proxy settings.
``server`` Proxy to be used for all requests. HTTP and SOCKS proxies are supported,
for example http://myproxy.com:3128 or socks5://myproxy.com:3128.
Short form myproxy.com:3128 is considered an HTTP proxy.
``bypass`` *Optional* coma-separated domains to bypass proxy,
for example ".com, chromium.org, .domain.com".
``username`` *Optional* username to use if HTTP proxy requires authentication.
``password`` *Optional* password to use if HTTP proxy requires authentication.
"""
bypass: str
username: str
password: str
class DownloadedFile(TypedDict):
"""Downloaded file information.
``saveAs`` is the path where downloaded file is saved.
``suggestedFilename`` is the contains the name suggested name for the download.
"""
saveAs: str
suggestedFilename: str
class NewPageDetails(TypedDict):
"""Return value of `New Page` keyword.
``page_id`` is the UUID of the opened page.
``video_path`` path to the video or empty string if video is not created.
"""
page_id: str
video_path: str
class HighLightElement(TypedDict):
"""Presenter mode configuration options.
``duration`` Sets for how long the selector shall be highlighted. Defaults to ``5s`` => 5 seconds.
``width`` Sets the width of the higlight border. Defaults to 2px.
``style`` Sets the style of the border. Defaults to dotted.
``color`` Sets the color of the border, default is blue. Valid colors i.e. are:
``red``, ``blue``, ``yellow``, ``pink``, ``black``
"""
duration: timedelta
width: str
style: str
color: str
class Scale(Enum):
"""Enum that defines the scale of the screenshot.
When set to "css", screenshot will have a single pixel per each css pixel on the page.
For high-dpi devices, this will keep screenshots small. Using "device" option will
produce a single pixel per each device pixel, so screenshots of high-dpi devices will
be twice as large or even larger.
"""
css = auto()
device = auto()
class SelectionType(Enum):
"""Enum that defines if the current id or all ids shall be returned.
``ACTIVE`` / ``CURRENT`` defines to return only the id of the currently active
instance of a Browser/Context/Page.
``ALL`` / ``ANY`` defines to return ids of all instances."""
CURRENT = "CURRENT"
ACTIVE = CURRENT
ALL = "ALL"
ANY = ALL
@classmethod
def create(cls, value: Union[str, "SelectionType"]):
"""Returns the enum value from the given string or not."""
if isinstance(value, cls):
return value
if isinstance(value, str):
try:
return cls[value.upper()]
except KeyError:
return value
return None
def __str__(self):
return self.value
class DialogAction(Enum):
"""Enum that defines how to handle a dialog."""
accept = auto()
dismiss = auto()
class CookieType(Enum):
"""Enum that defines the Cookie type."""
dictionary = auto()
dict = dictionary # noqa: A003
string = auto()
str = string # noqa: A003
CookieSameSite = Enum(
"CookieSameSite", {"Strict": "Strict", "Lax": "Lax", "None": "None"}
)
CookieSameSite.__doc__ = """Enum that defines the Cookie SameSite type.
It controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF).
The possible attribute values are:
| = Value = | = Description = |
| ``Strict`` | Means that the browser sends the cookie only for same-site requests, that is, requests originating from the same site that set the cookie. If a request originates from a different domain or scheme (even with the same domain), no cookies with the SameSite=Strict attribute are sent. |
| ``Lax`` | Means that the cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site (for example, when following a link). This is the default behavior if the SameSite attribute is not specified. |
| ``None`` | means that the browser sends the cookie with both cross-site and same-site requests. The Secure attribute must also be set when setting this value. |
See [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie|MDN Set-Cookie] for more information.
"""
class RequestMethod(Enum):
"""Enum that defines the request type."""
HEAD = auto()
GET = auto()
POST = auto()
PUT = auto()
PATCH = auto()
DELETE = auto()
class MouseButtonAction(Enum):
"""Enum that defines which `Mouse Button` action to perform."""
click = auto()
down = auto()
up = auto()
class MouseButton(Enum):
"""Enum that defines which mouse button to use."""
left = auto()
middle = auto()
right = auto()
class KeyAction(Enum):
"""Enum that defines which `Keyboard Key` action to perform."""
down = auto()
up = auto()
press = auto()
class KeyboardInputAction(Enum):
"""Enum that defines how `Keyboard Input` adds the text into the page.
``insertText`` is mostly similar to pasting of text.
``type`` is similar to typing by pressing keys on the keyboard."""
insertText = auto()
type = auto() # noqa: A003
class KeyboardModifier(Enum):
"""Modifier keys to press while doing other actions.
Modifiers that are pressed during the `Hover` or `Click`."""
Alt = auto()
Control = auto()
Meta = auto()
Shift = auto()
class SelectAttribute(Enum):
"""Enum that defines the attribute of an <option> element in a <select>-list.
This defines by what attribute an option is selected/chosen.
| <select class="my_drop_down">
| <option value="0: Object">None</option>
| <option value="1: Object">Some</option>
| <option value="2: Object">Other</option>
| </select>
``value`` of the first option would be ``0: Object``.
``label`` / ``text`` both defines the innerText which would be ``None`` for first element.
``index`` 0 indexed number of an option. Would be ``0`` for the first element.
"""
value = auto()
label = auto()
text = label
index = auto()
class SupportedBrowsers(Enum):
"""Defines which browser shall be started.
| =Browser= | =Browser with this engine= |
| ``chromium`` | Google Chrome, Microsoft Edge (since 2020), Opera |
| ``firefox`` | Mozilla Firefox |
| ``webkit`` | Apple Safari, Mail, AppStore on MacOS and iOS |
Since [https://github.com/microsoft/playwright|Playwright] comes with a pack of builtin
binaries for all browsers, no additional drivers e.g. geckodriver are needed.
All these browsers that cover more than 85% of the world wide used browsers,
can be tested on Windows, Linux and MacOS.
Theres is not need for dedicated machines anymore.
"""
chromium = auto()
firefox = auto()
webkit = auto()
ColorScheme = Enum("ColorScheme", ["dark", "light", "no-preference"])
ColorScheme.__doc__ = """Emulates 'prefers-colors-scheme' media feature.
See [https://playwright.dev/docs/api/class-page?_highlight=emulatemedia#pageemulatemediaparams |emulateMedia(options)]
for more details.
"""
class Permission(Enum):
"""Enum that defines the permission to grant to a context.
See [https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions |grantPermissions(permissions)]
for more details.
"""
geolocation = auto()
midi = auto()
midi_sysex = auto()
notifications = auto()
push = auto()
camera = auto()
microphone = auto()
background_sync = auto()
ambient_light_sensor = auto()
accelerometer = auto()
gyroscope = auto()
magnetometer = auto()
accessibility_events = auto()
clipboard_read = auto()
clipboard_write = auto()
payment_handler = auto()
ScrollBehavior = Enum("ScrollBehavior", ["auto", "smooth"])
ScrollBehavior.__doc__ = """Enum that controls the behavior of scrolling.
``smooth``
"""
class SizeFields(Enum):
"""Enum that defines how the returned size is filtered.
``ALL`` defines that the size is returned as a dictionary. ``{'width': <float>, 'height': <float>}.``
``width`` / ``height`` will return a single float value of the chosen dimension."""
width = auto()
height = auto()
ALL = auto()
class AreaFields(Enum):
"""Enumeration that defines which coordinates of an area should be selected.
``ALL`` defines that all fields are selected and a dictionary with all information
is returned.
"""
top = auto()
left = auto()
bottom = auto()
right = auto()
ALL = auto()
class BoundingBoxFields(Enum):
"""Enumeration that defines which location information of an element should be selected.
``x`` / ``y`` defines the position of the top left corner of an element.
``width`` / ``height`` defines the size of an elements bounding box.
``ALL`` defines that all fields are selected and a dictionary with all information
is returned.
"""
width = auto()
height = auto()
x = auto()
y = auto()
ALL = auto()
class AutoClosingLevel(Enum):
"""Controls when contexts and pages are closed during the test execution.
If automatic closing level is `TEST`, contexts and pages that are created during a single test are
automatically closed when the test ends. Contexts and pages that are created during suite setup are
closed when the suite teardown ends.
If automatic closing level is `SUITE`, all contexts and pages that are created during the test suite
are closed when the suite teardown ends.
If automatic closing level is `MANUAL`, nothing is closed automatically while the test execution
is ongoing.
All browsers are automatically closed, always and regardless of the automatic closing level at
the end of the test execution. This will also close all remaining pages and contexts.
Automatic closing can be configured or switched off with the auto_closing_level library import
parameter.
See: `Importing`"""
SUITE = auto()
TEST = auto()
MANUAL = auto()
class ElementState(IntFlag):
"""Enum that defines the state an element can have.
The following ``states`` are possible:
| =State= | =Description= |
| ``attached`` | to be present in DOM. |
| ``detached`` | to not be present in DOM. |
| ``visible`` | to have non or empty bounding box and no visibility:hidden. |
| ``hidden`` | to be detached from DOM, or have an empty bounding box or visibility:hidden. |
| ``enabled`` | to not be ``disabled``. |
| ``disabled`` | to be ``disabled``. Can be used on <button>, <fieldset>, <input>, <optgroup>, <option>, <select> and <textarea>. |
| ``editable`` | to not be ``readOnly``. |
| ``readonly`` | to be ``readOnly``. Can be used on <input> and <textarea>. |
| ``selected`` | to be ``selected``. Can be used on <option>. |
| ``deselected`` | to not be ``selected``. |
| ``focused`` | to be the ``activeElement``. |
| ``defocused`` | to not be the ``activeElement``. |
| ``checked`` | to be ``checked``. Can be used on <input>. |
| ``unchecked`` | to not be ``checked``. |
| ``stable`` | to be both ``visible`` and ``stable``. |
"""
attached = 1
detached = 2
visible = 4
hidden = 8
enabled = 16
disabled = 32
editable = 64
readonly = 128
selected = 256
deselected = 512
focused = 1024
defocused = 2048
checked = 4096
unchecked = 8192
stable = 16384
ElementStateKey = (
ElementState # Deprecated. Remove after `Get Element State` is removed.
)
class ScreenshotFileTypes(Enum):
"""Enum that defines available file types for screenshots."""
png = auto()
jpeg = auto()
class ScreenshotReturnType(Enum):
"""Enum that defines what `Take Screenshot` keyword returns.
- ``path`` returns the path to the screenshot file as ``pathlib.Path`` object.
- ``path_string`` returns the path to the screenshot file as string.
- ``bytes`` returns the screenshot itself as bytes.
- ``base64`` returns the screenshot itself as base64 encoded string.
"""
path = auto()
path_string = auto()
bytes = auto() # noqa: A003
base64 = auto()
class PageLoadStates(Enum):
"""Enum that defines available page load states."""
load = auto()
domcontentloaded = auto()
networkidle = auto()
commit = auto()
class ReduceMotion(Enum):
"""Emulates `prefers-reduced-motion` media feature, supported values are `reduce`, `no-preference`."""
reduce = auto()
no_preference = auto()
class ForcedColors(Enum):
"""Emulates `forced-colors` media feature, supported values are `active`, `none`."""
active = auto()
none = auto()
class ConditionInputs(Enum):
"""
Following values are allowed and represent the assertion keywords to use:
| =Value= | =Keyword= |
| ``Attribute`` | `Get Attribute` |
| ``Attribute Names`` | `Get Attribute Names` |
| ``BoundingBox`` | `Get BoundingBox` |
| ``Browser Catalog`` | `Get Browser Catalog` |
| ``Checkbox State`` | `Get Checkbox State` |
| ``Classes`` | `Get Classes` |
| ``Client Size`` | `Get Client Size` |
| ``Element Count`` | `Get Element Count` |
| ``Element States`` | `Get Element States` |
| ``Page Source`` | `Get Page Source` |
| ``Property`` | `Get Property` |
| ``Scroll Position`` | `Get Scroll Position` |
| ``Scroll Size`` | `Get Scroll Size` |
| ``Select Options`` | `Get Select Options` |
| ``Selected Options`` | `Get Selected Options` |
| ``Style`` | `Get Style` |
| ``Table Cell Index`` | `Get Table Cell Index` |
| ``Table Row Index`` | `Get Table Row Index` |
| ``Text`` | `Get Text` |
| ``Title`` | `Get Title` |
| ``Url`` | `Get Url` |
| ``Viewport Size`` | `Get Viewport Size` |
"""
attribute = "get_attribute"
attribute_names = "get_attribute_names"
bounding_box = "get_bounding_box"
browser_catalog = "get_browser_catalog"
checkbox_state = "get_checkbox_state"
classes = "get_classes"
client_size = "get_client_size"
element_count = "get_element_count"
element_states = "get_element_states"
page_source = "get_page_source"
property = "get_property" # noqa: A003
scroll_position = "get_scroll_position"
scroll_size = "get_scroll_size"
select_options = "get_select_options"
selected_options = "get_selected_options"
style = "get_style"
table_cell_index = "get_table_cell_index"
table_row_index = "get_table_row_index"
text = "get_text"
title = "get_title"
url = "get_url"
viewport_size = "get_viewport_size"
class Scope(Enum):
"""Some keywords which manipulates library settings have a scope argument.
With that scope argument one can set the "live time" of that setting.
Available Scopes are: ``Global``, ``Suite`` and ``Test`` / ``Task``.
Is a scope finished, this scoped setting, like timeout, will no longer be used and the previous higher scope setting applies again.
Live Times:
- A ``Global`` scope will live forever until it is overwritten by another Global scope.
Or locally temporarily overridden by a more narrow scope.
- A ``Suite`` scope will locally override the Global scope and
live until the end of the Suite within it is set, or if it is overwritten
by a later setting with Global or same scope.
Children suite does inherit the setting from the parent suite but also may have
its own local Suite setting that then will be inherited to its children suites.
- A ``Test`` or ``Task`` scope will be inherited from its parent suite but when set,
lives until the end of that particular test or task.
A new set higher order scope will always remove the lower order scope which may be in charge.
So the setting of a Suite scope from a test, will set that scope to the robot file suite where
that test is and removes the Test scope that may have been in place."""
Global = auto()
Suite = auto()
Test = auto()
Task = Test
class ServiceWorkersPermissions(Enum):
"""Whether to allow sites to register Service workers.
``allow``: Service Workers can be registered.
``block``: Playwright will block all registration of Service Workers.
"""
allow = auto()
block = auto() | /robotframework_browser-17.4.0-py3-none-any.whl/Browser/utils/data_types.py | 0.796094 | 0.241646 | data_types.py | pypi |
from browsermobproxy import Server
from browsermobproxy import RemoteServer
import json
from .version import VERSION
__version__ = VERSION
LIMITS = {
'upstream_kbps': 'upstreamKbps',
'downstream_kbps': 'downstreamKbps',
'latency': 'latency'
}
TIMEOUTS = {
'request': 'requestTimeout',
'read': 'readTimeout',
'connection': 'connectionTimeout',
'dns': 'dnsCacheTimeout'
}
class BrowserMobProxyLibrary(object):
"""BrowserMobProxyLibrary is a Robot Framework library ro interface with BrowserMob Proxy.
BrowserMob Proxy is a simple utility to capture performance data for web apps (via the HAR format),
as well as manipulate browser behavior and traffic, such as whitelisting and blacklisting content,
simulating network traffic and latency, and rewriting HTTP requests and responses.
= Before running tests =
Prior to running test cases using BrowserMobProxyLibrary, BrowserMobProxyLibrary must be
imported into your Robot test suite.
"""
ROBOT_LIBRARY_VERSION = VERSION
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self):
"""BrowserMobProxyLibrary is a Robot Framework library ro interface with BrowserMob Proxy.
"""
self.server = None
self.client = None
def get_proxy_url(self):
"""Gets the url that the proxy is running on. This is not the URL clients
should connect to.
"""
return self.server.url
def create_proxy(self, params={}):
"""Creates proxy.
:param params: Dictionary where you can specify params \
like httpProxy and httpsProxy
"""
self.client = self.server.create_proxy(params=params)
return self.client
def start_local_server(self, path='browsermob-proxy', options={}):
"""Start local Browsermob Proxy Server instance
:param path: Path to the browsermob proxy batch file
:param options: Dictionary that can hold the port. \
"""
self.server = Server(path=path, options=options)
self.server.start()
def stop_local_server(self):
"""This will stop the process running the Browsermob Proxy
"""
if isinstance(self.server, Server):
self.server.stop()
def connect_to_remote_server(self, host='localhost', port=9090):
"""Connect to a Remote Browsermob Proxy Server
:param host: The host of the proxy server.
:param port: The port of the proxy server.
"""
self.server = RemoteServer(host=host, port=int(port))
def close_proxy(self):
"""shuts down the proxy and closes the port
"""
return self.client.close()
def get_selenium_proxy(self):
"""Returns a Selenium WebDriver Proxy with details of the HTTP Proxy
"""
return self.client.selenium_proxy()
def get_webdriver_proxy(self):
"""Returns a Selenium WebDriver Proxy with details of the HTTP Proxy
"""
return self.client.webdriver_proxy()
def add_to_capabilities(self, capabilities):
"""Adds an 'proxy' entry to a desired capabilities dictionary with the
BrowserMob proxy information
:param capabilities: The Desired capabilities object from Selenium WebDriver
"""
self.client.add_to_capabilities(capabilities=capabilities)
def add_to_webdriver_capabilities(self, capabilities):
"""Adds an 'proxy' entry to a desired capabilities dictionary with the
BrowserMob proxy information
:param capabilities: The Desired capabilities object from Selenium WebDriver
"""
self.client.add_to_webdriver_capabilities(capabilities=capabilities)
def get_har(self):
"""Returns the HAR that has been recorded
"""
return self.client.har
def get_har_as_json(self):
"""Returns the HAR that has been recorded as json
"""
return json.dumps(self.client.har)
def new_har(self, ref=None, options={}):
"""This sets a new HAR to be recorded
:param ref: A reference for the HAR. Defaults to None
:param options: A dictionary that will be passed to BrowserMob Proxy \
with specific keywords. Keywords are: \
captureHeaders - Boolean, capture headers \
captureContent - Boolean, capture content bodies \
captureBinaryContent - Boolean, capture binary content
"""
return self.client.new_har(ref=ref, options=options)
def new_page(self, ref=None):
"""This sets a new page to be recorded
:param ref: A reference for the new page. Defaults to None
"""
return self.client.new_page(ref=ref)
def blacklist(self, regexp, status_code):
"""Sets a list of URL patterns to blacklist
:param regexp: a comma separated list of regular expressions
:param status_code: the HTTP status code to return for URLs that do not \
match the blacklist
"""
return self.client.blacklist(regexp=regexp, status_code=status_code)
def whitelist(self, regexp, status_code):
"""Sets a list of URL patterns to whitelist
:param regex: a comma separated list of regular expressions
:param status_code: the HTTP status code to return for URLs that do not \
match the whitelist
"""
return self.client.whitelist(regexp=regexp, status_code=status_code)
def basic_authentication(self, domain, username, password):
"""This add automatic basic authentication
:param domain: domain to set authentication credentials for
:param username: valid username to use when authenticating
:param password: valid password to use when authenticating
"""
return self.client.basic_authentication(domain=domain, username=username, password=password)
def set_headers(self, headers):
"""This sets the headers that will set by the proxy on all requests
:param headers: this is a dictionary of the headers to be set
"""
return self.client.headers(headers=headers)
def set_response_interceptor(self, js):
"""Executes the javascript against each response
:param js: the javascript to execute
"""
return self.client.response_interceptor(js=js)
def set_request_interceptor(self, js):
"""Executes the javascript against each request
:param js: the javascript to execute
"""
return self.client.request_interceptor(js=js)
def set_limits(self, options):
"""Limit the bandwidth through the proxy.
:param options: A dictionary with all the details you want to set. \
downstreamKbps - Sets the downstream kbps \
upstreamKbps - Sets the upstream kbps \
latency - Add the given latency to each HTTP request
"""
return self.client.limits(options)
def set_timeouts(self, options):
"""Configure timeouts in the proxy
:param options: A dictionary with all the details you want to set. \
request - request timeout (in seconds) \
read - read timeout (in seconds) \
connection - connection timeout (in seconds) \
dns - dns lookup timeout (in seconds)
"""
return self.client.timeouts(options=options)
def remap_hosts(self, address, ip_address):
"""Remap the hosts for a specific URL
:param address: url that you wish to remap
:param ip_address: IP Address that will handle all traffic for the address passed in
"""
return self.client.remap_hosts(address=address, ip_address=ip_address)
def wait_for_traffic_to_stop(self, quiet_period, timeout):
"""Waits for the network to be quiet
:param quiet_period: number of miliseconds the network needs to be quiet for
:param timeout: max number of miliseconds to wait
"""
return self.client.wait_for_traffic_to_stop(quiet_period=quiet_period, timeout=timeout)
def clear_dns_cache(self):
"""Clears the DNS cache associated with the proxy instance
"""
return self.client.clear_dns_cache()
def rewrite_url(self, match, replace):
"""Rewrites the requested url.
:param match: a regex to match requests with
:param replace: unicode a string to replace the matches with
"""
return self.client.rewrite_url(match=match, replace=replace)
def retry(self, retry_count):
"""Retries.
:param retry_count: the number of retries
"""
return self.client.retry(retry_count=retry_count) | /robotframework-browsermobproxylibrary-0.1.3.tar.gz/robotframework-browsermobproxylibrary-0.1.3/src/BrowserMobProxyLibrary/__init__.py | 0.767603 | 0.26923 | __init__.py | pypi |
from enum import IntEnum
from robot.utils import timestr_to_secs
__doc__ = """RobotTime are extension for RF robot_math.cross_type_operators.timestr_to_secs method
Allow math manipulation with time strings in compatible for RF formats
Examples:
my_time = RobotTime(1h) + RobotTime(2m)
print(f"{my_time}")
> 1h 2m
"""
from .abstracts import TypeAbstract
from . import Percent
class RobotTimeUnits(IntEnum):
s = 1
m = 60
h = 60 * 60
d = 24 * 60 * 60
class TimeInterval(TypeAbstract):
def __init__(cls, value_str):
super().__init__(int(timestr_to_secs(value_str)), type=int, units='seconds')
@staticmethod
def from_units(value, **kwargs):
if type(value) == TimeInterval:
return value
return TimeInterval(value)
@staticmethod
def _seconds_to_timestr(seconds, leading_unit=RobotTimeUnits.d):
_res_str = ''
for index, unit in enumerate([_u for _u in reversed(list(RobotTimeUnits)) if _u <= leading_unit]):
_mod = int(seconds // unit)
seconds -= _mod * unit
if _mod > 0:
_res_str += f'{_mod}{unit.name} '
return _res_str.strip() if len(_res_str) > 0 else '0'
def __str__(self):
return self._seconds_to_timestr(int(self))
def __format__(self, format_spec):
if format_spec != '':
return self._seconds_to_timestr(int(self), RobotTimeUnits[format_spec])
else:
return str(self)
def __add__(self, other):
if type(other) == Percent:
return self.from_units(other + self.units)
return super().__add__(other)
def __iadd__(self, other):
if type(other) == Percent:
self._units = other + self.units
return self
return super().__iadd__(other)
def __sub__(self, other):
if type(other) == Percent:
return self.from_units(other - self.units)
return super().__sub__(other)
def __isub__(self, other):
if type(other) == Percent:
self._units = other - self.units
return self
return super().__isub__(other) | /robotframework_calculator-2.3-py3-none-any.whl/robot_math/types/time_interval_type.py | 0.837221 | 0.341308 | time_interval_type.py | pypi |
import enum
import re
from .abstracts import TypeAbstract
from . import Percent
BIT = 1
BYTE = 8
KILO = 1000
class PacketUnit(enum.IntEnum):
b = BIT
B = BYTE
k = KILO
K = KILO * BYTE
m = pow(KILO, 2)
M = pow(KILO, 2) * BYTE
g = pow(KILO, 3)
G = pow(KILO, 3) * BYTE
BITRATE_REGEX = re.compile(r'([\d.]+)(.*)')
class DataPacket(TypeAbstract):
def __init__(cls, value_str=None, **kwargs):
try:
value_str = '0' if value_str == 0 else value_str
rate = kwargs.get('rate', '')
if rate != '':
rate = cls._get_rate(rate).name
parsing_value = value_str or f"{kwargs.get('number', '')}{rate}"
if parsing_value == '':
raise ValueError(f"Packet size not provided: neither in '{value_str}' or '{kwargs}")
number, rate_name = cls.parse(parsing_value)
cls.rate = PacketUnit[rate_name if rate == '' else rate]
super().__init__(int(number * cls._rate), type=int, units='bits')
except Exception as e:
raise ValueError(f"Cannot parse string '{e}'")
@staticmethod
def _get_rate(rate):
if isinstance(rate, PacketUnit):
return rate
else:
return PacketUnit[rate]
@property
def rate(cls):
return cls._rate
@rate.setter
def rate(cls, rate):
cls._rate = cls._get_rate(rate)
def _to_string(cls, format_spec, rate=None):
rate = PacketUnit[rate] if rate else cls._rate
return f"{cls.units / rate:{format_spec}}{rate.name}"
@staticmethod
def parse(bitrate_str: str):
try:
m = BITRATE_REGEX.match(str(bitrate_str))
if m is None:
raise AttributeError("Wrong bitrate format ({})".format(bitrate_str))
number = float(m.groups()[0])
rate = m.groups()[1] or PacketUnit.b.name
return number, rate
except Exception as e:
raise type(e)("Cannot parse PacketSize value string '{}' with error: {}".format(bitrate_str, e))
@staticmethod
def from_units(value, rate=PacketUnit.b):
if isinstance(value, str):
return DataPacket(value, rate=rate)
return DataPacket(number=value / rate, rate=rate)
def __format__(self, format_spec):
rates = [r for r in list(PacketUnit) if format_spec.endswith(r.name)]
if len(rates) == 1:
rate = rates[0].name
format_spec = format_spec.replace(rate, 'f')
return self._to_string(format_spec, rate=rate)
elif len(rates) == 0:
return self._to_string(format_spec)
else:
raise IndexError()
def __str__(self):
return self._to_string('')
def __radd__(self, other):
if other == 0:
return self
else:
return self + other
def __add__(self, other):
if type(other) == Percent:
return self.from_units(other + self.units, rate=self.rate)
return self.from_units(other + self.units, rate=self.rate)
def __iadd__(self, other):
if type(other) == Percent:
self._units = self.from_units(other + self.units, rate=self.rate)
return self
if isinstance(other, str):
other = DataPacket(other)
return super().__iadd__(other)
def __sub__(self, other):
if type(other) == Percent:
return self.from_units(other - self.units, rate=self.rate)
return super().__sub__(other)
def __isub__(self, other):
if type(other) == Percent:
self._units = other - self.units
return self
return super().__isub__(other) | /robotframework_calculator-2.3-py3-none-any.whl/robot_math/types/data_packet_type.py | 0.62681 | 0.302211 | data_packet_type.py | pypi |
import re
from abc import ABC, abstractmethod
class _SpecialType(ABC, type):
FORMAT_PARSE_REGEX = re.compile(r'^\.([\d]+)([a-zA-Z%]?)$')
def __new__(mcs, *args, **kwargs):
return super().__new__(mcs, mcs.__name__, (object,), kwargs)
def __init__(cls, units_count, **kwargs):
super().__init__(cls.__name__)
cls.__repr__ = cls.__str__
try:
cls._unit_type = kwargs.get('type', float)
cls._units = cls._unit_type(units_count)
assert isinstance(cls._units, cls._unit_type)
_unit_name = kwargs.get('units', 'units')
if _unit_name != 'units':
setattr(cls, _unit_name, cls.units)
except Exception:
raise ValueError(f"Value must be numeric only vs. {units_count} - ({type(units_count).__name__})")
def __float__(self):
return float(self.units)
def __int__(self):
return int(self.units)
def _get_round_from_format_spec(cls, format_spec, adjust=False):
m = cls.FORMAT_PARSE_REGEX.match(format_spec)
if m is None:
raise ValueError(f"Wrong format: {format_spec}")
_spec_index, _spec_char = int(m.groups()[0]), m.groups()[1]
if adjust:
_in_str = str(cls.units / 100).split('.', 2)[1]
_spec_index = len(_in_str)
return _spec_index, _spec_char
@property
def units(self):
return self._unit_type(self._units)
def cast_to_units(self, value, **kwargs) -> float:
if type(self) != type(value):
return self._unit_type(self.from_units(value, **kwargs))
return value.units
@abstractmethod
def __str__(self):
raise NotImplementedError()
def __repr__(self):
return str(self)
@staticmethod
@abstractmethod
def from_units(value, **kwargs):
raise NotImplementedError()
def __eq__(self, other):
return self.units == self.cast_to_units(other)
def __ne__(self, other):
return not _SpecialType.__eq__(self, other)
def __gt__(self, other):
return self.units > self.cast_to_units(other)
def __lt__(self, other):
return self.units < self.cast_to_units(other)
def __ge__(self, other):
return self.units >= self.cast_to_units(other)
def __le__(self, other):
return self.units <= self.cast_to_units(other)
def __add__(self, other):
return self.from_units(self.units + self.cast_to_units(other))
def __iadd__(self, other):
self._units = self._units + self.cast_to_units(other)
return self
def __sub__(self, other):
return self.from_units(self.units - self.cast_to_units(other))
def __isub__(self, other):
self._units = self._units - self.cast_to_units(other)
return self
def __idiv__(self, other):
if not isinstance(other, (int, float)):
raise TypeError("Dividing allowed to numbers only")
return self.from_units(self.units / self.cast_to_units(other))
def __mul__(self, other):
if not isinstance(other, (int, float)):
raise TypeError("Multiplexing allowed to numbers only")
self._units = self._units * other
return self
def __imul__(self, other):
if not isinstance(other, (int, float)):
raise TypeError("Multiplexing allowed to numbers only")
self._units = self.units / other
return self
def __truediv__(self, other):
return _SpecialType.__idiv__(self, other)
def __floordiv__(self, other):
return _SpecialType.__idiv__(self, other) | /robotframework_calculator-2.3-py3-none-any.whl/robot_math/types/abstracts/special_type_abs.py | 0.744192 | 0.263454 | special_type_abs.py | pypi |
from generic_camunda_client.configuration import Configuration
from robot.api.deco import library, keyword
from robot.api.logger import librarylogger as logger
# requests import
from requests import HTTPError
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
from url_normalize import url_normalize
# python imports
import os
from typing import List, Dict, Any
import time
from generic_camunda_client import ApiException, CountResultDto, DeploymentWithDefinitionsDto, DeploymentDto, \
LockedExternalTaskDto, \
VariableValueDto, FetchExternalTasksDto, FetchExternalTaskTopicDto, ProcessDefinitionApi, \
ProcessInstanceWithVariablesDto, StartProcessInstanceDto, ProcessInstanceModificationInstructionDto, \
ProcessInstanceApi, ProcessInstanceDto, VersionApi, EvaluateDecisionDto, MessageApi, \
MessageCorrelationResultWithVariableDto, CorrelationMessageDto, ActivityInstanceDto, ExternalTaskFailureDto, \
IncidentApi, IncidentDto
import generic_camunda_client as openapi_client
# local imports
from .CamundaResources import CamundaResources
@library(scope='SUITE')
class CamundaLibrary:
"""
Library for Camunda integration in Robot Framework
= Installation =
== Camunda ==
Easiest to run Camunda in docker:
| docker run -d --name camunda -p 8080:8080 camunda/camunda-bpm-platform:run-latest
== CamundaLibrary ==
You can use pip for installing CamundaLibrary:
| pip install robotframework-camunda
= Usage =
The library provides convenience keywords for accessing Camunda via REST API. You may deploy models,
start processes, fetch workloads and complete them.
When initializing the library the default url for Camunda is `http://localhost:8080` which is the default when
running Camunda locally. It is best practice to provide a variable for the url, so it can be set dynamically
by the executing environment (like on local machine, in pipeline, on test system and production):
| Library | CamundaLibrary | ${CAMUNDA_URL} |
Running locally:
| robot -v "CAMUNDA_URL:http://localhost:8080" task.robot
Running in production
| robot -v "CAMUNDA_URL:https://camunda-prod.mycompany.io" task.robot
= Execution =
In contrast to external workers that are common for Camunda, tasks implemented with CamundaLibrary do not
_subscribe_ on certain topics. A robot tasks is supposed to run once. How frequent the task is executed is up
to the operating environment of the developer.
== Subscribing a topic / long polling ==
You may achieve a kind of subscription by providing the ``asyncResponseTimeout`` with the `Fetch workload`
keyword in order to achieve [https://docs.camunda.org/manual/latest/user-guide/process-engine/external-tasks/#long-polling-to-fetch-and-lock-external-tasks|Long Polling].
| ${variables} | fetch workload | my_topic | async_response_timeout=60000 |
| log | Waited at most 1 minute before this log statement got executed |
= Missing Keywords =
If you miss a keyword, you can utilize the REST API from Camunda by yourself using the [https://github.com/MarketSquare/robotframework-requests|RequestsLibrary].
With RequestsLibrary you can access all of the fully documented [https://docs.camunda.org/manual/latest/reference/rest/|Camunda REST API].
= Feedback =
Feedback is very much appreciated regardless if it is comments, reported issues, feature requests or even merge
requests. You are welcome to participating in any way at the [https://github.com/MarketSquare/robotframework-camunda|GitHub project of CamundaLibrary].
"""
WORKER_ID = f'robotframework-camundalibrary-{time.time()}'
EMPTY_STRING = ""
KNOWN_TOPICS: Dict[str, Dict[str, Any]] = {}
FETCH_RESPONSE: LockedExternalTaskDto = {}
DEFAULT_LOCK_DURATION = None
def __init__(self, host="http://localhost:8080"):
self._shared_resources = CamundaResources()
self.set_camunda_configuration(configuration={'host': host})
self.DEFAULT_LOCK_DURATION = self.reset_task_lock_duration()
@keyword(tags=['configuration'])
def set_camunda_configuration(self,configuration: dict):
if 'host' not in configuration.keys():
raise ValueError(f"Incomplete configuration. Configuration must include at least the Camunda host url:\t{configuration}")
# weird things happen when dictionary is not copied and keyword is called repeatedly. Somehow robot or python remember the configuration from the previous call
camunda_config = configuration.copy()
host = configuration['host']
camunda_config['host'] = url_normalize(f'{host}/engine-rest')
if 'api_key' in configuration.keys():
api_key = configuration['api_key']
camunda_config['api_key'] = {
'default': api_key
}
if 'api_key_prefix' in configuration.keys():
api_key_prefix = configuration['api_key_prefix']
camunda_config['api_key_prefix'] = {
'default': api_key_prefix
}
logger.debug(f"New configuration for Camunda client:\t{camunda_config}")
self._shared_resources.client_configuration = Configuration(**camunda_config)
@keyword(tags=['configuration'])
def set_camunda_url(self, url: str):
"""
Sets url for camunda eninge. Only necessary when URL cannot be set during initialization of this library or
you want to switch camunda url for some reason.
"""
if not url:
raise ValueError('Cannot set camunda engine url: no url given.')
self._shared_resources.camunda_url = url_normalize(f'{url}/engine-rest')
@keyword(tags=['task', 'configuration'])
def set_task_lock_duration(self, lock_duration: int):
"""
Sets lock duration used as default when fetching. Camunda locks a process instance for the period. If the
external task os not completed, Camunda gives the process instance free for another attempt only when lock
duration has expired.
Value is in milliseconds (1000 = 1 minute)
"""
try:
self.DEFAULT_LOCK_DURATION = int(lock_duration)
except ValueError:
logger.error(f'Failed to set lock duration. Value does not seem a valid integer:\t{lock_duration}')
@keyword(tags=['task', 'configuration'])
def reset_task_lock_duration(self):
"""
Counter keyword for "Set Task Lock Duration". Resets lock duration to the default. The default is either
environment variable CAMUNDA_TASK_LOCK_DURATION or 600000 (10 minutes).
"""
try:
lock_duration = int(os.environ.get('CAMUNDA_TASK_LOCK_DURATION', 600000))
except ValueError as e:
logger.warn(
f'Failed to interpret "CAMUNDA_TASK_LOCK_DURATION". Environment variable does not seem to contain a valid integer:\t{e}')
lock_duration = 600000
return lock_duration
@keyword(tags=['configuration'])
def get_camunda_url(self) -> str:
return self._shared_resources.camunda_url
@keyword(tags=['task'])
def get_amount_of_workloads(self, topic: str, **kwargs) -> int:
"""
Retrieves count of tasks. By default expects a topic name, but all parameters from the original endpoint
may be provided: https://docs.camunda.org/manual/latest/reference/rest/external-task/get-query-count/
"""
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ExternalTaskApi(api_client)
try:
response: CountResultDto = api_instance.get_external_tasks_count(topic_name=topic, **kwargs)
except ApiException as e:
raise ApiException(f'Failed to count workload for topic "{topic}":\n{e}')
logger.info(f'Amount of workloads for "{topic}":\t{response.count}')
return response.count
@keyword(tags=['deployment'])
def deploy(self, *args):
"""Creates a deployment from all given files and uploads them to camunda.
Return response from camunda rest api as dictionary.
Further documentation: https://docs.camunda.org/manual/latest/reference/rest/deployment/post-deployment/
By default, this keyword only deploys changed models and filters duplicates. Deployment name is the filename of
the first file.
Example:
| ${response} | *Deploy model from file* | _../bpmn/my_model.bpnm_ | _../forms/my_forms.html_ |
"""
if not args:
raise ValueError('Failed deploying model, because no file provided.')
if len(args) > 1:
# We have to use plain REST then when uploading more than 1 file.
return self.deploy_multiple_files(*args)
filename = os.path.basename(args[0])
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.DeploymentApi(api_client)
data = [*args]
deployment_name = filename
try:
response: DeploymentWithDefinitionsDto = api_instance.create_deployment(deploy_changed_only=True,
enable_duplicate_filtering=True,
deployment_name=deployment_name,
data=data)
logger.info(f'Response from camunda:\t{response}')
except ApiException as e:
raise ApiException(f'Failed to upload {filename}:\n{e}')
return response.to_dict()
def deploy_multiple_files(self, *args):
"""
# Due to https://jira.camunda.com/browse/CAM-13105 we cannot use generic camunda client when dealing with
# multiple files. We have to use plain REST then.
"""
fields = {
'deployment-name': f'{os.path.basename(args[0])}',
}
for file in args:
filename = os.path.basename(file)
fields[f'{filename}'] = (filename, open(file, 'rb'), 'application/octet-stream')
multipart_data = MultipartEncoder(
fields=fields
)
headers=self._shared_resources.api_client.default_headers.copy()
headers['Content-Type'] =multipart_data.content_type
logger.debug(multipart_data.fields)
response = requests.post(f'{self._shared_resources.camunda_url}/deployment/create', data=multipart_data,
headers=headers)
json = response.json()
try:
response.raise_for_status()
logger.debug(json)
except HTTPError as e:
raise ApiException(json)
return json
@keyword(tags=['deployment'])
def get_deployments(self, deployment_id: str = None, **kwargs):
"""
Retrieves all deployments that match given criteria. All parameters are available from https://docs.camunda.org/manual/latest/reference/rest/deployment/get-query/
Example:
| ${list_of_deployments} | get deployments | ${my_deployments_id} |
| ${list_of_deployments} | get deployments | id=${my_deployments_id} |
| ${list_of_deployments} | get deployments | after=2013-01-23T14:42:45.000+0200 |
"""
if deployment_id:
kwargs['id'] = deployment_id
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.DeploymentApi(api_client)
try:
response: List[DeploymentDto] = api_instance.get_deployments(**kwargs)
logger.info(f'Response from camunda:\t{response}')
except ApiException as e:
raise ApiException(f'Failed get deployments:\n{e}')
return [r.to_dict() for r in response]
@keyword(tags=['message'])
def deliver_message(self, message_name, **kwargs):
"""
Delivers a message using Camunda REST API: https://docs.camunda.org/manual/latest/reference/rest/message/post-message/
Example:
| ${result} | deliver message | msg_payment_received |
| ${result} | deliver message | msg_payment_received | process_variables = ${variable_dictionary} |
| ${result} | deliver message | msg_payment_received | business_key = ${correlating_business_key} |
"""
with self._shared_resources.api_client as api_client:
correlation_message: CorrelationMessageDto = CorrelationMessageDto(**kwargs)
correlation_message.message_name = message_name
if not 'result_enabled' in kwargs:
correlation_message.result_enabled = True
if 'process_variables' in kwargs:
correlation_message.process_variables = CamundaResources.dict_to_camunda_json(
kwargs['process_variables'])
serialized_message = api_client.sanitize_for_serialization(correlation_message)
logger.debug(f'Message:\n{serialized_message}')
headers=self._shared_resources.api_client.default_headers.copy()
headers['Content-Type'] = 'application/json'
try:
response = requests.post(f'{self._shared_resources.camunda_url}/message', json=serialized_message,
headers=headers)
except ApiException as e:
raise ApiException(f'Failed to deliver message:\n{e}')
try:
response.raise_for_status()
except HTTPError as e:
logger.error(e)
raise ApiException(response.text)
if correlation_message.result_enabled:
json = response.json()
logger.debug(json)
return json
else:
return {}
@keyword(tags=['task'])
def fetch_workload(self, topic: str, async_response_timeout=None, use_priority=None, **kwargs) -> Dict:
"""
Locks and fetches workloads from camunda on a given topic. Returns a list of variable dictionary.
Each dictionary representing 1 workload from a process instance.
If a process instance was fetched, the process instance is cached and can be retrieved by keyword
`Get Fetch Response`
The only mandatory parameter for this keyword is *topic* which is the name of the topic to fetch workload from.
More parameters can be added from the Camunda documentation: https://docs.camunda.org/manual/latest/reference/rest/external-task/fetch/
If not provided, this keyword will use a lock_duration of 60000 ms (10 minutes) and set {{deserialize_value=True}}
Examples:
| ${input_variables} | *Create Dictionary* | _name=Robot_ |
| | *start process* | _my_demo_ | _${input_variables}_ |
| ${variables} | *fetch workload* | _first_task_in_demo_ |
| | *Dictionary Should Contain Key* | _${variables}_ | _name_ |
| | *Should Be Equal As String* | _Robot_ | _${variables}[name]_ |
Example deserializing only some variables:
| ${input_variables} | *Create Dictionary* | _name=Robot_ | _profession=Framework_ |
| | *start process* | _my_demo_ | _${input_variables}_ |
| ${variables_of_interest} | *Create List* | _profession_ |
| ${variables} | *Fetch Workload* | _first_task_in_demo_ | _variables=${variables_of_interest}_ |
| | *Dictionary Should Not Contain Key* | _${variables}_ | _name_ |
| | *Dictionary Should Contain Key* | _${variables}_ | _profession_ |
| | *Should Be Equal As String* | _Framework_ | _${variables}[profession]_ |
"""
api_response = []
with self._shared_resources.api_client as api_client:
# Create an instance of the API class
api_instance = openapi_client.ExternalTaskApi(api_client)
if 'lock_duration' not in kwargs:
kwargs['lock_duration'] = self.DEFAULT_LOCK_DURATION
if 'deserialize_values' not in kwargs:
kwargs['deserialize_values'] = False
topic_dto = FetchExternalTaskTopicDto(topic_name=topic, **kwargs)
fetch_external_tasks_dto = FetchExternalTasksDto(worker_id=self.WORKER_ID, max_tasks=1,
async_response_timeout=async_response_timeout,
use_priority=use_priority,
topics=[topic_dto])
try:
api_response = api_instance.fetch_and_lock(fetch_external_tasks_dto=fetch_external_tasks_dto)
logger.info(api_response)
except ApiException as e:
raise ApiException("Exception when calling ExternalTaskApi->fetch_and_lock: %s\n" % e)
work_items: List[LockedExternalTaskDto] = api_response
if work_items:
logger.debug(f'Received {len(work_items)} work_items from camunda engine for topic:\t{topic}')
else:
logger.debug(f'Received no work items from camunda engine for topic:\t{topic}')
if not work_items:
return {}
self.FETCH_RESPONSE = work_items[0]
variables: Dict[str, VariableValueDto] = self.FETCH_RESPONSE.variables
return CamundaResources.convert_openapi_variables_to_dict(variables)
@keyword(tags=['task'])
def get_fetch_response(self):
"""Returns cached response from the last call of `fetch workload`.
The response contains all kind of data that is required for custom REST Calls.
Example:
| *** Settings *** |
| *Library* | RequestsLibrary |
| |
| *** Tasks *** |
| | *Create Session* | _alias=camunda_ | _url=http://localhost:8080_ |
| | ${variables} | *fetch workload* | _my_first_task_in_demo_ | |
| | ${fetch_response} | *get fetch response* | | |
| | *POST On Session* | _camunda_ | _engine-rest/external-task/${fetch_response}[id]/complete_ | _json=${{ {'workerId': '${fetch_response}[worker_id]'} }}_ |
"""
if self.FETCH_RESPONSE:
return self.FETCH_RESPONSE.to_dict()
return self.FETCH_RESPONSE
@keyword("Drop fetch response", tags=['task'])
def drop_fetch_response(self):
"""
Removes last process instance from cache.
When you use common keywords like `complete task` or `unlock` or any other keyword finishing execution of a task,
you do not need to call this keyword, as it is called implicitly.
This keyword is handy, when you mix CamundaLibrary keywords and custom REST calls to Camunda API. In such
scenarios you might want to empty the cache.
"""
self.FETCH_RESPONSE = {}
@keyword(tags=['task', 'complete'])
def throw_bpmn_error(self, error_code: str, error_message: str = None, variables: Dict[str, Any] = None,
files: Dict = None):
if not self.FETCH_RESPONSE:
logger.warn('No task to complete. Maybe you did not fetch and lock a workitem before?')
else:
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ExternalTaskApi(api_client)
variables = CamundaResources.convert_dict_to_openapi_variables(variables)
openapi_files = CamundaResources.convert_file_dict_to_openapi_variables(files)
variables.update(openapi_files)
bpmn_error = openapi_client.ExternalTaskBpmnError(worker_id=self.WORKER_ID,
error_message=error_message,
error_code=error_code,
variables=variables)
try:
logger.debug(f"Sending BPMN error for task:\n{bpmn_error}")
api_instance.handle_external_task_bpmn_error(self.FETCH_RESPONSE.id,
external_task_bpmn_error=bpmn_error)
self.drop_fetch_response()
except ApiException as e:
raise ApiException(f"Exception when calling ExternalTaskApi->handle_external_task_bpmn_error: {e}\n")
@keyword(tags=['task', 'complete'])
def notify_failure(self, **kwargs):
"""
Raises a failure to Camunda. When retry counter is less than 1, an incident is created by Camunda.
You can specify number of retries with the *retries* argument. If current fetched process instance already has
*retries* parameter set, the *retries* argument of this keyword is ignored. Instead, the retries counter will
be decreased by 1.
CamundaLibrary takes care of providing the worker_id and task_id. *retry_timeout* is equal to *lock_duration* for external tasks.
Check for camunda client documentation for all parameters of the request body: https://noordsestern.gitlab.io/camunda-client-for-python/7-15-0/docs/ExternalTaskApi.html#handle_failure
Example:
| *notify failure* | | |
| *notify failure* | retries=3 | error_message=Task failed due to... |
"""
current_process_instance = self.FETCH_RESPONSE
if not current_process_instance:
logger.warn('No task to notify failure for. Maybe you did not fetch and lock a workitem before?')
else:
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ExternalTaskApi(api_client)
if 'retry_timeout' not in kwargs or None is kwargs['retry_timeout'] or not kwargs['retry_timeout']:
kwargs['retry_timeout'] = self.DEFAULT_LOCK_DURATION
if None is not current_process_instance.retries:
kwargs['retries'] = current_process_instance.retries - 1
external_task_failure_dto = ExternalTaskFailureDto(worker_id=self.WORKER_ID, **kwargs)
try:
api_instance.handle_failure(id=current_process_instance.id,
external_task_failure_dto=external_task_failure_dto)
self.drop_fetch_response()
except ApiException as e:
raise ApiException("Exception when calling ExternalTaskApi->handle_failure: %s\n" % e)
@keyword(tags=['incident'])
def get_incidents(self, **kwargs):
"""
Retrieves incidents matching given filter arguments.
For full parameter list checkout: https://noordsestern.gitlab.io/camunda-client-for-python/7-15-0/docs/IncidentApi.html#get_incidents
Example:
| ${all_incidents} | *get incidents* | |
| ${incidents_of_process_instance | *get incidentse* | process_instance_id=${process_instance}[process_instance_id] |
"""
with self._shared_resources.api_client as api_client:
api_instance: IncidentApi = openapi_client.IncidentApi(api_client)
try:
response: List[IncidentDto] = api_instance.get_incidents(**kwargs)
except ApiException as e:
raise ApiException(f'Failed to get incidents:\n{e}')
return [incident.to_dict() for incident in response]
@keyword(tags=['task', 'complete'])
def complete_task(self, result_set: Dict[str, Any] = None, files: Dict = None):
"""
Completes the task that was fetched before with `fetch workload`.
*Requires `fetch workload` to run before this one, logs warning instead.*
Additional variables can be provided as dictionary in _result_set_ .
Files can be provided as dictionary of filename and patch.
Examples:
| _# fetch and immediately complete_ |
| | *fetch workload* | _my_topic_ |
| | *complete task* | |
| |
| _# fetch and complete with return values_ |
| | *fetch workload* | _decide_on_dish_ |
| ${new_variables} | *Create Dictionary* | _my_dish=salad_ |
| | *complete task* | _result_set=${new_variables}_ |
| |
| _# fetch and complete with return values and files_ |
| | *fetch workload* | _decide_on_haircut_ |
| ${return_values} | *Create Dictionary* | _style=short hair_ |
| ${files} | *Create Dictionary* | _should_look_like=~/favorites/beckham.jpg_ |
| | *complete task* | _${return_values}_ | _${files}_ |
"""
if not self.FETCH_RESPONSE:
logger.warn('No task to complete. Maybe you did not fetch and lock a workitem before?')
else:
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ExternalTaskApi(api_client)
variables = CamundaResources.convert_dict_to_openapi_variables(result_set)
openapi_files = CamundaResources.convert_file_dict_to_openapi_variables(files)
variables.update(openapi_files)
complete_task_dto = openapi_client.CompleteExternalTaskDto(worker_id=self.WORKER_ID,
variables=variables)
try:
logger.debug(f"Sending to Camunda for completing Task:\n{complete_task_dto}")
api_instance.complete_external_task_resource(self.FETCH_RESPONSE.id,
complete_external_task_dto=complete_task_dto)
self.drop_fetch_response()
except ApiException as e:
raise ApiException(f"Exception when calling ExternalTaskApi->complete_external_task_resource: {e}\n")
@keyword(tags=['task', 'variable', 'file'])
def download_file_from_variable(self, variable_name: str) -> str:
"""
For performance reasons, files are not retrieved automatically during `fetch workload`. If your task requires
a file that is attached to a process instance, you need to download the file explicitly.
Example:
| ${variables} | *fetch workload* | _first_task_in_demo_ |
| | *Dictionary Should Contain Key* | _${variables}_ | _my_file_ |
| ${file} | *Download File From Variable* | ${variables}[my_file] | |
"""
if not self.FETCH_RESPONSE:
logger.warn('Could not download file for variable. Maybe you did not fetch and lock a workitem before?')
else:
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ProcessInstanceApi(api_client)
try:
response = api_instance.get_process_instance_variable_binary(
id=self.FETCH_RESPONSE.process_instance_id, var_name=variable_name)
logger.debug(response)
except ApiException as e:
raise ApiException(f"Exception when calling ExternalTaskApi->get_process_instance_variable_binary: {e}\n")
return response
@keyword(tags=['task', 'complete'])
def unlock(self):
"""
Unlocks recent task.
"""
if not self.FETCH_RESPONSE:
logger.warn('No task to unlock. Maybe you did not fetch and lock a workitem before?')
else:
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ExternalTaskApi(api_client)
try:
api_instance.unlock(self.FETCH_RESPONSE.id)
self.drop_fetch_response()
except ApiException as e:
raise ApiException(f"Exception when calling ExternalTaskApi->unlock: {e}\n")
@keyword(tags=['process'])
def start_process(self, process_key: str, variables: Dict = None, files: Dict = None,
before_activity_id: str = None, after_activity_id: str = None, **kwargs) -> Dict:
"""
Starts a new process instance from a process definition with given key.
variables: _optional_ dictionary like: {'variable name' : 'value'}
files: _optional_ dictionary like: {'variable name' : path}. will be attached to variables in Camunda
before_activity_id: _optional_ id of activity at which the process starts before. *CANNOT BE USED TOGETHER WITH _after_activity_id_*
after_activity_id: _optional_ id of activity at which the process starts after. *CANNOT BE USED TOGETHER WITH _before_activity_id_*
Returns response from Camunda as dictionary
== Examples ==
| `start process` | apply for job promotion | _variables_= { 'employee' : 'John Doe', 'permission_for_application_granted' : True} | _files_ = { 'cv' : 'documents/my_life.md'} | _after_activity_id_ = 'Activity_ask_boss_for_persmission' |
| `start process` | apply for promotion | business_key=John again |
"""
if not process_key:
raise ValueError('Error starting process. No process key provided.')
if before_activity_id and after_activity_id:
raise AssertionError('2 activity ids provided. Cannot start before and after an activity.')
with self._shared_resources.api_client as api_client:
api_instance: ProcessDefinitionApi = openapi_client.ProcessDefinitionApi(api_client)
openapi_variables = CamundaResources.convert_dict_to_openapi_variables(variables)
openapi_files = CamundaResources.convert_file_dict_to_openapi_variables(files)
openapi_variables.update(openapi_files)
if before_activity_id or after_activity_id:
instruction: ProcessInstanceModificationInstructionDto = ProcessInstanceModificationInstructionDto(
type='startBeforeActivity' if before_activity_id else 'startAfterActivity',
activity_id=before_activity_id if before_activity_id else after_activity_id,
)
kwargs.update(start_instructions=[instruction])
start_process_instance_dto: StartProcessInstanceDto = StartProcessInstanceDto(
variables=openapi_variables,
**kwargs
)
try:
response: ProcessInstanceWithVariablesDto = api_instance.start_process_instance_by_key(
key=process_key,
start_process_instance_dto=start_process_instance_dto
)
except ApiException as e:
raise ApiException(f'Failed to start process {process_key}:\n{e}')
logger.info(f'Response:\n{response}')
return response.to_dict()
@keyword(tags=['process'])
def delete_process_instance(self, process_instance_id):
"""
USE WITH CARE: Deletes a process instance by id. All data in this process instance will be lost.
"""
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.ProcessInstanceApi(api_client)
try:
response = api_instance.delete_process_instance(id=process_instance_id)
except ApiException as e:
raise ApiException(f'Failed to delete process instance {process_instance_id}:\n{e}')
@keyword(tags=['process'])
def get_all_active_process_instances(self, process_definition_key):
"""
Returns a list of process instances that are active for a certain process definition identified by key.
"""
return self.get_process_instances(process_definition_key=process_definition_key, active='true')
@keyword(tags=['process'])
def get_process_instances(self, **kwargs):
"""
Queries Camunda for process instances that match certain criteria.
*Be aware, that boolean value must be strings either 'true' or 'false'*
== Arguments ==
| async_req | execute request asynchronously |
| sort_by | Sort the results lexicographically by a given criterion. Must be used in conjunction with the sortOrder parameter. |
| sort_order | Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. |
| first_result | Pagination of results. Specifies the index of the first result to return. |
| max_results | Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. |
| process_instance_ids | Filter by a comma-separated list of process instance ids. |
| business_key | Filter by process instance business key. |
| business_key_like | Filter by process instance business key that the parameter is a substring of. |
| case_instance_id | Filter by case instance id. |
| process_definition_id | Filter by the deployment the id belongs to. |
| process_definition_key | Filter by the key of the process definition the instances run on. |
| process_definition_key_in | Filter by a comma-separated list of process definition keys. A process instance must have one of the given process definition keys. |
| process_definition_key_not_in | Exclude instances by a comma-separated list of process definition keys. A process instance must not have one of the given process definition keys. |
| deployment_id | Filter by the deployment the id belongs to. |
| super_process_instance | Restrict query to all process instances that are sub process instances of the given process instance. Takes a process instance id. |
| sub_process_instance | Restrict query to all process instances that have the given process instance as a sub process instance. Takes a process instance id. |
| super_case_instance | Restrict query to all process instances that are sub process instances of the given case instance. Takes a case instance id. |
| sub_case_instance | Restrict query to all process instances that have the given case instance as a sub case instance. Takes a case instance id. |
| active | Only include active process instances. Value may only be true, as false is the default behavior. |
| suspended | Only include suspended process instances. Value may only be true, as false is the default behavior. |
| with_incident | Filter by presence of incidents. Selects only process instances that have an incident. |
| incident_id | Filter by the incident id. |
| incident_type | Filter by the incident type. See the [User Guide](https://docs.camunda.org/manual/latest/user-guide/process-engine/incidents/#incident-types) for a list of incident types. |
| incident_message | Filter by the incident message. Exact match. |
| incident_message_like | Filter by the incident message that the parameter is a substring of. |
| tenant_id_in | Filter by a comma-separated list of tenant ids. A process instance must have one of the given tenant ids. |
| without_tenant_id | Only include process instances which belong to no tenant. |
| process_definition_without_tenant_id | Only include process instances which process definition has no tenant id. |
| activity_id_in | Filter by a comma-separated list of activity ids. A process instance must currently wait in a leaf activity with one of the given activity ids. |
| root_process_instances | Restrict the query to all process instances that are top level process instances. |
| leaf_process_instances | Restrict the query to all process instances that are leaf instances. (i.e. don't have any sub instances). |
| variables | Only include process instances that have variables with certain values. Variable filtering expressions are comma-separated and are structured as follows: A valid parameter value has the form `key_operator_value`. `key` is the variable name, `operator` is the comparison operator to be used and `value` the variable value. **Note**: Values are always treated as String objects on server side. Valid `operator` values are: `eq` - equal to; `neq` - not equal to; `gt` - greater than; `gteq` - greater than or equal to; `lt` - lower than; `lteq` - lower than or equal to; `like`. `key` and `value` may not contain underscore or comma characters. |
| variable_names_ignore_case | Match all variable names in this query case-insensitively. If set to true variableName and variablename are treated as equal. |
| variable_values_ignore_case | Match all variable values in this query case-insensitively. If set to true variableValue and variablevalue are treated as equal. |
| _preload_content | if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True. |
| _request_timeout | timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts. |
"""
with self._shared_resources.api_client as api_client:
api_instance: ProcessInstanceApi = openapi_client.ProcessInstanceApi(api_client)
try:
response: List[ProcessInstanceDto] = api_instance.get_process_instances(**kwargs)
except ApiException as e:
raise ApiException(f'Failed to get process instances of process:\n{e}')
return [process_instance.to_dict() for process_instance in response]
@keyword(tags=['version'])
def get_version(self):
"""
Returns Version of Camunda.
== Example ==
| ${camunda_version_dto} | Get Version |
| ${camunda_version} | Set Variable | ${camunda_version_dto.version} |
"""
with self._shared_resources.api_client as api_client:
api_instance: VersionApi = openapi_client.VersionApi(api_client)
return api_instance.get_rest_api_version()
@keyword(tags=['process'])
def get_process_definitions(self, **kwargs):
"""
Returns a list of process definitions that fulfill given parameters.
See Rest API documentation on ``https://docs.camunda.org/manual`` for available parameters.
== Example ==
| ${list} | Get Process Definitions | name=my_process_definition |
"""
with self._shared_resources.api_client as api_client:
api_instance: ProcessDefinitionApi = openapi_client.ProcessDefinitionApi(api_client)
try:
response = api_instance.get_process_definitions(**kwargs)
except ApiException as e:
raise ApiException(f'Failed to get process definitions:\n{e}')
return response
@keyword(tags=['process'])
def get_activity_instance(self, id: str):
"""
Returns an Activity Instance (Tree) for a given process instance.
== Example ==
| ${tree} | Get Activity Instance | id=fcab43bc-b970-11eb-be75-0242ac110002 |
https://docs.camunda.org/manual/7.5/reference/rest/process-instance/get-activity-instances/
"""
with self._shared_resources.api_client as api_client:
api_instance: ProcessInstanceApi = openapi_client.ProcessInstanceApi(api_client)
try:
response: ActivityInstanceDto = api_instance.get_activity_instance_tree(id)
except ApiException as e:
raise ApiException(f'failed to get activity tree for process instance with id {id}:\n{e}')
return response.to_dict()
@keyword(tags=['process'])
def get_process_instance_variable(self, process_instance_id: str, variable_name: str, auto_type_conversion: bool = True):
"""
Returns the variable with the given name from the process instance with
the given process_instance_id.
Parameters:
- ``process_instance_id``: ID of the target process instance
- ``variable_name``: name of the variable to read
- ``auto_type_conversion``: Converts JSON structures automatically in to python data structures. Default: True. When False, values are not retrieved for JSON variables, but metadata is. Only useful when you want to verify that Camunda holds certain data types.%
== Example ==
| ${variable} | Get Process Instance Variable |
| ... | process_instance_id=fcab43bc-b970-11eb-be75-0242ac110002 |
| ... | variable_name=foo |
See also:
https://docs.camunda.org/manual/latest/reference/rest/process-instance/variables/get-single-variable/
"""
with self._shared_resources.api_client as api_client:
api_instance: ProcessInstanceApi = openapi_client.ProcessInstanceApi(api_client)
try:
response = api_instance.get_process_instance_variable(
id=process_instance_id, var_name=variable_name, deserialize_value=not auto_type_conversion)
except ApiException as e:
raise ApiException(f'Failed to get variable {variable_name} from '
f'process instance {process_instance_id}:\n{e}')
if auto_type_conversion:
return CamundaResources.convert_variable_dto(response)
return response
@keyword(tags=['decision'])
def evaluate_decision(self, key: str, variables: dict) -> list:
"""
Evaluates a given decision and returns the result.
The input values of the decision have to be supplied with `variables`.
== Example ==
| ${variables} | Create Dictionary | my_input=42 |
| ${response} | Evaluate Decision | my_decision_table | ${variables} |
"""
with self._shared_resources.api_client as api_client:
api_instance = openapi_client.DecisionDefinitionApi(api_client)
dto = CamundaResources.convert_dict_to_openapi_variables(variables)
try:
response = api_instance.evaluate_decision_by_key(
key=key,
evaluate_decision_dto=openapi_client.EvaluateDecisionDto(dto))
return [CamundaResources.convert_openapi_variables_to_dict(r)
for r in response]
except ApiException as e:
raise ApiException(f'Failed to evaluate decision {key}:\n{e}') | /robotframework_camunda-2.0.3-py3-none-any.whl/CamundaLibrary/CamundaLibrary.py | 0.774029 | 0.164852 | CamundaLibrary.py | pypi |
import requests
import base64
import json
import time
import ntpath
import os
class CaptureFastBase:
accesstoken: str = None
def _init_client(self):
headers = {'content-type': 'application/x-www-form-urlencoded'}
authRequest = {
"username": self.cfusername,
"password": self.cfpassword,
"grant_type": "password"
}
response = requests.request(
"POST", "https://api.capturefast.com/token",
headers=headers,
data=authRequest
)
if not response.json().get('access_token'):
raise Exception(response.json().get('error_description'))
time.sleep(1)
self.accesstoken = response.json().get('access_token')
def UploadDocument(self, filepath, documenttypeid):
"""Method used to upload your documents to Capturefast.
Args:
filepath(str): path of the document to be uploaded
documenttypeid(int): ID of the document you used in Capturefast
Returns:
int: The documentId created for the uploaded document that is created by Capturefast and you need this documentId to get the data
"""
fileContent = ''
with open(filepath, "rb") as f:
fileContent = base64.b64encode(f.read()).decode('ascii')
headers = {
'content-type': 'application/json',
'Authorization': 'Bearer ' + self.accesstoken
}
document = {
'TeamId': self.teamid,
'DocumentTypeId': documenttypeid,
'Files': [{'FileName': os.path.basename(filepath),
'Content': fileContent}]
}
try:
response = requests.request("POST",
"https://api.capturefast.com/api/Upload/Document",
headers=headers,
data=json.dumps(document))
if(response.json().get('ResultCode') != 0):
raise Exception(response.json().get('ResultMessage'))
except Exception as ex:
raise Exception("Capturefast Communication Error")
return response.json().get('DocumentId')
def GetDocumentData(self, documentid, timeoutinseconds=100):
"""Getting data of a document uploaded to Capturefat
Args:
documentid(int): Documentid from UploadDocument method
timeoutinseconds(int): The required timeout for data retrieval depending on the time the document spends in the processing phase değeri.Default 100 second.
Returns:
Json: Processing and content data of the submitted document
{
"DocumentName":"",
"DocReferenceKey":"",
"DocumentId":0,
"TeamId":0,
"TemplateId":0,
"TemplateName":",
"DocumentTypeId":0,
"DocumentTypeName":"",
"CapturedUserId":0,
"CapturedDate":"",
"CapturedUser":"",
"VerifiedUserId":0,
"VerifiedDate":,
"VerifiedUser":,
"AdditionalData":,
"Pages":[
{
"PageId":0,
"PageName":"Page #1",
"PageOrder":1,
"OrginalFileName":"",
"Fields":[
{
"FieldName":"",
"Value":"",
"ConfidenceLevel":100,
"Coordinate":""
}
]
}
],
"ResultCode":0,
"ResultMessage":""
}
"""
headers = {
'content-type': 'application/json',
'Authorization': 'Bearer ' + self.accesstoken
}
jsonDoc = {}
while(timeoutinseconds > 0):
timeoutinseconds -= 5
if(timeoutinseconds < 0):
raise Exception("Sorry, data is not available")
try:
response = requests.request("GET",
"https://api.capturefast.com/api/Download/Data?documentId=" + str(documentid),
headers=headers)
except Exception as ex:
raise Exception("Capturefast Communication Error")
jsonDoc = response.json()
resultCode = jsonDoc['ResultCode']
if(resultCode == 0):
break
elif(resultCode == 100):
continue
else:
time.sleep(5)
jsonDoc = self.GetDocumentData(documentId, timeoutinseconds)
break
return jsonDoc
class CaptureFast(CaptureFastBase):
"""CaptureFast is an online document capture application.
With the application, you can extract data from your documents and transfer
your digitalized data to the desired environment for processing.
To use the library, you can first create a user and create your document types by watching the video at https://www.youtube.com/watch?v=AMfOZBkK-M4.
Args:
username(str): The username you create on Capturefast.
password(str): The password you create on Capturefast.
teamid(str): The team you create on Capturefast.
Returns:
Automatic token will be created from Capturefast, and you can send and receive your documents for capture using the UploadDocument and GetDocumentData methods.
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self, username: str = None, password: str = None, teamid: str = None):
self.cfusername = username
self.cfpassword = password
self.teamid = teamid
self._init_client() | /robotframework-capturefast-1.8.0.tar.gz/robotframework-capturefast-1.8.0/CaptureFast.py | 0.541651 | 0.150653 | CaptureFast.py | pypi |
from typing import List, Optional, Union
from robot.api import logger
from robot.utils import ConnectionCache
from cassandra.auth import PlainTextAuthProvider
from cassandra.policies import TokenAwarePolicy, DCAwareRoundRobinPolicy
from cassandra.cluster import Cluster, ResponseFuture, ResultSet, Session
class CassandraCQLLibrary(object):
"""
Library for executing CQL statements in database [ http://cassandra.apache.org/ | Apache Cassandra ].
== Dependencies ==
| datastax python-driver | https://github.com/datastax/python-driver |
| robot framework | http://robotframework.org |
== Additional Information ==
- [ http://www.datastax.com/documentation/cql/3.1/cql/cql_using/about_cql_c.html | CQL query language]
== Example ==
| *Settings* | *Value* | *Value* | *Value* |
| Library | CassandraCQLLibrary |
| Library | Collections |
| Suite Setup | Connect To Cassandra | 192.168.33.10 | 9042 |
| Suite Teardown | Disconnect From Cassandra |
| *Test Cases* | *Action* | *Argument* | *Argument* |
| Get Keyspaces |
| | Execute CQL | USE system |
| | ${result}= | Execute CQL | SELECT * FROM schema_keyspaces; |
| | Log List | ${result} |
| | Log | ${result[1].keyspace_name} |
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self) -> None:
""" Initialization. """
self._connection: Optional[Session] = None
self._cache = ConnectionCache()
@property
def keyspace(self) -> str:
"""Get keyspace Cassandra.
Returns:
keyspace: the name of the keyspace in Cassandra.
"""
if self._connection is None:
raise Exception('There is no connection to Cassandra cluster.')
return self._connection.keyspace
def connect_to_cassandra(self, host: str, port: Union[int, str] = 9042, alias: str = None, keyspace: str = None,
username: str = None, password: str = '') -> Session:
"""
Connect to Apache Cassandra cluster.
AllowAllAuthenticator and PasswordAuthenticator are supported as authentication backend.
This setting should be in configuration file cassandra.yaml:
by default:
| authenticator: AllowAllAuthenticator
or for password authentification:
| authenticator: PasswordAuthenticator
*Args:*\n
_host_ - IP address or host name of a cluster node;\n
_port_ - connection port;\n
_alias_ - connection alias;\n
_keyspace_ - the name of the keyspace that the UDT is defined in;\n
_username_ - username to connect to cassandra
_password_ - password for username
*Returns:*\n
Index of current connection.
*Example:*\n
| Connect To Cassandra | 192.168.1.108 | 9042 | alias=cluster1 |
"""
logger.info('Connecting using : host={0}, port={1}, alias={2}'.format(host, port, alias))
try:
auth_provider = PlainTextAuthProvider(username=username, password=password) if username else None
cluster = Cluster([host], port=int(port), auth_provider=auth_provider,
load_balancing_policy=TokenAwarePolicy(DCAwareRoundRobinPolicy()))
session = cluster.connect()
if keyspace is not None:
session.set_keyspace(keyspace)
self._connection = session
return self._cache.register(self._connection, alias)
except Exception as e:
raise Exception('Connect to Cassandra error: {0}'.format(e))
def disconnect_from_cassandra(self) -> None:
"""
Close current connection with cluster.
*Example:*\n
| Connect To Cassandra | server-host.local |
| Disconnect From Cassandra |
"""
if self._connection is None:
raise Exception('There is no connection to Cassandra cluster.')
self._connection.shutdown()
def close_all_cassandra_connections(self) -> None:
"""
Close all connections with cluster.
This keyword is used to close all connections only in case if there are several open connections.
Do not use keywords [#Disconnect From Cassandra|Disconnect From Cassandra] and
[#Close All Cassandra Connections|Close All Cassandra Connections] together.
After this keyword is executed, the index returned by [#Connect To Cassandra | Connect To Cassandra]
starts at 1.
*Example:*\n
| Connect To Cassandra | 192.168.1.108 | alias=cluster1 |
| Connect To Cassandra | 192.168.1.208 | alias=cluster2 |
| Close All Cassandra Connections |
"""
self._connection = self._cache.close_all(closer_method='shutdown')
def switch_cassandra_connection(self, index_or_alias: Union[int, str]) -> int:
"""
Switch between active connections with several clusters using their index or alias.
Connection alias is set in keyword [#Connect To Cassandra|Connect To Cassandra],
which also returns the index of connection.
*Args:*\n
_index_or_alias_ - connection index or alias;
*Returns:*\n
Index of the previous connection.
*Example:* (switch by alias)\n
| Connect To Cassandra | 192.168.1.108 | alias=cluster1 |
| Connect To Cassandra | 192.168.1.208 | alias=cluster2 |
| Switch Cassandra Connection | cluster1 |
*Example:* (switch by index)\n
| ${cluster1}= | Connect To Cassandra | 192.168.1.108 |
| ${cluster2}= | Connect To Cassandra | 192.168.1.208 |
| ${previous_index}= | Switch Cassandra Connection | ${cluster1} |
| Switch Cassandra Connection | ${previous_index} |
=>\n
${cluster1}= 1\n
${cluster2}= 2\n
${previous_index}= 2\n
"""
old_index = self._cache.current_index
self._connection = self._cache.switch(index_or_alias)
return old_index
def execute_cql(self, statement: str) -> ResultSet:
"""
Execute CQL statement.
*Args:*\n
_statement_ - CQL statement;
*Returns:*\n
Execution result.
*Example:*\n
| ${result}= | Execute CQL | SELECT * FROM system.schema_keyspaces; |
| Log | ${result[1].keyspace_name} |
=>\n
system
"""
if not self._connection:
raise Exception('There is no connection to Cassandra cluster.')
logger.debug("Executing :\n %s" % statement)
result = self._connection.execute(statement, timeout=60)
return result
def execute_async_cql(self, statement: str) -> ResponseFuture:
"""
Execute asynchronous CQL statement.
*Args:*\n
_statement_ - CQL statement;
*Returns:*\n
Object that can be used with keyword [#Get Async Result | Get Async Result] to get the result of CQL statement.
"""
if not self._connection:
raise Exception('There is no connection to Cassandra cluster.')
logger.debug("Executing :\n %s" % statement)
future = self._connection.execute_async(statement)
return future
def get_async_result(self, future: ResponseFuture) -> ResultSet:
"""
Get the result of asynchronous CQL statement.
*Args:*\n
_future_ - object, returned as a result of keyword [#Execute Async Cql | Execute Async Cql]
*Returns:*\n
Result of asynchronous CQL statement.
*Example:*\n
| ${obj}= | Execute Async Cql | SELECT * FROM system.schema_keyspaces; |
| Sleep | 5 |
| ${result}= | Get Async Result | ${obj} |
| Log | ${result[1].keyspace_name} |
=>\n
system
"""
try:
result = future.result()
except Exception as e:
raise Exception('Operation failed: {0}'.format(e))
return result
def get_column(self, column: str, statement: str) -> List[str]:
"""
Get column values from the data sampling.
*Args:*\n
_column_ - name of the column which value you want to get;\n
_statement_ - CQL select statement.
*Returns:*\n
List of column values.
*Example:*\n
| ${result}= | Get Column | keyspace_name | SELECT * FROM system.schema_keyspaces LIMIT 2; |
| Log List | ${result} |
=>\n
| List length is 2 and it contains following items:
| 0: test
| 1: OpsCenter
"""
result = self.execute_cql(statement)
result_values = []
for item in result:
column_attr = str(getattr(item, column))
result_values.append(column_attr)
return result_values
def get_column_from_schema_keyspaces(self, column: str) -> List[str]:
"""Get column values from the table schema_keyspaces.
*Args:*\n
_column_ - the name of the column which values you want to get;\n
*Returns:*\n
List of column values from the table schema_keyspaces.
"""
statement = """SELECT *
FROM system.schema_keyspaces"""
return self.get_column(column, statement) | /robotframework-cassandracqllibrary-2.0.1.tar.gz/robotframework-cassandracqllibrary-2.0.1/src/CassandraCQLLibrary.py | 0.919841 | 0.253693 | CassandraCQLLibrary.py | pypi |
__author__ = 'Tom Werner'
__email__ = 'tom@fluffycloudsandlines.cc'
__version__ = '0.1.0'
import subprocess
import logging
import json
from robot.api.deco import keyword, library
from robot.running.model import TestSuite
from robot.model.body import BodyItem
@library(scope='TEST SUITE', version=__version__)
class CINCLibrary(object):
def __init__(self):
"""Intiliase CINC Auditor Library
Init our library to be a robot listener, using the v2 API.
This allows hooking into the execution lifecycle of a Test Suite to
dynamically add cinc controls into the suite as test cases.
"""
self.ROBOT_LIBRARY_LISTENER = self
self.ROBOT_LISTENER_API_VERSION = 3
self.current_suite = None
def start_suite(self, suite, result):
"""Start Suite Hook
Listener API Hook, invoked when the suite starts.
Save the suite reference so that we can append tests to the handle.
"""
self.current_suite = suite
@keyword("Validate cinc Profile")
def validate_profile(self, profile, auditor_executable='cinc-auditor'):
"""Validate CINC Profile
Run the auditor tool to parse the provided profile to allow us to fail quick. Parse the number of controls for logging purposes.
:param str cinc-auditor: Optional over-ride of the executable name, incase the upstream tool (or other whitelabel) is being used instead.
:param str profile: Path to the profile to be exeucted.
:raise: AssertionError if the profile is invalid
"""
# Run `cinc-auditor json`` which parses the profile and provides
# a list of controls to then create dynamic test cases for
cinc_validate_execution = subprocess.run([auditor_executable, "json", profile], capture_output=True)
if cinc_validate_execution.returncode == 0:
cinc_validation_result = json.loads(cinc_validate_execution.stdout)
logging.info("Found {0} controls in {1}".format(len(cinc_validation_result["controls"]), profile))
return True
else:
raise AssertionError("Non zero return from cinc validate ... [{0}]. {1}".format(
cinc_validate_execution.returncode,
cinc_validate_execution.stdout
))
@keyword("Execute cinc Profile")
def exec_profile(self, profile, auditor_executable='cinc-auditor', backend="local"):
cinc_execution = subprocess.run([auditor_executable, "exec", profile, "--reporter", "json"], capture_output=True)
if cinc_execution.returncode in (0,100,101):
cinc_execution_json = json.loads(cinc_execution.stdout)
logging.debug(json.dumps(cinc_execution_json))
for control in cinc_execution_json["profiles"][0]["controls"]:
tc = self.current_suite.tests.create(name="cinc Control - [ {0} ]".format(control['title']))
tc.body.create_keyword(name="Process cinc Control Result", args=[control])
else:
logging.info(cinc_execution.returncode)
logging.info(cinc_execution.stdout)
@keyword("Process cinc Control Result")
def process_cinc_control_result(self, control_json):
logging.debug(control_json)
for result in control_json['results']:
if result['status'] != 'passed':
raise AssertionError("Failed")
globals()[__name__] = CINCLibrary | /robotframework-cinc-0.1.4.tar.gz/robotframework-cinc-0.1.4/src/CINCLibrary/__init__.py | 0.71889 | 0.217068 | __init__.py | pypi |
from robot.api.deco import library, keyword
from CircleciLibrary.model import Project, Workflow, Pipeline, WorkflowList
from CircleciLibrary.log import trace
from pycircleci.api import Api, API_BASE_URL
class WorkflowRunningError(Exception):
"""
this exception will be raised if the workflow is still running
"""
class WorkflowStatusError(Exception):
"""
this exception will be raised if the workflow does not have the desired status
"""
class ProjectNotFoundError(Exception):
"""
this exception will be raised if a project was not found by the given criteria
"""
@library
class CircleciLibraryKeywords:
"""
circleci keywords
"""
def __init__(self, api_token, base_url=API_BASE_URL):
"""
:param api_token: circleci api token
:param base_url: circleci base url (default: pycircleci.api.API_BASE_URL)
"""
self.api = Api(api_token, url=base_url)
@keyword
def define_project(self, vcs_type: str, username: str, reponame: str) -> Project:
"""
creates a project object
:param vcs_type: vcs type
:param username: project organisation
:param reponame: name of the repository
:return: Project object
"""
return Project(
vcs_type=vcs_type,
username=username,
reponame=reponame
)
@keyword
def trigger_pipeline(
self,
project: Project,
branch: str = None,
tag: str = None,
parameters: dict = {}
) -> Pipeline:
"""
Triggers a circleci pipeline
:param project: the circleci project
:param branch: the branch to build
Defaults to None. Cannot be used with the ``tag`` parameter.
:param tag: the tag to build
Defaults to None. Cannot be used with the ``branch`` parameter.
:param parameters: additional pipeline parameters (default: {})
:return: Pipeline object
"""
response = trace(
self.api.trigger_pipeline(
username=project.username,
project=project.reponame,
branch=branch,
tag=tag,
vcs_type=project.vcs_type,
params=parameters
)
)
return Pipeline.from_json(response)
@keyword
def get_pipeline(self, pipeline_id) -> Pipeline:
"""
Get the information for a given pipeline
:param pipeline_id: the id of a circleci pipeline
:return: Pipeline object
"""
return Pipeline.from_json(trace(self.api.get_pipeline(pipeline_id)))
@keyword
def get_workflows(self, pipeline: Pipeline) -> WorkflowList:
"""
Get the information for all workflow of a given pipeline
:param pipeline: circleci pipeline object
:return: list of workflows object
"""
response = trace(self.api.get_pipeline_workflow(pipeline.id))
if isinstance(response, list):
workflow_items = response
elif isinstance(response, dict):
workflow_items = response['items']
else:
raise RuntimeError(f"list or dict expected for the response: {response}")
workflows = [Workflow.from_json(w) for w in workflow_items]
return WorkflowList.from_list(workflows)
@keyword
def all_workflows_stopped(self, pipeline: Pipeline) -> bool:
"""
Return True if all workflows of the given pipeline completed
:param pipeline: circleci pipeline object
:return: True if all workflows of this pipeline are complete
"""
workflows = self.get_workflows(pipeline)
return workflows.completed()
@keyword
def all_workflows_should_be_stopped(self, pipeline: Pipeline):
"""
Check if all workflows of the given pipeline stopped
:param pipeline: circleci pipeline object
:raise: WorkflowRunningError if not all workflows of this pipeline are stopped
"""
if not self.all_workflows_stopped(pipeline):
raise WorkflowRunningError(f"Workflows still running for pipeline: {pipeline}")
@keyword
def all_workflows_have_status(self, pipeline: Pipeline, status: Workflow.Status):
"""
:return: True if all workflows have the desired status
"""
for w in self.get_workflows(pipeline):
if w.status != status:
return False
return True
@keyword
def all_workflows_should_have_the_status(self, pipeline: Pipeline, status: Workflow.Status):
"""
Check if all workflows have the desired status
:param pipeline: circleci pipeline object
:param status: desired workflow status
:raise: WorkflowStatusError if not all workflows have the desired status
"""
if not self.all_workflows_have_status(pipeline, status):
raise WorkflowStatusError(f"Workflows do not have the status {status.name} for pipeline: {pipeline}")
def _get_projects(self):
for p in trace(self.api.get_projects()):
yield Project.from_json(p)
@keyword
def get_projects(self):
"""
:return: all projects of the current user
"""
return list(self._get_projects())
@keyword
def get_project(self, name):
"""
returns the desired project of the current user
:param name: name of the desired project
:return: the desired project of the current user
:raise: ProjectNotFoundError if no project was found for the given name
"""
for p in self._get_projects():
if p.reponame == name:
return p
raise ProjectNotFoundError(f"project {name} was not found in the projects list of the current user") | /robotframework-circlecilibrary-0.1.3.tar.gz/robotframework-circlecilibrary-0.1.3/CircleciLibrary/keywords.py | 0.890032 | 0.302855 | keywords.py | pypi |
from dataclasses import dataclass
from datetime import datetime
from enum import Enum, unique
@dataclass
class Project:
"""circleci project"""
@staticmethod
def from_json(d: dict):
return Project(
vcs_type=d['vcs_type'],
username=d['username'],
reponame=d['reponame']
)
username: str
reponame: str
vcs_type: str
def __init__(self, vcs_type: str, username: str, reponame: str):
self.vcs_type = vcs_type
self.username = username
self.reponame = reponame
@dataclass
class Pipeline:
"""circleci pipeline object"""
@staticmethod
def parse_datetime(dt_str: str) -> datetime:
if dt_str is None:
return None
return datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%S.%f%z')
@dataclass
class Error:
"""error information of a pipeline"""
@staticmethod
def from_json(d: dict):
return Pipeline.Error(d['type'], d['message'])
type: str
message: str
def __init__(self, error_type: str, message: str):
self.type = error_type
self.message = message
@dataclass
class Vcs:
"""vcs information of a pipeline"""
@staticmethod
def from_json(d: dict):
return Pipeline.Vcs(
provider_name=d['provider_name'],
target_repository_url=d['target_repository_url'],
branch=d.get('branch'),
tag=d.get('tag')
)
provider_name: str
target_repository_url: str
branch: str
tag: str
def __int__(
self,
provider_name: str,
target_repository_url: str,
branch: str,
tag: str
):
self.provider_name = provider_name
self.target_repository_url = target_repository_url
self.branch = branch
self.tag = tag
@staticmethod
def from_json(d: dict):
created = Pipeline.parse_datetime(d['created_at'])
updated_at = Pipeline.parse_datetime(d.get('updated_at'))
errors = [Pipeline.Error.from_json(j) for j in d.get('errors', [])]
vcs = Pipeline.Vcs.from_json(d['vcs']) if 'vcs' in d.keys() else None
return Pipeline(
pipeline_id=d['id'],
number=d['number'],
state=d['state'],
created_at=created,
updated_at=updated_at,
errors=errors,
vcs=vcs
)
id: str
number: int
state: str
created_at: datetime
updated_at: datetime
errors: list[Error]
vcs: Vcs
def __init__(
self,
pipeline_id: str,
number: int,
state: str,
created_at: datetime,
updated_at: datetime,
errors: list[Error],
vcs: Vcs
):
self.number = number
self.state = state
self.id = pipeline_id
self.created_at = created_at
self.updated_at = updated_at
self.errors = errors
self.vcs = vcs
@dataclass
class Workflow:
"""circleci workflow object"""
@unique
class Status(Enum):
"""status which a circleci workflow could have"""
SUCCESS = 'success'
RUNNING = 'running'
ON_HOLD = 'on_hold'
NOT_RUN = 'not_run'
FAILED = 'failed'
ERROR = 'error'
FAILING = 'failing'
CANCELLED = 'canceled'
UNAUTHORIZED = 'unauthorized'
id: str
name: str
pipeline_id: str
pipeline_number: str
project_slug: str
status: Status
started_by: str
created_at: datetime
stopped_at: datetime
@staticmethod
def from_json(d: dict):
def parse_datetime(dt_str: str):
if dt_str is None:
return None
return datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%S%z')
created = parse_datetime(d['created_at'])
stopped = parse_datetime(d['stopped_at'])
return Workflow(
workflow_id=d['id'],
name=d['name'],
pipeline_id=d['pipeline_id'],
pipeline_number=d['pipeline_number'],
project_slug=d['project_slug'],
status=Workflow.Status(d['status']),
started_by=d['started_by'],
created_at=created,
stopped_at=stopped
)
def __init__(
self,
workflow_id: str,
name: str,
pipeline_id: str,
pipeline_number: str,
project_slug: str,
status: str,
started_by: str,
created_at: datetime,
stopped_at: datetime = None
):
self.id = workflow_id
self.name = name
self.pipeline_id = pipeline_id
self.pipeline_number = pipeline_number
self.project_slug = project_slug
self.status = status
self.started_by = started_by
self.created_at = created_at
self.stopped_at = stopped_at
def in_progress(self) -> bool:
return self.stopped_at is None
class WorkflowList(list[Workflow]):
"""a list of circleci workflow objects"""
@staticmethod
def from_list(l: list):
wl = WorkflowList()
wl.extend(l)
return wl
def completed(self) -> bool:
"""
:return: True if all workflows of this pipeline are complete
"""
if len(self) == 0:
return False
in_progress = [w for w in self if w.in_progress()]
return len(in_progress) == 0
def overall_status(self, status: Workflow.Status):
"""
:param status: desired status
:return: True if all workflows have the given status
"""
success_workflows = [w for w in self if w.status == status]
return len(self) == len(success_workflows) | /robotframework-circlecilibrary-0.1.3.tar.gz/robotframework-circlecilibrary-0.1.3/CircleciLibrary/model.py | 0.839422 | 0.169166 | model.py | pypi |
import ast
from collections import defaultdict
from robot.api import Token, get_model
from robot.utils.misc import printable_name
from robot.parsing.model import Statement, ForLoop, KeywordSection, TestCaseSection
from robot.parsing.model.statements import EmptyLine, Comment
from robot.parsing.model.visitor import ModelVisitor
class SplitToMultiline(ast.NodeVisitor):
def __init__(self, line, end_line, separator):
self.tree = {
'runkeywordif',
'setvariableif',
'settodictionary',
'removefromdictionary'
}
self.ignore_chars = {
'SEPARATOR',
'EOL',
'CONTINUATION'
}
self.line = line
self.end_line = end_line or line
self.separator = separator
def insert_seperator(self, iterator):
for elem in iterator:
yield elem
yield Token(Token.SEPARATOR, self.separator * ' ')
def split_to_new_line(self, iterator, indent, not_split_first=False):
iter_gen = (elem for elem in iterator)
if not_split_first:
elem = next(iter_gen)
yield Token(Token.SEPARATOR, self.separator * ' ')
yield elem
for elem in iter_gen:
yield Token(Token.EOL, '\n')
yield indent
yield Token(Token.CONTINUATION, '...')
yield Token(Token.SEPARATOR, self.separator * ' ')
yield elem
yield Token(Token.EOL, '\n')
def visit_KeywordCall(self, node): # noqa
if node.lineno < self.line or node.lineno > self.end_line:
return
indent = node.tokens[0]
args = defaultdict(list)
keyword_token = None
for child in node.tokens:
if child.type in self.ignore_chars:
continue
if child.type == 'KEYWORD':
keyword_token = child
continue
args[child.type].append(child)
assign = list(self.insert_seperator(args['ASSIGN']))
not_split_first = self.is_nested_tree(keyword_token)
arguments = list(self.split_to_new_line(args['ARGUMENT'], indent, not_split_first))
tokens = [indent] + assign
tokens.append(keyword_token)
tokens.extend(arguments)
node.tokens = tokens
@staticmethod
def normalize_name(name):
return name.replace('_', '').replace(' ', '').lower()
def is_nested_tree(self, token):
if not token.value:
return False
return self.normalize_name(token.value) in self.tree
class KeywordRenamer(ast.NodeVisitor):
def __init__(self, ignore):
self.ignore = ignore
def rename_token(self, token):
if token is None or (self.ignore and self.ignore in token.value):
return
token.value = printable_name(token.value, code_style=True)
def visit_KeywordName(self, node): # noqa
token = node.get_token(Token.KEYWORD_NAME)
self.rename_token(token)
def visit_KeywordCall(self, node): # noqa
token = node.get_token(Token.KEYWORD)
self.rename_token(token)
def visit_File(self, node): # noqa
self.generic_visit(node)
def visit_Keyword(self, node): # noqa
self.generic_visit(node)
def visit_TestCase(self, node): # noqa
self.generic_visit(node)
def visit_SuiteSetup(self, node): # noqa
self.generic_visit(node)
def visit_TestSetup(self, node): # noqa
self.generic_visit(node)
def visit_Setup(self, node): # noqa
self.generic_visit(node)
def visit_SuiteTeardown(self, node): # noqa
self.generic_visit(node)
def visit_TestTeardown(self, node): # noqa
self.generic_visit(node)
def visit_Teardown(self, node): # noqa
self.generic_visit(node)
class CollectColumnWidth(ModelVisitor):
def __init__(self, start_line, end_line):
self.start_line = start_line
self.end_line = end_line
self.columns = []
def visit_Statement(self, node): # noqa
if node.end_lineno < self.start_line or node.lineno > self.end_line:
return
if node.type in ('DOCUMENTATION', 'FOR'):
return
tokens = [token for token in node.tokens
if token.type not in ('SEPARATOR', 'CONTINUATION', 'EOL', 'EOS')]
for index, token in enumerate(tokens):
tok_len = len(token.value)
try:
self.columns[index] = max(self.columns[index], tok_len)
except IndexError:
self.columns.append(tok_len)
@staticmethod
def round_to_four(number):
div = number % 4
if div:
return number + 4 - div
return number
def align_to_tab_size(self):
self.columns = [self.round_to_four(column) for column in self.columns]
class AlignSelected(ast.NodeVisitor):
def __init__(self, start_line, end_line, indent, align_globally):
self.start_line = start_line
self.end_line = end_line
self.indent = indent
self.align_globally = align_globally
self.global_look_up = []
def visit_File(self, node): # noqa
if self.align_globally:
model = get_model(node.source)
column_widths = CollectColumnWidth(self.start_line, self.end_line)
column_widths.visit(model)
column_widths.align_to_tab_size()
self.global_look_up = column_widths.columns
self.generic_visit(node)
def visit_TestCase(self, node): # noqa
self.align(node, self.indent, self.align_globally)
def visit_Keyword(self, node): # noqa
self.align(node, self.indent, self.align_globally)
@staticmethod
def get_longest(matrix, index):
longest = max(len(r[index].value) for r in matrix if len(r) > index)
return CollectColumnWidth.round_to_four(longest)
def align(self, node, indent, use_global_lookup):
if node.end_lineno < self.start_line or node.lineno > self.end_line:
return
statements = []
for child in node.body:
if isinstance(child, ForLoop):
self.align(child, indent * 2, False)
statements.append(child)
elif child.type == 'DOCUMENTATION' or self.start_line > child.lineno or self.end_line < child.lineno:
statements.append(child)
else:
statements.append([token for token in child.tokens
if token.type not in ('SEPARATOR', 'CONTINUATION', 'EOL', 'EOS')])
if not use_global_lookup:
misaligned_stat = [st for st in statements if isinstance(st, list)]
if not misaligned_stat:
return
col_len = max(len(c) for c in misaligned_stat)
look_up = [self.get_longest(misaligned_stat, i) for i in range(col_len)]
else:
look_up = self.global_look_up
node.body = list(self.align_rows(statements, indent, look_up))
def align_rows(self, statements, indent, look_up):
for row in statements:
if isinstance(row, list):
yield self.align_row(row, indent, look_up)
else:
yield row
@staticmethod
def align_row(row, indent, look_up):
aligned_row = [Token(Token.SEPARATOR, indent * ' ')]
row_len = len(row)
for i, c in enumerate(row):
aligned_row.append(c)
if i < row_len - 1:
separator = Token(Token.SEPARATOR, (look_up[i] - len(c.value) + 4) * ' ')
aligned_row.append(separator)
aligned_row.append(Token(Token.EOL, '\n'))
return Statement.from_tokens(aligned_row)
class TabsToSpaces(ModelVisitor):
def visit_Statement(self, node): # noqa
for token in node.get_tokens('SEPARATOR'):
token.value = token.value.expandtabs(4)
eol_token = node.get_token('EOL')
if eol_token is not None:
eol_token.value = '\n'
class WhitespaceCleanup(ast.NodeVisitor):
def __init__(self):
self.header_end_lines = 2
self.test_case_sep = 2
self.empty_line = Statement.from_tokens([
Token(Token.EOL, '\n')
])
@staticmethod
def is_keyword_or_tests_section(section):
return isinstance(section, (KeywordSection, TestCaseSection))
@staticmethod
def trim_trailing_empty_lines(node):
while hasattr(node, 'body') and node.body and isinstance(node.body[-1], EmptyLine):
node.body.pop()
@staticmethod
def trim_leading_empty_lines(node):
while node.body and isinstance(node.body[0], EmptyLine):
node.body.pop(0)
def visit_File(self, node): # noqa
self.generic_visit(node)
if node.sections and node.sections[-1].body:
self.trim_trailing_empty_lines(node.sections[-1])
self.trim_trailing_empty_lines(node.sections[-1].body[-1])
if not self.is_keyword_or_tests_section(node.sections[-1]):
node.sections[-1].body[-1].tokens = node.sections[-1].body[-1].tokens[:-1] + (Token(Token.EOL, '\n'),)
node.sections = [section for section in node.sections if not self.only_empty_lines(section)]
@staticmethod
def only_empty_lines(node):
return all(isinstance(child, EmptyLine) for child in node.body)
def parse_settings_or_variables(self, node):
self.trim_trailing_empty_lines(node)
self.trim_leading_empty_lines(node)
statements = []
is_prev_empty_line = False
for child in node.body:
if isinstance(child, EmptyLine) and is_prev_empty_line:
continue
is_prev_empty_line = isinstance(child, EmptyLine)
statements.append(child)
statements.extend([self.empty_line] * self.header_end_lines)
node.body = statements
def visit_SettingSection(self, node): # noqa
self.parse_settings_or_variables(node)
def visit_VariableSection(self, node): # noqa
self.parse_settings_or_variables(node)
def visit_CommentSection(self, node): # noqa
self.parse_settings_or_variables(node)
def parse_tests_or_keywords(self, node):
while node.body and isinstance(node.body[0], EmptyLine):
node.body.pop(0)
child = None
for child in node.body:
if isinstance(child, Comment):
continue
self.trim_leading_empty_lines(child)
self.trim_trailing_empty_lines(child)
child.body.append(self.empty_line)
if child is not None:
child.body.append(self.empty_line)
def visit_TestCaseSection(self, node): # noqa
self.parse_tests_or_keywords(node)
def visit_KeywordSection(self, node): # noqa
self.parse_tests_or_keywords(node) | /robotframework_clean-1.2.1-py3-none-any.whl/robotclean/code_formatters.py | 0.484136 | 0.182407 | code_formatters.py | pypi |
from datetime import datetime
from pytz import timezone
def getcurrentDateTimeZone(TimeZone, Format):
"""
helper function to get the Current Date
"""
Current_Date = datetime.now(timezone(TimeZone)).strftime(Format)
return Current_Date
def currentDateTime():
"""
helper function to get the Current DateTime
"""
Current_Time = datetime.now(timezone('America/Chicago')).strftime("%Y-%m-%d %H:%M:%S")
return Current_Time
def currenttimefordiffzones(timeZone):
"""
helper function to get the currenttimefordiffzones
"""
currenttime = datetime.now(timezone(timeZone)).strftime("%H:%M:%S")
if timeZone == "America/Chicago":
currenttimewithzone = currenttime + ' ' + "CDT"
elif timeZone == "America/New_York":
currenttimewithzone = currenttime + ' ' + "EDT"
if timeZone == "America/Anchorage":
currenttimewithzone = currenttime + ' ' + "AKDT"
elif timeZone == "Pacific/Honolulu":
currenttimewithzone = currenttime + ' ' + "HST"
if timeZone == "America/Phoenix":
currenttimewithzone = currenttime + ' ' + "MST"
elif timeZone == "America/Los_Angeles":
currenttimewithzone = currenttime + ' ' + "PDT"
return currenttimewithzone
def current_date_time1():
"""
helper function to get the Current Date1
"""
Current_Time = datetime.now(timezone('America/Chicago')).strftime("%Y-%m-%d")
return Current_Time
def epochtimeToTZ(epoch_time, TimeZone, datetimeformat):
tz = timezone(TimeZone) # 'America/Chicago'
dt = datetime.fromtimestamp(epoch_time, tz)
# print it
print(dt.strftime(datetimeformat)) # '%m/%d/%Y %H:%M'
return dt.strftime(datetimeformat)
class DateTime:
""" Connection class """
def __init__(self):
self.log = None
def currentDateTimeNew(self):
self.log = None
Current_TimeNew = datetime.now(timezone('America/Chicago')).strftime("%Y-%m-%d")
return Current_TimeNew
@staticmethod
def Difference():
""" Fetch CST timings """
shift = "Shift1".upper()
if shift == "Shift1".upper():
start = "00:00:00"
end = "11:59:00"
elif shift == "Shift2".upper():
start = "12:00:00"
end = "23:59:00"
elif shift == "Shift3".upper():
start = "12:00:00"
end = "14:59:00"
elif shift == "Production Day".upper():
start = "00:00:00"
end = "24:00:00"
Now = datetime.now(timezone('America/Chicago')).strftime("%H:%M:%S")
Current_Time = datetime.strptime(Now, "%H:%M:%S") # Converting string to date
print("Current Time(CST):", Current_Time)
start_time = datetime.strptime(start, "%H:%M:%S")
print("Shift Start Time:", start_time)
total_time = str(Current_Time - start_time)
print("TotalTime:", total_time)
hours, minutes, seconds = map(int, total_time.split(':'))
CurrentTimeInSec1 = (hours * 3600 + minutes * 60 + seconds)
print("Max Run time:", CurrentTimeInSec1)
if __name__ == "__main__":
TEST = DateTime() | /robotframework_commonKeywrds-0.0.1-py3-none-any.whl/CommonKeywords/DateTime1.py | 0.634656 | 0.318194 | DateTime1.py | pypi |
try:
import curses
curses_available = True
from ConsoleDialogs.cursesdialogs import CursesMessageDialog, CursesPassFailDialog, CursesInputDialog
except ImportError:
logger.warn("Failed to load curses module - falling back to raw input mode")
curses_available = False
from ConsoleDialogs.rawdialogs import RawMessageDialog, RawPassFailDialog, RawInputDialog, RawSingleSelectionDialog
class ConsoleKeywords(object):
def pause_execution(self, message="Test execution paused. Press OK to continue."):
"""Pauses test execution until user clicks ``Ok`` button.
``message`` is the message shown in the dialog.
"""
if curses_available:
CursesMessageDialog(message).show()
else:
RawMessageDialog(message).show()
def execute_manual_step(self, message, default_error=""):
"""Pauses test execution until user sets the keyword status.
User can press either ``PASS`` or ``FAIL`` button. In the latter case execution
fails and an additional dialog is opened for defining the error message.
``message`` is the instruction shown in the initial dialog and
``default_error`` is the default value shown in the possible error message
dialog.
"""
if curses_available:
pf_dialog = CursesPassFailDialog(message)
pf_dialog.show()
result = pf_dialog.get_result()
else:
result = RawPassFailDialog(message).show()
if not result:
if curses_available:
CursesMessageDialog(default_error).show()
else:
RawMessageDialog(default_error).show()
raise AssertionError("User selected FAIL when executing manual step")
def get_value_from_user(self, message, default_value="", hidden=False):
"""Pauses test execution and asks user to input a value.
Value typed by the user, or the possible default value, is returned.
Returning an empty value is fine, but pressing ``Cancel`` fails the keyword.
``message`` is the instruction shown in the dialog and ``default_value`` is
the possible default value shown in the input field.
If ``hidden`` is given a true value, the value typed by the user is hidden.
``hidden`` is considered true if it is a non-empty string not equal to
``false``, ``none`` or ``no``, case-insensitively. If it is not a string,
its truth value is got directly using same
[http://docs.python.org/library/stdtypes.html#truth|rules as in Python].
Example:
| ${username} = | Get Value From User | Input user name | default |
| ${password} = | Get Value From User | Input password | hidden=yes |
Considering strings ``false`` and ``no`` to be false is new in RF 2.9
and considering string ``none`` false is new in RF 3.0.3.
"""
if curses_available:
input_dialog = CursesInputDialog(message, default_value, hidden)
input_dialog.show()
return input_dialog.get_result()
else:
input_dialog = RawInputDialog(message, default_value, hidden)
return input_dialog.show()
def get_selection_from_user(self, message, *values):
"""Pauses test execution and asks user to select a value.
The selected value is returned. Pressing ``Cancel`` fails the keyword.
``message`` is the instruction shown in the dialog and ``values`` are
the options given to the user.
Example:
| ${user} = | Get Selection From User | Select user | user1 | user2 | admin |
"""
# Currently only supported by raw dialog mode
dialog = RawSingleSelectionDialog(message, *values)
return dialog.show()
def get_selections_from_user(self, message, *values):
"""Pauses test execution and asks user to select multiple values.
The selected values are returned as a list. Selecting no values is OK
and in that case the returned list is empty. Pressing ``Cancel`` fails
the keyword.
``message`` is the instruction shown in the dialog and ``values`` are
the options given to the user.
Example:
| ${users} = | Get Selections From User | Select users | user1 | user2 | admin |
New in Robot Framework 3.1.
"""
# Currently only supported by raw dialog mode
dialog = RawMultiSelectionDialog(message, *values)
return dialog.show() | /robotframework_consoledialogs-1.1.3-py3-none-any.whl/ConsoleDialogs/keywords.py | 0.772445 | 0.268351 | keywords.py | pypi |
import curses
import curses.ascii
from curses import A_UNDERLINE
class WindowFullException(Exception):
pass
def calc_wordwrap_lines(s, width):
# Split string into list of words
word_list = s.split()
# Line-based loop
y = 0
w = 0
while True:
width_sum = 0
while w < len(word_list):
word = word_list[w]
if (width_sum + len(word)) >= width:
break
width_sum += len(word)
if width_sum + 1 < width:
width_sum += 1
w += 1
if w >= len(word_list):
break
y = y + 1
# Return the actual number of lines needed
return y
def addstr_charwrap(window, s, cursorpos=None, mode=0, halign=0, fail_on_window_full=False):
(height, width) = window.getmaxyx()
# Char-based loop
y = 0
c = 0
while y < height:
x = 0
while x < width and c < len(s):
flags = A_UNDERLINE if c == cursorpos else 0
window.addch(y, x, s[c], flags)
c += 1
x += 1
y += 1
if c >= len(s):
break
def addstr_wordwrap(window, s, mode=0, halign=0, fail_on_window_full=False):
""" (cursesWindow, str, int, int, int, bool) -> None
Add a string to a curses window. If mode is given
(e.g. curses.A_BOLD), then format text accordingly. We do very
rudimentary wrapping on word boundaries.
"""
(height, width) = window.getmaxyx()
# Split string into list of words
word_list = s.split()
# Line-based loop
y = 0
x = 0
w = 0
while w < len(word_list):
if x + (len(word_list[w]) + 1) >= width:
y += 1
x = 0
if y >= height:
# No more lines to add
break
window.addstr(y, x, word_list[w], mode)
x += len(word_list[w])
window.addstr(y, x, ' ', mode)
x += 1
w += 1
if fail_on_window_full and y >= height and w < len(word_list):
# Haven't managed to fit all of the text into the window
raise WindowFullException()
# Return the actual number of lines we rendered
return y + 1
def insert_str(string, ch, index):
return string[:index] + chr(ch) + string[index:]
class CustomTextBox:
"""Editing widget using the interior of a window object.
"""
def __init__(self, default_string="", hidden=False):
self.string = default_string
self.cursorpos = len(self.string)
self.enable = False
self.hidden = hidden
def handle_key(self, k):
if not self.enable:
return
ch = int(k)
if curses.ascii.isprint(ch):
if self.cursorpos <= len(self.string):
self.string = insert_str(self.string, ch, self.cursorpos)
self.cursorpos += 1
elif ch in (curses.KEY_LEFT, curses.ascii.BS, curses.KEY_BACKSPACE):
if self.cursorpos > 0:
self.cursorpos = self.cursorpos - 1
if ch in (curses.ascii.BS, curses.KEY_BACKSPACE):
self.string = self.string[:self.cursorpos] + self.string[(self.cursorpos + 1):]
elif ch == curses.KEY_RIGHT:
if self.cursorpos < len(self.string):
self.cursorpos += 1
elif ch == curses.KEY_DC:
self.string = self.string[:self.cursorpos] + self.string[(self.cursorpos + 1):]
elif ch == curses.KEY_HOME:
self.cursorpos = 0
elif ch == curses.KEY_END:
self.cursorpos = len(self.string)
def set_enable(self, enable):
self.enable = enable
self.cursorpos = len(self.string)
def get_string(self):
return self.string
def draw(self, win):
disp_str = self.string
if self.hidden:
disp_str = '*' * len(self.string)
cp = self.cursorpos if self.enable else None
addstr_charwrap(win, disp_str, cp) | /robotframework_consoledialogs-1.1.3-py3-none-any.whl/ConsoleDialogs/cursesutils.py | 0.550849 | 0.354042 | cursesutils.py | pypi |
from CoreRPAHive.ExcelTestDataRow.MandatoryTestDataColumn import MANDATORY_TEST_DATA_COLUMN
from CoreRPAHive.ExcelTestDataRow.TestStatus import TEST_STATUSES
from CoreRPAHive.ExcelTestDataRow.TestStatus import TEST_STATUS_PRIORITIES
class ExcelTestDataRow:
def __init__(self, excel_title, excel_row_index, excel_row, column_indexes, status, log_message, screenshot, tags):
self.excel_title = excel_title
self.excel_row_index = excel_row_index
self.excel_row = excel_row
self.column_indexes = column_indexes
self.status = status
self.log_message = log_message
self.screenshot = screenshot
self.tags = tags
def get_status(self):
return self.status.value
def get_testcase_tags(self):
if self.tags.value is None:
return []
return list(map(lambda tag: tag.strip(), self.tags.value.split(',')))
def get_row_no(self):
return self.status.row
def get_sheet_name(self):
return self.status.parent.title
def get_log_message(self):
return self.log_message.value
def set_log_message(self, log_message):
self.log_message.value = log_message
def get_screenshot(self):
return self.screenshot.value
def get_test_data_property(self, property_name):
try:
return self.excel_row[self.column_indexes[property_name.lower().strip()] - 1].value
except:
raise Exception('Can\'t find property name '+property_name+' under test data row index '+str(self.get_row_no()))
def get_excel_results(self):
update_data = [cell.value for cell in self.excel_row]
update_data[self.column_indexes[MANDATORY_TEST_DATA_COLUMN['status']] - 1] = self.status
update_data[self.column_indexes[MANDATORY_TEST_DATA_COLUMN['log_message']] - 1] = self.log_message
update_data[self.column_indexes[MANDATORY_TEST_DATA_COLUMN['screenshot']] - 1] = self.screenshot
update_datas = {self.excel_title + '_' + str(self.excel_row_index): update_data}
return update_datas
def is_pass(self):
if self.get_status() == TEST_STATUSES['pass']:
return True
return False
def is_fail(self):
if self.get_status() == TEST_STATUSES['fail']:
return True
return False
def is_warning(self):
if self.get_status() == TEST_STATUSES['warning']:
return True
return False
def is_not_run(self):
if self.is_pass() is not True and self.is_fail() is not True and self.is_warning() is not True:
return True
return False
def update_result(self, status=None, log_message=None, screenshot=None):
"""
Save the result back to excel file
:return None:
"""
# Only update status if the update one more priority
if status is not None and status in TEST_STATUSES.values():
if TEST_STATUS_PRIORITIES[self.status.value] < TEST_STATUS_PRIORITIES[status]:
self.status.value = status
# Log should be append not replace
if log_message is not None:
if self.log_message.value is None or self.log_message.value == '':
self.log_message.value = log_message
else:
self.log_message.value += '\n'+log_message
# Log error screenshot
if screenshot is not None:
self.screenshot.value = screenshot
def clear_test_result(self):
self.status.value = ''
self.log_message.value = ''
self.screenshot.value = '' | /robotframework-corerpahive-1.2.0.tar.gz/robotframework-corerpahive-1.2.0/CoreRPAHive/ExcelTestDataRow/ExcelTestDataRow.py | 0.534977 | 0.380414 | ExcelTestDataRow.py | pypi |
from abc import ABCMeta, abstractmethod
from CoreRPAHive.ExcelTestDataRow.MandatoryTestDataColumn import MANDATORY_TEST_DATA_COLUMN
from openpyxl.utils import column_index_from_string
from openpyxl.utils.cell import coordinate_from_string
class ABCParserStrategy:
__metaclass__ = ABCMeta
def __init__(self):
self.MANDATORY_TEST_DATA_COLUMN = MANDATORY_TEST_DATA_COLUMN
self.DEFAULT_COLUMN_INDEXS = self.MANDATORY_TEST_DATA_COLUMN.values()
self.start_row = 2
self.max_column = 50
self.maximum_column_index_row = 5
def is_ws_column_valid(self, ws, validate_result):
ws_column_indexes = self.parsing_column_indexs(ws)
diff_column_list = list(set(self.DEFAULT_COLUMN_INDEXS) - set(ws_column_indexes))
if len(diff_column_list) > 0:
validate_result['is_pass'] = False
validate_result['error_message'] += "[" + ws.title + "] Excel column " + ", ".join(
diff_column_list) + " are missing.\r\n"
print("[" + ws.title + "] Excel column " + ", ".join(diff_column_list) + " are missing.")
return validate_result
@abstractmethod
def is_test_data_valid(self, ws_column_indexes, ws_title, row_index, row): pass
@abstractmethod
def map_data_row_into_test_data_obj(self, ws_column_indexes, ws_title, row_index, row): pass
def get_all_worksheet(self, wb):
return list(wb)
def parsing_column_indexs(self, ws):
ws_column_indexs = {}
# Parse mandatory property
for index, row in enumerate(ws.rows):
if index > self.maximum_column_index_row:
break
for cell in row:
if (cell.value is not None) and (cell.value in self.DEFAULT_COLUMN_INDEXS):
ws_column_indexs[cell.value] = column_index_from_string(coordinate_from_string(cell.coordinate)[0])
print('Mandatory : '+str(cell.value) + ' : ' + str(cell.coordinate) + ' : ' + str(column_index_from_string(coordinate_from_string(cell.coordinate)[0])))
self.start_row = index + 1
if len(ws_column_indexs) > 0:
break
# Parse optional property
for index, row in enumerate(ws.rows):
if index > self.maximum_column_index_row:
break
if index != self.start_row - 1:
continue
for cell in row:
if (cell.value is not None) and (cell.value not in self.DEFAULT_COLUMN_INDEXS):
ws_column_indexs[cell.value.lower().strip()] = column_index_from_string(coordinate_from_string(cell.coordinate)[0])
print('Optional : '+str(cell.value.lower().strip()) + ' : ' + str(cell.coordinate) + ' : ' + str(column_index_from_string(coordinate_from_string(cell.coordinate)[0])))
break
print('Done parsing column indexes')
return ws_column_indexs
def parse_test_data_properties(self, ws, ws_column_indexs):
test_datas = []
for index, row in enumerate(ws.rows):
if index < self.start_row:
continue
self.is_test_data_valid(ws_column_indexs, ws.title, index, row)
test_data = self.map_data_row_into_test_data_obj(ws_column_indexs, ws.title, index, row)
if test_data is not None:
test_datas.append(test_data)
else:
break
print('Total test datas: ' + str(len(test_datas)))
return test_datas | /robotframework-corerpahive-1.2.0.tar.gz/robotframework-corerpahive-1.2.0/CoreRPAHive/ExcelParser/ABCParserStrategy.py | 0.718397 | 0.375563 | ABCParserStrategy.py | pypi |
from CryptoLibrary.utils import CryptoUtility
from robot.libraries.BuiltIn import BuiltIn
from SeleniumLibrary.base import LibraryComponent, keyword
from robot.utils.robottypes import is_truthy
import re
class Plugin(LibraryComponent):
def __init__(self, ctx):
self.crypto = CryptoUtility()
LibraryComponent.__init__(self, ctx)
@keyword
def input_password(self, locator, password, clear=True):
"""Types the given password into the text field identified by ``locator``.
The `password` argument may be encrypted with CryptoLibrary.
Then this Keyword decrypts it automatically.
Be aware that the crypt: prefix is needed for automatic decryption.
See the `Locating elements` section for details about the locator
syntax. See `Input Text` for ``clear`` argument details.
Difference compared to `Input Text` is that this keyword does not
log the given password on the INFO level. Notice that if you use
the keyword like
| Input Password | password_field | password |
the password is shown as a normal keyword argument. A way to avoid
that is using variables like
| Input Password | password_field | ${PASSWORD} |
Please notice that Robot Framework logs all arguments using
the TRACE level and tests must not be executed using level below
DEBUG if the password should not be logged in any format.
The `clear` argument is new in SeleniumLibrary 4.0. Hiding password
logging from Selenium logs is new in SeleniumLibrary 4.2.
"""
self.info("Typing password into text field '%s'." % locator)
if isinstance(password, str) and re.fullmatch(self.crypto.CIPHER_PATTERN, password):
plaintext = self.crypto.decrypt_text(password)
else:
plaintext = password
self._input_text_into_text_field(locator, plaintext, clear)
def _input_text_into_text_field(self, locator, text, clear=True):
element = self.find_element(locator)
if is_truthy(clear):
element.clear()
previous_level = BuiltIn().set_log_level('NONE')
try:
element.send_keys(text)
finally:
BuiltIn().set_log_level(previous_level) | /robotframework-crypto-0.3.0.tar.gz/robotframework-crypto-0.3.0/src/CryptoLibrary/Plugin.py | 0.712932 | 0.225694 | Plugin.py | pypi |
from CryptoLibrary.utils import CryptoUtility
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
from CryptoLibrary.__main__ import Encrypter
import re
__version__ = '0.3.0'
def main():
Encrypter().main()
class CryptoLibrary(object):
"""
===================================================
robotframework-crypto
===================================================
CryptoLibrary is a library for secure password handling.
`project page <https://github.com/Snooz82/robotframework-crypto>`_
For more information about Robot Framework, see http://robotframework.org.
`Keyword Documentation <https://snooz82.github.io/robotframework-crypto/CryptoLibrary.html>`_
|
Installation
------------
If you already have Python >= 3.6 with pip installed, you can simply
run:
``pip install --upgrade robotframework-crypto``
or if you have Python 2 and 3 installed in parallel you may use
``pip3 install --upgrade robotframework-crypto``
If you have Python 2 ... i am very sorry! Please update!
|
How it works
------------
CryptoLibrary uses asymmetric crypto with elliptic curve cryptography to store confidential data securely.
With the command ``CryptoLibrary`` in console/terminal you can generate a key pair
(private and public key) for your test env.
You will get the public key after generating.
This public key can now be used to encrypt every data you do not want to be public.
Passwords, personal data, etc.
You can use the command``CryptoClient`` on you computer where you want to encrypt data.
Encrypted Data will look like this:
``crypt:tIdr5s65+ggfJZl46pJgljioCUePUdZLozgiwquznw+xSlmzT3dcvfrTL9wIdRwmNOJuONT7FBW5``
This encrypted data can now be decrypted with CryptoLibrary within Robot Framework.
CryptoLibrary need the private_key_store.json for this.
This is what is generated as key pair.
Private key can be imported in test env with ``python -m CryptoLibrary`` .
|
Suppressing encrypted Text from Logs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All Data that is decrypted by CryptoLibrary is replaced in the log by ``***``
This works always and can not be disabled.
No need to use special keywords for this.
|
Usage in Test
~~~~~~~~~~~~~
.. code :: robotframework
*** Settings ***
Resource imports.resource
Library CryptoLibrary %{private_key_password} variable_decryption=False
#private key which should be secret, should also be protected by a password
*** Variables ***
${secret}= KILL ALL HUMANS!!!
${enc_user}= crypt:nkpEPOVKfOko3t04XxOupA+F/ANTEuR9aQuPaPeMBGBQenwYf6UNESEl9MWRKGuj60ZWd10=
${enc_pwd}= crypt:TVpamLXCtrzRsl8UAgD0YuoY+lSJNV73+bTYhOP51zM1GQihgyCvSZ2CoGoKsUHLFjokyJLHxFzPEB4=
*** Test Cases ***
Valid Login
Open Browser ${BASE-URL}
Suppress Logging #disable Robot Framework logging
${var}= set Variable ${secret}
Log ${var}
Unsuppress Logging #enable Robot Framework logging
${user}= Get Decrypted Text ${enc_user} #decrypts cipher text and returns plain text
Input Text id:input_username ${user}
${password}= Get Decrypted Text ${enc_pwd} #decrypts cipher text and returns plain text
Input Password id:input_password ${password}
Click Button id:button_login
Page Should Contain Element //a[text()='Logout']
[Teardown] Close Browser
in this case the decryption password for the private key.
It can also be saved on test env persistently as a hash.
The parameter **variable_decryption** in the Library call, if set to true it will automatically decode ALL passwords defined in the variables section
and then ``"Get Decrypted Text"`` isn't needed.
|
Importing of CryptoLibrary
~~~~~~~~~~~~~~~~~~~~~~~~~~
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **password:** | Password for private key can be given as argument. This should be stored as secret! Use environment variables instead of hard coding it here. |
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **variable_decryption:** | If set to ``True`` all variables that are available on Test Suite or on Test Case start, |
| | that contain a encrypted text, will be decrypted automatically. |
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **key_path:** | A path that defines where the key pair is stored physically. |
| | Path needs to be an absolute path or relative to ``cryptoutility.py``. |
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
|
Menu walkthrough
----------------
|
CryptoLibrary Command Line Tool
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This Command Line tool has to be used to create a key pair.
It can also show the public key and encrypt or decrypt data.
``python -m CryptoLibrary``::
? What do you want to do? (Use arrow keys)
Encrypt
Decrypt
Open config ---> ? What do you want to do? (Use arrow keys)
Quit Configure key pair -----------------------------------------------------------------------------------------> ? What do you want to do? (Use arrow keys)
Configure public key ---> ? What do you want to do? (Use arrow keys) Generate key pair
Back Set public key from string ---> ? Input public_key as Base64: ThePublicKey Set key path
Get public key from string ---> Public Key: ThePublicKey Set key pair from string
Delete public key ---> ? Do you really want to delete public key? Delete key pair
Back Save private key password
Delete saved password
Back
? What do you want to do? (Use arrow keys)
Encrypt -------------------------------------------------------------------> ? Enter the password to encrypt YourPassword
Decrypt -----> ? Input encrypted cipher text: crypt:TheEncryptedPassword Encrypted password: (use inlc. "crypt:")
Open config ? Enter the password to decrypt **********
Quit Your password is: YourPassword crypt:TheEncryptedPassword=
To start using the CryptoLibrary, start ``python -m CryptoLibrary`` and choose ``Open config`` -> ``Configure key pair``-> ``Generate key pair``.
This generates the private and public keys in the ``private_key.json`` and ``public_key.key`` files.
The ``private_key.json`` is needed to decrypt the values on your test server and has to be copied manually or added through the CLI interface.
See ``Set key pair from...`` above.
Next you can encrypt the values needed on your test server, looking something like ``crypt:nkpEPOVKfOko3t04XxOupA+F/ANTEuR9aQuPaPeMBGBQenwYf6UNESEl9MWRKGuj60ZWd10=``
There are two options to decrypt your values in the robot file. When CryptoLibrary is loaded with ``variable_decryption=True``,
ALL variables defined in that section, will automatically get decrypted.
When the option is turned off (the default) the keyword ``Get Decrypted Text`` explicitly decrypts specific values.
|
CryptoClient Command Line Tool
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This CryptoClient command line tool is the tool for all test designers that want to encrypt data.
I can only import and show the public key and encrypt data.
``python -m CryptoClient``::
? What do you want to do? (Use arrow keys)
Encrypt ---------------------------------------------------------------------------------------> ? Enter the password to encrypt YourPassword
Open config -----> ? What do you want to do? (Use arrow keys) Encrypted password: (use inlc. "crypt:")
Quit Set public key from string ---> ? Input public_key as Base64: ThePublicKey
Get public key from string ---> Public Key: ThePublicKey crypt:TheEncryptedPassword
Delete public key ---> ? Do you really want to delete public key?
Back
|
SeleniumLibrary Plugin
----------------------
CryptoLibrary.Plugin is a SeleniumLibrary Plugin.
When taken into usage, the ``Input Password`` Keyword can now handle decrypted cipher texts as well.
Example:
.. code :: robotframework
*** Settings ***
Library SeleniumLibrary plugins=CryptoLibrary.Plugin
*** Variables ***
${Admins-Password}= crypt:fQ5Iqn/j2lN8rXwimyz0JXlYzD0gTsPRwb0YJ3YSvDchkvDpfwYDmhHxsZ2i7bIQDlsWKJVhBb+Dz4w=
*** Test Cases ***
Decrypt as Plugin
Open Browser http://www.keyword-driven.de
Input Text input_username admin
Input Password input_password ${Admins-Password}
|
It may happen that keywords changes.
i try not to do, but it can happen in major releases.
Feel free to make a pull Request to improve docs or write some tests for it.
"""
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
ROBOT_LISTENER_API_VERSION = 3
def __init__(self, password=None, variable_decryption=False, key_path=None):
"""
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **password:** | Password for private key can be given as argument. This should be stored as secret! Use environment variables instead of hard coding it here. |
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **variable_decryption:** | If set to ``True`` all variables that are available on Test Suite or on Test Case start, |
| | that contain a encrypted text, will be decrypted automatically. |
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
| **key_path:** | A path that defines where the key pair is stored physically. |
| | Path needs to be an absolute path or relative to ``cryptoutility.py``. |
+--------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------+
"""
self.ROBOT_LIBRARY_LISTENER = self
self.value_list = list()
self.crypto = CryptoUtility(key_path)
self.original_log_level = 'INFO'
self.disable_logging = False
if password:
self.crypto.password = password
self.variable_decryption = variable_decryption
self.builtin = BuiltIn()
def conceal_text_in_logs(self, text):
"""This keyword conceals the password, passed as input, in the logs.
Only ``***`` will be shown in the logs.
Because CrytoLibrary is a global Library, this text will be hidden from the point
where it is concealed until robot execution ends.
Earlier appearances will be visible in the logs!"""
logger.info(f'Conceal the text in the logs.')
self.value_list.append(text)
def get_decrypted_text(self, cipher_text):
"""Decrypts cipher text and returns the plain text.
Example:
.. code :: robotframework
${plain_text}= Get Decrypted Text crypt:sZ2i7bIQDlsWKJVhBb+Dz4w=
"""
logger.info(f'Decrypting text and return value.')
plaintext = self.crypto.decrypt_text(cipher_text)
self.value_list.append(plaintext)
return plaintext
def suppress_logging(self, disable: bool = True):
"""Disables the logging of robot framework until ``Unsuppress Logging`` has been called."""
if disable:
logger.info('disable logging...')
self.original_log_level = self.builtin.set_log_level('NONE')
else:
self.builtin.set_log_level(self.original_log_level)
logger.info('enable logging...')
logger.debug(f'Switching Loglevel from NONE to {self.original_log_level}.')
def unsuppress_logging(self):
"""Enables the logging of robot framework and set it back to the original log level."""
self.suppress_logging(False)
def _start_test(self, test, result):
self._decrypt_variable_in_scope(self.builtin.set_test_variable)
def _start_suite(self, suite, result):
self._decrypt_variable_in_scope(self.builtin.set_suite_variable)
def _decrypt_variable_in_scope(self, set_scope_variable):
if self.variable_decryption:
variables = self.builtin.get_variables()
for var in variables:
value = self.builtin.get_variable_value(var)
if isinstance(value, str) and re.fullmatch(self.crypto.CIPHER_PATTERN, value):
plain = self.get_decrypted_text(value)
set_scope_variable(var, plain)
def _log_message(self, message):
if self.value_list:
pattern = re.compile("|".join([re.escape(x) for x in self.value_list]))
message.message = pattern.sub('***', message.message) | /robotframework-crypto-0.3.0.tar.gz/robotframework-crypto-0.3.0/src/CryptoLibrary/__init__.py | 0.788949 | 0.329567 | __init__.py | pypi |
import os
from DatabaseLibrary.connection_manager import ConnectionManager
from DatabaseLibrary.query import Query
from DatabaseLibrary.assertion import Assertion
from DatabaseLibrary.version import VERSION
__version__ = VERSION
class DatabaseLibrary(ConnectionManager, Query, Assertion):
"""
The Database Library for [https://robotframework.org|Robot Framework] allows you to query a database and verify the results.
It requires an appropriate *Python module to be installed separately* - depending on your database, like e.g. `oracledb` or `pymysql`.
== Requirements ==
- Python
- Robot Framework
- Python database module you're going to use - e.g. `oracledb`
== Installation ==
| pip install robotframework-databaselibrary
Don't forget to install the required Python database module!
== Usage example ==
| *** Settings ***
| Library DatabaseLibrary
| Test Setup Connect To My Oracle DB
|
| *** Keywords ***
| Connect To My Oracle DB
| Connect To Database
| ... oracledb
| ... dbName=db
| ... dbUsername=my_user
| ... dbPassword=my_pass
| ... dbHost=127.0.0.1
| ... dbPort=1521
|
| *** Test Cases ***
| Person Table Contains Expected Records
| ${output}= Query select LAST_NAME from person
| Length Should Be ${output} 2
| Should Be Equal ${output}[0][0] See
| Should Be Equal ${output}[1][0] Schneider
|
| Person Table Contains No Joe
| ${sql}= Catenate SELECT id FROM person
| ... WHERE FIRST_NAME= 'Joe'
| Check If Not Exists In Database ${sql}
|
== Database modules compatibility ==
The library is basically compatible with any [https://peps.python.org/pep-0249|Python Database API Specification 2.0] module.
However, the actual implementation in existing Python modules is sometimes quite different, which requires custom handling in the library.
Therefore there are some modules, which are "natively" supported in the library - and others, which may work and may not.
See more on the [https://github.com/MarketSquare/Robotframework-Database-Library|project page on GitHub].
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL' | /robotframework_databaselibrary-1.3.1-py3-none-any.whl/DatabaseLibrary/__init__.py | 0.646795 | 0.399987 | __init__.py | pypi |
from robot.api import logger
class Assertion(object):
"""
Assertion handles all the assertions of Database Library.
"""
def check_if_exists_in_database(self, selectStatement, sansTran=False, msg=None):
"""
Check if any row would be returned by given the input `selectStatement`. If there are no results, then this will
throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit transaction
commit or rollback. The default error message can be overridden with the `msg` argument.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you have the following assertions in your robot
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' |
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' |
Then you will get the following:
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | # PASS |
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' | # FAIL |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' | True |
Using optional `msg` to override the default error message:
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' | msg=my error message |
"""
logger.info (f"Executing : Check If Exists In Database | {selectStatement}")
if not self.query(selectStatement, sansTran):
raise AssertionError(msg or f"Expected to have have at least one row, "
f"but got 0 rows from: '{selectStatement}'")
def check_if_not_exists_in_database(self, selectStatement, sansTran=False, msg=None):
"""
This is the negation of `check_if_exists_in_database`.
Check if no rows would be returned by given the input `selectStatement`. If there are any results, then this
will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit
transaction commit or rollback. The default error message can be overridden with the `msg` argument.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you have the following assertions in your robot
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' |
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' |
Then you will get the following:
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' | # PASS |
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | # FAIL |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' | True |
Using optional `msg` to override the default error message:
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | msg=my error message |
"""
logger.info(f"Executing : Check If Not Exists In Database | {selectStatement}")
queryResults = self.query(selectStatement, sansTran)
if queryResults:
raise AssertionError(msg or f"Expected to have have no rows from '{selectStatement}', "
f"but got some rows: {queryResults}")
def row_count_is_0(self, selectStatement, sansTran=False, msg=None):
"""
Check if any rows are returned from the submitted `selectStatement`. If there are, then this will throw an
AssertionError. Set optional input `sansTran` to True to run command without an explicit transaction commit or
rollback. The default error message can be overridden with the `msg` argument.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you have the following assertions in your robot
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' |
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' |
Then you will get the following:
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' | # FAIL |
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' | # PASS |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' | True |
Using optional `msg` to override the default error message:
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' | msg=my error message |
"""
logger.info(f"Executing : Row Count Is 0 | selectStatement")
num_rows = self.row_count(selectStatement, sansTran)
if num_rows > 0:
raise AssertionError(msg or f"Expected 0 rows, but {num_rows} were returned from: '{selectStatement}'")
def row_count_is_equal_to_x(self, selectStatement, numRows, sansTran=False, msg=None):
"""
Check if the number of rows returned from `selectStatement` is equal to the value submitted. If not, then this
will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit
transaction commit or rollback. The default error message can be overridden with the `msg` argument.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you have the following assertions in your robot
| Row Count Is Equal To X | SELECT id FROM person | 1 |
| Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 |
Then you will get the following:
| Row Count Is Equal To X | SELECT id FROM person | 1 | # FAIL |
| Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 | # PASS |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 | True |
Using optional `msg` to override the default error message:
| Row Count Is Equal To X | SELECT id FROM person | 1 | msg=my error message |
"""
logger.info(f"Executing : Row Count Is Equal To X | {selectStatement} | {numRows}")
num_rows = self.row_count(selectStatement, sansTran)
if num_rows != int(numRows.encode('ascii')):
raise AssertionError(msg or f"Expected {numRows} rows, "
f"but {num_rows} were returned from: '{selectStatement}'")
def row_count_is_greater_than_x(self, selectStatement, numRows, sansTran=False, msg=None):
"""
Check if the number of rows returned from `selectStatement` is greater than the value submitted. If not, then
this will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit
transaction commit or rollback. The default error message can be overridden with the `msg` argument.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you have the following assertions in your robot
| Row Count Is Greater Than X | SELECT id FROM person | 1 |
| Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 |
Then you will get the following:
| Row Count Is Greater Than X | SELECT id FROM person | 1 | # PASS |
| Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 | # FAIL |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Row Count Is Greater Than X | SELECT id FROM person | 1 | True |
Using optional `msg` to override the default error message:
| Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 | msg=my error message |
"""
logger.info(f"Executing : Row Count Is Greater Than X | {selectStatement} | {numRows}")
num_rows = self.row_count(selectStatement, sansTran)
if num_rows <= int(numRows.encode('ascii')):
raise AssertionError(msg or f"Expected more than {numRows} rows, "
f"but {num_rows} were returned from '{selectStatement}'")
def row_count_is_less_than_x(self, selectStatement, numRows, sansTran=False, msg=None):
"""
Check if the number of rows returned from `selectStatement` is less than the value submitted. If not, then this
will throw an AssertionError. Set optional input `sansTran` to True to run command without an explicit
transaction commit or rollback.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you have the following assertions in your robot
| Row Count Is Less Than X | SELECT id FROM person | 3 |
| Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 |
Then you will get the following:
| Row Count Is Less Than X | SELECT id FROM person | 3 | # PASS |
| Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 | # FAIL |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Row Count Is Less Than X | SELECT id FROM person | 3 | True |
Using optional `msg` to override the default error message:
| Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 | msg=my error message |
"""
logger.info(f"Executing : Row Count Is Less Than X | {selectStatement} | {numRows}")
num_rows = self.row_count(selectStatement, sansTran)
if num_rows >= int(numRows.encode('ascii')):
raise AssertionError(msg or f"Expected less than {numRows} rows, "
f"but {num_rows} were returned from '{selectStatement}'")
def table_must_exist(self, tableName, sansTran=False, msg=None):
"""
Check if the table given exists in the database. Set optional input `sansTran` to True to run command without an
explicit transaction commit or rollback. The default error message can be overridden with the `msg` argument.
For example, given we have a table `person` in a database
When you do the following:
| Table Must Exist | person |
Then you will get the following:
| Table Must Exist | person | # PASS |
| Table Must Exist | first_name | # FAIL |
Using optional `sansTran` to run command without an explicit transaction commit or rollback:
| Table Must Exist | person | True |
Using optional `msg` to override the default error message:
| Table Must Exist | first_name | msg=my error message |
"""
logger.info('Executing : Table Must Exist | %s ' % tableName)
if self.db_api_module_name in ["cx_Oracle", "oracledb"]:
selectStatement = ("SELECT * FROM all_objects WHERE object_type IN ('TABLE','VIEW') AND owner = SYS_CONTEXT('USERENV', 'SESSION_USER') AND object_name = UPPER('%s')" % tableName)
table_exists = self.row_count(selectStatement, sansTran) > 0
elif self.db_api_module_name in ["sqlite3"]:
selectStatement = ("SELECT name FROM sqlite_master WHERE type='table' AND name='%s' COLLATE NOCASE" % tableName)
table_exists = self.row_count(selectStatement, sansTran) > 0
elif self.db_api_module_name in ["ibm_db", "ibm_db_dbi"]:
selectStatement = ("SELECT name FROM SYSIBM.SYSTABLES WHERE type='T' AND name=UPPER('%s')" % tableName)
table_exists = self.row_count(selectStatement, sansTran) > 0
elif self.db_api_module_name in ["teradata"]:
selectStatement = ("SELECT TableName FROM DBC.TablesV WHERE TableKind='T' AND TableName='%s'" % tableName)
table_exists = self.row_count(selectStatement, sansTran) > 0
else:
try:
selectStatement = (f"SELECT * FROM information_schema.tables WHERE table_name='{tableName}'")
table_exists = self.row_count(selectStatement, sansTran) > 0
except:
logger.info("Database doesn't support information schema, try using a simple SQL request")
try:
selectStatement = (f"SELECT 1 from {tableName} where 1=0")
num_rows = self.row_count(selectStatement, sansTran)
table_exists = True
except:
table_exists = False
assert table_exists, msg or f"Table '{tableName}' does not exist in the db" | /robotframework_databaselibrary-1.3.1-py3-none-any.whl/DatabaseLibrary/assertion.py | 0.909156 | 0.583233 | assertion.py | pypi |
from robot.api import logger
class Query(object):
"""
Query handles all the querying done by the Database Library.
"""
def query(self, selectStatement):
"""
Uses the input `selectStatement` to query for the values that
will be returned as a list of tuples.
Tip: Unless you want to log all column values of the specified rows,
try specifying the column names in your select statements
as much as possible to prevent any unnecessary surprises with schema
changes and to easily see what your [] indexing is trying to retrieve
(i.e. instead of `"select * from my_table"`, try
`"select id, col_1, col_2 from my_table"`).
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you do the following:
| @{queryResults} | Query | SELECT * FROM person |
| Log Many | @{queryResults} |
You will get the following:
[1, 'Franz Allan', 'See']
Also, you can do something like this:
| ${queryResults} | Query | SELECT first_name, last_name FROM person |
| Log | ${queryResults[0][1]}, ${queryResults[0][0]} |
And get the following
See, Franz Allan
"""
cur = None
try:
cur = self._dbconnection.cursor()
self.__execute_sql(cur, selectStatement)
allRows = cur.fetchall()
return allRows
finally :
if cur :
self._dbconnection.rollback()
def row_count(self, selectStatement):
"""
Uses the input `selectStatement` to query the database and returns
the number of rows from the query.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you do the following:
| ${rowCount} | Row Count | SELECT * FROM person |
| Log | ${rowCount} |
You will get the following:
2
Also, you can do something like this:
| ${rowCount} | Row Count | SELECT * FROM person WHERE id = 2 |
| Log | ${rowCount} |
And get the following
1
"""
cur = None
try:
cur = self._dbconnection.cursor()
self.__execute_sql(cur, selectStatement)
data = cur.fetchall()
if self.db_api_module_name in ["sqlite3", "ibm_db", "ibm_db_dbi"]:
rowCount = len(data)
else:
rowCount = cur.rowcount
return rowCount
finally :
if cur :
self._dbconnection.rollback()
def description(self, selectStatement):
"""
Uses the input `selectStatement` to query a table in the db which
will be used to determine the description.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you do the following:
| @{queryResults} | Description | SELECT * FROM person |
| Log Many | @{queryResults} |
You will get the following:
[Column(name='id', type_code=1043, display_size=None, internal_size=255, precision=None, scale=None, null_ok=None)]
[Column(name='first_name', type_code=1043, display_size=None, internal_size=255, precision=None, scale=None, null_ok=None)]
[Column(name='last_name', type_code=1043, display_size=None, internal_size=255, precision=None, scale=None, null_ok=None)]
"""
cur = None
try:
cur = self._dbconnection.cursor()
self.__execute_sql(cur, selectStatement)
description = cur.description
return description
finally :
if cur :
self._dbconnection.rollback()
def delete_all_rows_from_table(self, tableName):
"""
Delete all the rows within a given table.
For example, given we have a table `person` in a database
When you do the following:
| Delete All Rows From Table | person |
If all the rows can be successfully deleted, then you will get:
| Delete All Rows From Table | person | # PASS |
If the table doesn't exist or all the data can't be deleted, then you
will get:
| Delete All Rows From Table | first_name | # FAIL |
"""
cur = None
selectStatement = ("DELETE FROM %s;" % tableName)
try:
cur = self._dbconnection.cursor()
result = self.__execute_sql(cur, selectStatement)
if result is not None:
self._dbconnection.commit()
return result
self._dbconnection.commit()
finally :
if cur :
self._dbconnection.rollback()
def execute_sql_script(self, sqlScriptFileName):
"""
Executes the content of the `sqlScriptFileName` as SQL commands.
Useful for setting the database to a known state before running
your tests, or clearing out your test data after running each a
test.
Sample usage :
| Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-setup.sql |
| Execute Sql Script | ${EXECDIR}${/}resources${/}DML-setup.sql |
| #interesting stuff here |
| Execute Sql Script | ${EXECDIR}${/}resources${/}DML-teardown.sql |
| Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-teardown.sql |
SQL commands are expected to be delimited by a semi-colon (';').
For example:
DELETE FROM person_employee_table;
DELETE FROM person_table;
DELETE FROM employee_table;
Also, the last SQL command can optionally omit its trailing semi-colon.
For example:
DELETE FROM person_employee_table;
DELETE FROM person_table;
DELETE FROM employee_table
Given this, that means you can create spread your SQL commands in several
lines.
For example:
DELETE
FROM person_employee_table;
DELETE
FROM person_table;
DELETE
FROM employee_table
However, lines that starts with a number sign (`#`) are treated as a
commented line. Thus, none of the contents of that line will be executed.
For example:
# Delete the bridging table first...
DELETE
FROM person_employee_table;
# ...and then the bridged tables.
DELETE
FROM person_table;
DELETE
FROM employee_table
"""
sqlScriptFile = open(sqlScriptFileName)
cur = None
try:
cur = self._dbconnection.cursor()
sqlStatement = ''
for line in sqlScriptFile:
line = line.strip()
if line.startswith('#'):
continue
elif line.startswith('--'):
continue
sqlFragments = line.split(';')
if len(sqlFragments) == 1:
sqlStatement += line + ' '
else:
for sqlFragment in sqlFragments:
sqlFragment = sqlFragment.strip()
if len(sqlFragment) == 0:
continue
sqlStatement += sqlFragment + ' '
self.__execute_sql(cur, sqlStatement)
sqlStatement = ''
sqlStatement = sqlStatement.strip()
if len(sqlStatement) != 0:
self.__execute_sql(cur, sqlStatement)
self._dbconnection.commit()
finally:
if cur :
self._dbconnection.rollback()
def execute_sql_string(self, sqlString):
"""
Executes the sqlString as SQL commands.
Useful to pass arguments to your sql.
SQL commands are expected to be delimited by a semi-colon (';').
For example:
| Execute Sql String | DELETE FROM person_employee_table; DELETE FROM person_table |
For example with an argument:
| Execute Sql String | SELECT * FROM person WHERE first_name = ${FIRSTNAME} |
"""
try:
cur = self._dbconnection.cursor()
self.__execute_sql(cur, sqlString)
self._dbconnection.commit()
finally:
if cur:
self._dbconnection.rollback()
def to_chn_str(self, str):
"""decode the utf8 characters"""
return str.decode('gbk')
def __execute_sql(self, cur, sqlStatement):
logger.debug("Executing : %s" % sqlStatement)
return cur.execute(sqlStatement) | /robotframework-databaseslibrary-0.8.10.tar.gz/robotframework-databaseslibrary-0.8.10/src/DatabaseLibrary/query.py | 0.77928 | 0.546073 | query.py | pypi |
class Assertion(object):
"""
Assertion handles all the assertions of Database Library.
"""
def check_if_exists_in_database(self,selectStatement):
"""
Check if any row would be returned by given the input
`selectStatement`. If there are no results, then this will
throw an AssertionError.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you have the following assertions in your robot
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' |
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' |
Then you will get the following:
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | # PASS |
| Check If Exists In Database | SELECT id FROM person WHERE first_name = 'John' | # FAIL |
"""
if not self.query(selectStatement):
raise AssertionError("Expected to have have at least one row from '%s' "
"but got 0 rows." % selectStatement)
def check_if_not_exists_in_database(self,selectStatement):
"""
This is the negation of `check_if_exists_in_database`.
Check if no rows would be returned by given the input
`selectStatement`. If there are any results, then this will
throw an AssertionError.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you have the following assertions in your robot
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' |
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' |
Then you will get the following:
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'John' | # PASS |
| Check If Not Exists In Database | SELECT id FROM person WHERE first_name = 'Franz Allan' | # FAIL |
"""
queryResults = self.query(selectStatement)
if queryResults:
raise AssertionError("Expected to have have no rows from '%s' "
"but got some rows : %s." % (selectStatement, queryResults))
def row_count_is_0(self,selectStatement):
"""
Check if any rows are returned from the submitted `selectStatement`.
If there are, then this will throw an AssertionError.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
When you have the following assertions in your robot
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' |
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' |
Then you will get the following:
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'Franz Allan' | # FAIL |
| Row Count is 0 | SELECT id FROM person WHERE first_name = 'John' | # PASS |
"""
num_rows = self.row_count(selectStatement)
if (num_rows > 0):
raise AssertionError("Expected zero rows to be returned from '%s' "
"but got rows back. Number of rows returned was %s" % (selectStatement, num_rows))
def row_count_is_equal_to_x(self,selectStatement,numRows):
"""
Check if the number of rows returned from `selectStatement` is equal to
the value submitted. If not, then this will throw an AssertionError.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you have the following assertions in your robot
| Row Count Is Equal To X | SELECT id FROM person | 1 |
| Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 |
Then you will get the following:
| Row Count Is Equal To X | SELECT id FROM person | 1 | # FAIL |
| Row Count Is Equal To X | SELECT id FROM person WHERE first_name = 'John' | 0 | # PASS |
"""
num_rows = self.row_count(selectStatement)
if (num_rows != int(numRows.encode('ascii'))):
raise AssertionError("Expected same number of rows to be returned from '%s' "
"than the returned rows of %s" % (selectStatement, num_rows))
def row_count_is_greater_than_x(self,selectStatement,numRows):
"""
Check if the number of rows returned from `selectStatement` is greater
than the value submitted. If not, then this will throw an AssertionError.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you have the following assertions in your robot
| Row Count Is Greater Than X | SELECT id FROM person | 1 |
| Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 |
Then you will get the following:
| Row Count Is Greater Than X | SELECT id FROM person | 1 | # PASS |
| Row Count Is Greater Than X | SELECT id FROM person WHERE first_name = 'John' | 0 | # FAIL |
"""
num_rows = self.row_count(selectStatement)
if (num_rows <= int(numRows.encode('ascii'))):
raise AssertionError("Expected more rows to be returned from '%s' "
"than the returned rows of %s" % (selectStatement, num_rows))
def row_count_is_less_than_x(self,selectStatement,numRows):
"""
Check if the number of rows returned from `selectStatement` is less
than the value submitted. If not, then this will throw an AssertionError.
For example, given we have a table `person` with the following data:
| id | first_name | last_name |
| 1 | Franz Allan | See |
| 2 | Jerry | Schneider |
When you have the following assertions in your robot
| Row Count Is Less Than X | SELECT id FROM person | 3 |
| Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 |
Then you will get the following:
| Row Count Is Less Than X | SELECT id FROM person | 3 | # PASS |
| Row Count Is Less Than X | SELECT id FROM person WHERE first_name = 'John' | 1 | # FAIL |
"""
num_rows = self.row_count(selectStatement)
if (num_rows >= int(numRows.encode('ascii'))):
raise AssertionError("Expected less rows to be returned from '%s' "
"than the returned rows of %s" % (selectStatement, num_rows))
def table_must_exist(self,tableName):
"""
Check if the table given exists in the database.
For example, given we have a table `person` in a database
When you do the following:
| Table Must Exist | person |
Then you will get the following:
| Table Must Exist | person | # PASS |
| Table Must Exist | first_name | # FAIL |
"""
if self.db_api_module_name in ["cx_Oracle"]:
selectStatement = ("SELECT * FROM all_objects WHERE object_type IN ('TABLE','VIEW') AND owner = SYS_CONTEXT('USERENV', 'SESSION_USER') AND object_name = UPPER('%s')" % tableName)
elif self.db_api_module_name in ["sqlite3"]:
selectStatement = ("SELECT name FROM sqlite_master WHERE type='table' AND name='%s' COLLATE NOCASE" % tableName)
elif self.db_api_module_name in ["ibm_db", "ibm_db_dbi"]:
selectStatement = ("SELECT name FROM SYSIBM.SYSTABLES WHERE type='T' AND name=UPPER('%s')" % tableName)
else:
selectStatement = ("SELECT * FROM information_schema.tables WHERE table_name='%s'" % tableName)
num_rows = self.row_count(selectStatement)
if (num_rows == 0):
raise AssertionError("Table '%s' does not exist in the db" % tableName) | /robotframework-databaseslibrary-0.8.10.tar.gz/robotframework-databaseslibrary-0.8.10/src/DatabaseLibrary/assertion.py | 0.827061 | 0.725867 | assertion.py | pypi |
import re
from robot.errors import VariableError # type: ignore
def search_variable(string, identifiers="$@&%*", ignore_errors=False):
if not (isinstance(string, str) and "{" in string):
return VariableMatch(string)
return VariableSearcher(identifiers, ignore_errors).search(string)
class VariableMatch:
def __init__(self, string, identifier=None, base=None, items=(), start=-1, end=-1):
self.string = string
self.identifier = identifier
self.base = base
self.items = items
self.start = start
self.end = end
def resolve_base(self, variables, ignore_errors=False):
if self.identifier:
internal = search_variable(self.base)
self.base = variables.replace_string(
internal,
custom_unescaper=unescape_variable_syntax,
ignore_errors=ignore_errors,
)
@property
def name(self):
return f"{self.identifier}{{{self.base}}}" if self else None
@property
def before(self):
return self.string[: self.start] if self.identifier else self.string
@property
def match(self):
return self.string[self.start : self.end] if self.identifier else None
@property
def after(self):
return self.string[self.end :] if self.identifier else None
@property
def is_variable(self):
return bool(
self.identifier and self.base and self.start == 0 and self.end == len(self.string)
)
@property
def is_list_variable(self):
return bool(self.is_variable and self.identifier == "@" and not self.items)
@property
def is_dict_variable(self):
return bool(self.is_variable and self.identifier == "&" and not self.items)
def __bool__(self):
return self.identifier is not None
def __str__(self):
if not self:
return "<no match>"
items = "".join("[%s]" % i for i in self.item) if self.items else ""
return f"{self.identifier}{{{self.base}}}{items}"
class VariableSearcher:
def __init__(self, identifiers, ignore_errors=False):
self.identifiers = identifiers
self._ignore_errors = ignore_errors
self.start = -1
self.variable_chars = []
self.item_chars = []
self.items = []
self._open_brackets = 0 # Used both with curly and square brackets
self._escaped = False
def search(self, string):
if not self._search(string):
return VariableMatch(string)
match = VariableMatch(
string=string,
identifier=self.variable_chars[0],
base="".join(self.variable_chars[2:-1]),
start=self.start,
end=self.start + len(self.variable_chars),
)
if self.items:
match.items = tuple(self.items)
match.end += sum(len(i) for i in self.items) + 2 * len(self.items)
return match
def _search(self, string, offset=0):
start = self._find_variable_start(string)
if start == -1:
return False
self.start = start + offset
self._open_brackets += 1
self.variable_chars = [string[start], "{"]
start += 2
state = self.variable_state
for char in string[start:]:
state = state(char)
self._escaped = False if char != "\\" else not self._escaped
if state is None:
break
if state:
try:
self._validate_end_state(state)
except VariableError:
if self._ignore_errors:
return False
raise
return True
def _find_variable_start(self, string):
start = 1
while True:
start = string.find("{", start) - 1
if start < 0:
return -1
if self._start_index_is_ok(string, start):
return start
start += 2
def _start_index_is_ok(self, string, index):
return string[index] in self.identifiers and not self._is_escaped(string, index)
def _is_escaped(self, string, index):
escaped = False
while index > 0 and string[index - 1] == "\\":
index -= 1
escaped = not escaped
return escaped
def variable_state(self, char):
self.variable_chars.append(char)
if char == "}" and not self._escaped:
self._open_brackets -= 1
if self._open_brackets == 0:
if not self._can_have_items():
return None
return self.waiting_item_state
elif char == "{" and not self._escaped:
self._open_brackets += 1
return self.variable_state
def _can_have_items(self):
return self.variable_chars[0] in "$@&"
def waiting_item_state(self, char):
if char == "[":
self._open_brackets += 1
return self.item_state
return None
def item_state(self, char):
if char == "]" and not self._escaped:
self._open_brackets -= 1
if self._open_brackets == 0:
self.items.append("".join(self.item_chars))
self.item_chars = []
# Don't support chained item access with old @ and & syntax.
# The old syntax was deprecated in RF 3.2 and in RF 3.3 it'll
# be reassigned to mean using item in list/dict context.
if self.variable_chars[0] in "@&":
return None
return self.waiting_item_state
elif char == "[" and not self._escaped:
self._open_brackets += 1
self.item_chars.append(char)
return self.item_state
def _validate_end_state(self, state):
if state == self.variable_state:
incomplete = "".join(self.variable_chars)
raise VariableError("Variable '%s' was not closed properly." % incomplete)
if state == self.item_state:
variable = "".join(self.variable_chars)
items = "".join("[%s]" % i for i in self.items)
incomplete = "".join(self.item_chars)
raise VariableError(
"Variable item '{}{}[{}' was not closed "
"properly.".format(variable, items, incomplete)
)
def unescape_variable_syntax(item):
def handle_escapes(match):
escapes, text = match.groups()
if len(escapes) % 2 == 1 and starts_with_variable_or_curly(text):
return escapes[1:]
return escapes
def starts_with_variable_or_curly(text):
if text[0] in "{}":
return True
match = search_variable(text, ignore_errors=True)
return match and match.start == 0
return re.sub(r"(\\+)(?=(.+))", handle_escapes, item)
# TODO: This is pretty odd/ugly and used only in two places. Implement
# something better or just remove altogether.
class VariableIterator:
def __init__(self, string, identifiers="$@&%*"):
self._string = string
self._identifiers = identifiers
def __iter__(self):
remaining = self._string
while True:
match = search_variable(remaining, self._identifiers)
if not match:
break
remaining = match.after
yield match.before, match.match, remaining
def __len__(self):
return sum(1 for _ in self)
def __bool__(self):
try:
next(iter(self))
except StopIteration:
return False
else:
return True | /robotframework-datadriver-1.9.0.tar.gz/robotframework-datadriver-1.9.0/src/DataDriver/search.py | 0.513912 | 0.26662 | search.py | pypi |
from typing import Any, Dict, List, Optional
from robot.utils import DotDict # type: ignore
from .utils import PabotOpt, TagHandling
class ReaderConfig:
TEST_CASE_TABLE_NAME = "*** Test Cases ***"
def __init__(
self,
file: Optional[str] = None,
encoding: Optional[str] = None,
dialect: Optional[str] = None,
delimiter: Optional[str] = None,
quotechar: Optional[str] = None,
escapechar: Optional[str] = None,
doublequote: Optional[bool] = None,
skipinitialspace: Optional[bool] = None,
lineterminator: Optional[str] = None,
sheet_name: Any = None,
reader_class: Any = None,
file_search_strategy: str = "path",
file_regex: Optional[str] = None,
include: Optional[str] = None,
exclude: Optional[str] = None,
handle_template_tags: TagHandling = TagHandling.UnsetTags,
list_separator: Optional[str] = ",",
config_keyword: Optional[str] = None,
optimize_pabot: PabotOpt = PabotOpt.Equal,
**kwargs,
):
self.file = file
self.encoding = encoding
self.dialect = dialect
self.delimiter = delimiter
self.quotechar = quotechar
self.escapechar = escapechar
self.doublequote = doublequote
self.skipinitialspace = skipinitialspace
self.lineterminator = lineterminator
self.sheet_name = sheet_name
self.reader_class = reader_class
self.file_search_strategy = file_search_strategy
self.file_regex = file_regex
self.include = include
self.exclude = exclude
self.handle_template_tags = handle_template_tags
self.list_separator = list_separator
self.config_keyword = config_keyword
self.optimize_pabot = optimize_pabot
self.kwargs = kwargs
class TestCaseData(DotDict):
def __init__(
self,
test_case_name: str = "",
arguments: Optional[Dict] = None,
tags: Optional[List] = None,
documentation: Optional[str] = None,
):
super().__init__()
self.test_case_name = test_case_name
self.arguments = arguments if arguments else {}
self.tags = tags
self.documentation = documentation | /robotframework-datadriver-1.9.0.tar.gz/robotframework-datadriver-1.9.0/src/DataDriver/ReaderConfig.py | 0.838531 | 0.258738 | ReaderConfig.py | pypi |
import math
import re
from enum import Enum, auto
from typing import Any, List
from robot.api import logger # type: ignore
from robot.libraries.BuiltIn import BuiltIn # type: ignore
from .argument_utils import is_pabot_testlevelsplit
class Encodings(Enum):
"""
Python comes with a number of codecs built-in,
either implemented as C functions or with dictionaries as mapping tables.
The following table lists the codecs by name,
together with a few common aliases, and the languages for which the encoding is likely used.
Neither the list of aliases nor the list of languages is meant to be exhaustive.
Notice that spelling alternatives that only differ in case or use a hyphen instead
of an underscore are also valid aliases; therefore, e.g. ``utf-8` is a valid alias for the ``utf_8`` codec.
*CPython implementation detail:* Some common encodings can bypass the codecs lookup machinery to improve performance.
These optimization opportunities are only recognized by CPython for a limited set of (case insensitive) aliases:
utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows only),
ascii, us-ascii, utf-16, utf16, utf-32, utf32, and the same using underscores instead of dashes.
Using alternative aliases for these encodings may result in slower execution.
Changed in version 3.6: Optimization opportunity recognized for us-ascii.
Many of the character sets support the same languages. They vary in individual characters (e.g. whether the EURO SIGN is supported or not), and in the assignment of characters to code positions. For the European languages in particular, the following variants typically exist:
- utf-8
- cp1252
- an ISO 8859 codeset
- a Microsoft Windows code page, which is typically derived from an 8859 codeset, but replaces control characters with additional graphic characters
- an IBM EBCDIC code page
- an IBM PC code page, which is ASCII compatible
"""
ascii = auto() # noqa: A003
big5 = auto()
big5hkscs = auto()
cp037 = auto()
cp273 = auto()
cp424 = auto()
cp437 = auto()
cp500 = auto()
cp720 = auto()
cp737 = auto()
cp775 = auto()
cp850 = auto()
cp852 = auto()
cp855 = auto()
cp856 = auto()
cp857 = auto()
cp858 = auto()
cp860 = auto()
cp861 = auto()
cp862 = auto()
cp863 = auto()
cp864 = auto()
cp865 = auto()
cp866 = auto()
cp869 = auto()
cp874 = auto()
cp875 = auto()
cp932 = auto()
cp949 = auto()
cp950 = auto()
cp1006 = auto()
cp1026 = auto()
cp1125 = auto()
cp1140 = auto()
cp1250 = auto()
cp1251 = auto()
cp1252 = auto()
cp1253 = auto()
cp1254 = auto()
cp1255 = auto()
cp1256 = auto()
cp1257 = auto()
cp1258 = auto()
euc_jp = auto()
euc_jis_2004 = auto()
euc_jisx0213 = auto()
euc_kr = auto()
gb2312 = auto()
gbk = auto()
gb18030 = auto()
hz = auto()
iso2022_jp = auto()
iso2022_jp_1 = auto()
iso2022_jp_2 = auto()
iso2022_jp_2004 = auto()
iso2022_jp_3 = auto()
iso2022_jp_ext = auto()
iso2022_kr = auto()
latin_1 = auto()
iso8859_2 = auto()
iso8859_3 = auto()
iso8859_4 = auto()
iso8859_5 = auto()
iso8859_6 = auto()
iso8859_7 = auto()
iso8859_8 = auto()
iso8859_9 = auto()
iso8859_10 = auto()
iso8859_11 = auto()
iso8859_13 = auto()
iso8859_14 = auto()
iso8859_15 = auto()
iso8859_16 = auto()
johab = auto()
koi8_r = auto()
koi8_t = auto()
koi8_u = auto()
kz1048 = auto()
mac_cyrillic = auto()
mac_greek = auto()
mac_iceland = auto()
mac_latin2 = auto()
mac_roman = auto()
mac_turkish = auto()
ptcp154 = auto()
shift_jis = auto()
shift_jis_2004 = auto()
shift_jisx0213 = auto()
utf_32 = auto()
utf_32_be = auto()
utf_32_le = auto()
utf_16 = auto()
utf_16_be = auto()
utf_16_le = auto()
utf_7 = auto()
utf_8 = auto()
utf_8_sig = auto()
class PabotOpt(Enum):
"""
You can switch Pabot --testlevelsplit between three modes:
- Equal: means it creates equal sizes groups
- Binary: is more complex. it created a decreasing size of containers to support better balancing.
- Atomic: it does not group tests at all and runs really each test case in a separate thread.
See `Pabot and DataDriver <#pabot-and-datadriver>`__ for more details.
This can be set by ``optimize_pabot`` in Library import.
"""
Equal = auto()
Binary = auto()
Atomic = auto()
class TagHandling(Enum):
"""
You can configure how to handle tags from the template in generated tests:
- ForceTags: Will add all tags of the template test to all data-driven test cases.
- UnsetTags: Will add only these tags from template test to the tests, that are not assigned to any of the test cases.
- DefaultTags: Will only add tags to data-driven test if no tag is set on that test.
- NoTags: Will not add any tags from the template to date-driven tests.
"""
ForceTags = auto()
UnsetTags = auto()
DefaultTags = auto()
NoTags = auto()
def debug(msg: Any, newline: bool = True, stream: str = "stdout"):
if get_variable_value("${LOG LEVEL}") in ["DEBUG", "TRACE"]:
logger.console(msg, newline, stream)
def console(msg: Any, newline: bool = True, stream: str = "stdout"):
logger.console(msg, newline, stream)
def warn(msg: Any, html: bool = False):
logger.warn(msg, html)
def error(msg: Any, html: bool = False):
logger.error(msg, html)
def get_filter_dynamic_test_names():
dynamic_test_list = get_variable_value("${DYNAMICTESTS}")
if isinstance(dynamic_test_list, str):
test_names_esc = re.split(r"(?<!\\)(?:\\\\)*\|", dynamic_test_list)
return [name.replace("\\|", "|").replace("\\\\", "\\") for name in test_names_esc]
if isinstance(dynamic_test_list, list):
return dynamic_test_list
dynamic_test_name = get_variable_value("${DYNAMICTEST}")
if dynamic_test_name:
BuiltIn().set_suite_metadata("DataDriver", dynamic_test_name, True)
return [dynamic_test_name]
return None
def is_pabot_dry_run():
return is_pabot_testlevelsplit() and get_variable_value("${PABOTQUEUEINDEX}") == "-1"
def get_variable_value(name: str):
return BuiltIn().get_variable_value(name)
def is_same_keyword(first: str, second: str):
return _get_normalized_keyword(first) == _get_normalized_keyword(second)
def _get_normalized_keyword(keyword: str):
return keyword.lower().replace(" ", "").replace("_", "")
def binary_partition_test_list(test_list: List, process_count: int):
fractions = equally_partition_test_list(test_list, process_count)
return_list = []
for _i in range(int(math.sqrt(len(test_list) // process_count))):
first, second = _partition_second_half(fractions)
return_list.extend(first)
fractions = second
return_list.extend(fractions)
return [test_name for test_name in return_list if test_name]
def _partition_second_half(fractions):
first = fractions[: len(fractions) // 2]
second = []
for sub_list in fractions[len(fractions) // 2 :]:
sub_sub_list = equally_partition_test_list(sub_list, 2)
second.extend(sub_sub_list)
return first, second
def equally_partition_test_list(test_list: List, fraction_count: int):
quotient, remainder = divmod(len(test_list), fraction_count)
return [
test_list[i * quotient + min(i, remainder) : (i + 1) * quotient + min(i + 1, remainder)]
for i in range(fraction_count)
] | /robotframework-datadriver-1.9.0.tar.gz/robotframework-datadriver-1.9.0/src/DataDriver/utils.py | 0.749637 | 0.351228 | utils.py | pypi |
import time
from datetime import datetime
from dateutil.parser import parse
from babel.dates import format_datetime
from dateutil.relativedelta import relativedelta
class DateTimeTZ:
"""
Robot Framework [https://github.com/testautomation/DateTimeTZ|DateTimeTZ] library provides functionality for manipulating date and time in different locales and time zones.\n
DateTime library is based on [http://babel.pocoo.org|Babel] and [http://labix.org/python-dateutil|python-dateutil].
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
def wait(self, seconds):
"""
Suspends test execution for the given number of seconds.\n
*Example usage:*
| *Keyword* | *Argument* |
| Wait | 5 |
"""
print("Suspend test execution on " + str(seconds) + " seconds.")
time.sleep(int(seconds))
def get_unix_time(self):
"""
Returns current Unix time.\n
*Example usage:*
| *Variable* | *Keyword* |
| ${unix_time} | Get Unix Time |
*Example result:*\n
INFO : ${unix_time} = 1394694526.94
"""
return time.time()
def get_timestamp(self, locale="en", time_format="dd-LL-y H:mm:ss.A", *args, **delta):
"""
Returns current local timestamp in defined format and locale.\n
_"locale"_ argument allows to set timestamp languages such as the ISO country and language codes.\n
_"time_format"_ argument allows to set timestamp pattern for representation as described below.\n
*Date format:*
| *Field* | *Symbol* | *Description* |
| Era | G | Replaced with the era string for the current date. One to three letters for the abbreviated form, four letters for the long form, five for the narrow form. |
| Year | y | Replaced by the year. Normally the length specifies the padding, but for two letters it also specifies the maximum length. |
| | Y | Same as y but uses the ISO year-week calendar. |
| Quarter | Q | Use one or two for the numerical quarter, three for the abbreviation, or four for the full name. |
| | q | Use one or two for the numerical quarter, three for the abbreviation, or four for the full name. |
| Month | M | Use one or two for the numerical month, three for the abbreviation, or four for the full name, or five for the narrow name. |
| | L | Use one or two for the numerical month, three for the abbreviation, or four for the full name, or 5 for the narrow name. |
| Week | w | Week of year. |
| | W | Week of month. |
| Day | d | Day of month. |
| | D | Day of year. |
| | F | Day of week in month. |
| Week day | E | Day of week. Use one through three letters for the short day, or four for the full name, or five for the narrow name. |
| | e | Local day of week. Same as E except adds a numeric value that will depend on the local starting day of the week, using one or two letters. |
*Time format:*\n
| *Field* | *Symbol* | *Description* |
| Period | a | AM or PM. |
| Hour | h | Hour [1-12]. |
| | H | Hour [0-23]. |
| | K | Hour [0-11]. |
| | k | Hour [1-24]. |
| Minute | m | Use one or two for zero places padding. |
| Second | s | Use one or two for zero places padding. |
| | S | Fractional second, rounds to the count of letters. |
| | A | Milliseconds in day. |
| Timezone | z | Use one to three letters for the short timezone or four for the full name. |
| | Z | Use one to three letters for RFC 822, four letters for GMT format. |
| | v | Use one letter for short wall (generic) time, four for long wall time. |
| | V | Same as z, except that timezone abbreviations should be used regardless of whether they are in common use by the locale. |
_"delta"_ argument allows to set timestamp delta (minus or plus). It allows take one or multiple parameters such as: years, months, weeks, days, hours, minutes, seconds, microseconds.\n
_"delta"_ also allows to set specific timestamp parts (year, month, day, hour, minute, second, microsecond).\n
*Example usage:*
| *Variable* | *Keyword* | *Argument* | *Argument* | *Argument* | *Argument* |
| ${timestamp} | Get Timestamp | locale=rus | time_format=dd LLL y H:mm:ss |
| ${timestamp_with_delta} | Get Timestamp | locale=rus | time_format=LLL y H:mm | months=-2 |
| ${timestamp_with_delta} | Get Timestamp | locale=rus | time_format=LLL y H:mm | months=-2 | year=2012 |
*Example result:*\n
INFO : ${timestamp} = 13 Март 2014 17:54:57\n
INFO : ${timestamp_with_delta} = Янв. 2014 17:54\n
INFO : ${delta_and_cpecific_part} = Янв. 2012 17:54
"""
delta = dict((key, int(value)) for (key, value) in list(delta.items()))
timestamp = datetime.today() + relativedelta(**delta)
return format_datetime(timestamp, time_format, locale=locale)
def get_utc_timestamp(self, locale="en", time_format="dd-LL-y H:mm:ss.A", *args, **delta):
"""
Returns current UTC timestamp in defined format and locale.\n
*Get Utc Timestamp* keyword arguments are the same as *`Get Timestamp`* arguments.\n
*Example usage:*\n
| *Variable* | *Keyword* | *Argument* | *Argument* |
| ${utc_timestamp} | Get Utc Timestamp | locale=rus | time_format=dd LLL y H:mm:ss |
*Example result:*\n
INFO : ${utc_timestamp} = 13 Март 2014 11:32:58
"""
delta = dict((key, int(value)) for (key, value) in list(delta.items()))
timestamp = datetime.utcnow() + relativedelta(**delta)
return format_datetime(timestamp, time_format, locale=locale)
def convert_timestamp_format(self, timestamp, time_format, locale="en"):
"""
Converts timestamp from one format to another.\n
*Warning!* This keyword support only numeric or string with English locale words timestamps.\n
_"time_format"_ and _"locale"_ arguments are the same as *`Get Timestamp`* arguments.\n
*Example usage:*\n
| *Variable* | *Keyword* | *Argument* | *Argument* |
| ${timestamp} | Get Timestamp |
| ${rus_timestamp} | Convert Timestamp Format | time_format=dd LLL y H:mm:ss | locale=rus |
*Example result:*\n
INFO : ${timestamp} = 13-03-2014 18:38:07.67087810\n
INFO : ${rus_timestamp} = 13 Март 2014 18:38:07
"""
timestamp = parse(timestamp)
return format_datetime(timestamp, time_format, locale=locale) | /robotframework-datetime-tz-1.0.6.tar.gz/robotframework-datetime-tz-1.0.6/src/DateTimeTZ/DateTimeTZ.py | 0.806434 | 0.545951 | DateTimeTZ.py | pypi |
import re
import tempfile
from pathlib import Path
from typing import Iterator, List, Tuple
from robot.libdocpkg.model import KeywordDoc, LibraryDoc
from robot.libraries.BuiltIn import BuiltIn
from robot.parsing import get_model
from robot.running import TestSuite, UserLibrary
from robot.variables.search import is_variable
from .robotlib import ImportedLibraryDocBuilder, ImportedResourceDocBuilder, get_libs
KEYWORD_SEP = re.compile(" +|\t")
_lib_keywords_cache = {}
_resource_keywords_cache = {}
temp_resources = []
def parse_keyword(command) -> Tuple[List[str], str, List[str]]:
"""Split a robotframework keyword string."""
# TODO use robotframework functions
variables = []
keyword = ""
args = []
parts = KEYWORD_SEP.split(command)
for part in parts:
if not keyword and is_variable(part.rstrip("=").strip()):
variables.append(part.rstrip("=").strip())
elif not keyword:
keyword = part
else:
args.append(part)
return variables, keyword, args
def get_lib_keywords(library) -> List[KeywordDoc]:
"""Get keywords of imported library."""
if library.name not in _lib_keywords_cache:
if isinstance(library, UserLibrary):
_lib_keywords_cache[library.name]: LibraryDoc = ImportedResourceDocBuilder().build(
library
)
else:
_lib_keywords_cache[library.name]: LibraryDoc = ImportedLibraryDocBuilder().build(
library
)
return _lib_keywords_cache[library.name].keywords
def get_keywords() -> Iterator[KeywordDoc]:
"""Get all keywords of libraries."""
for lib in get_libs():
yield from get_lib_keywords(lib)
def find_keyword(keyword_name) -> List[KeywordDoc]:
keyword_name = keyword_name.lower()
return [
keyword
for lib in get_libs()
for keyword in get_lib_keywords(lib)
if normalize_kw(keyword.name) == normalize_kw(keyword_name)
]
def normalize_kw(keyword_name):
return keyword_name.lower().replace("_", "").replace(" ", "")
def get_test_body_from_string(command):
if "\n" in command:
command = "\n ".join(command.split("\n"))
suite_str = f"""
*** Test Cases ***
Fake Test
{command}
"""
model = get_model(suite_str)
suite: TestSuite = TestSuite.from_model(model)
return suite.tests[0]
def _import_resource_from_string(command):
res_file = tempfile.NamedTemporaryFile(
mode="w",
prefix="RobotDebug_keywords_",
suffix=".resource",
encoding="utf-8",
delete=False,
)
resource_path = Path(res_file.name)
try:
res_file.write(command)
res_file.close()
temp_resources.insert(0, str(resource_path.stem))
BuiltIn().import_resource(resource_path.resolve().as_posix())
BuiltIn().set_library_search_order(*temp_resources)
finally:
resource_path.unlink(missing_ok=True)
def _get_assignments(body_elem):
if hasattr(body_elem, "assign"):
yield from body_elem.assign
else:
for child in body_elem.body:
yield from _get_assignments(child)
def run_debug_if(condition, *args):
"""Runs DEBUG if condition is true."""
return BuiltIn().run_keyword_if(condition, "RobotDebug.DEBUG", *args) | /robotframework_debug-4.3.4-py3-none-any.whl/RobotDebug/robotkeyword.py | 0.423577 | 0.1692 | robotkeyword.py | pypi |
from pathlib import Path
from typing import List, Tuple
from pygments.token import Token
from RobotDebug.lexer import (
RobotFrameworkLocalLexer,
get_robot_token_from_file,
)
from RobotDebug.styles import print_output, print_pygments_styles
LINE_NO_TOKEN = Token.Operator.LineNumber
def print_source_lines(style, source_file, lineno, before_and_after=5):
if not source_file or not lineno:
return
Path(source_file).open().readlines()
prefixed_token = get_pygments_token_from_file(lineno, source_file)
printable_token = filter_token_by_lineno(
prefixed_token, lineno - before_and_after, lineno + before_and_after + 1
)
print_pygments_styles(printable_token, style)
def print_test_case_lines(style, source_file, current_lineno):
if not source_file or not current_lineno:
return
Path(source_file).open().readlines()
prefixed_token = get_pygments_token_from_file(current_lineno, source_file)
printable_token = filter_token_by_scope(prefixed_token, current_lineno)
print_pygments_styles(printable_token, style)
def filter_token_by_lineno(token, start_lineno, end_lineno):
current_lineno = 0
for tok, val in token:
if tok == LINE_NO_TOKEN:
current_lineno += 1
if start_lineno <= current_lineno < end_lineno:
yield tok, val
def filter_token_by_scope(token, current_lineno):
rf_to_py = RobotFrameworkLocalLexer.ROBOT_TO_PYGMENTS
scope_start_lineno = 0
scope_end_lineno = 1000000
line_found = False
lineno = 0
all_token = list(token)
for tok, _val in all_token:
if tok == LINE_NO_TOKEN:
lineno += 1
if not line_found and tok in [rf_to_py["HEADER"], rf_to_py["DEFINITION"]]:
scope_start_lineno = lineno
if lineno == current_lineno:
line_found = True
if line_found and tok in [rf_to_py["HEADER"], rf_to_py["DEFINITION"]]:
scope_end_lineno = lineno
break
filtered_token = list(filter_token_by_lineno(all_token, scope_start_lineno, scope_end_lineno))
tokens_to_remove = 0
for tok, val in reversed(filtered_token):
if tok == LINE_NO_TOKEN or val == "\n" or not val.strip():
tokens_to_remove += 1
else:
break
if tokens_to_remove:
return filtered_token[:-tokens_to_remove]
return filtered_token
def get_pygments_token_from_file(current_lineno, source_file):
token = get_robot_token_from_file(Path(source_file))
pygments_token = list(RobotFrameworkLocalLexer().get_pygments_token(token))
return prefix_line_numbers_and_position(pygments_token, current_lineno)
def prefix_line_numbers_and_position(token: List[Tuple], lineno):
"""prefix each line with a pygment token of line number and add an arrow in the line of lineno"""
line_number = 1
yield LINE_NO_TOKEN, f"{line_number:>3} "
for tok, val in token:
yield tok, val
if val == "\n":
line_number += 1
if line_number == lineno:
yield LINE_NO_TOKEN, f"{line_number:>3} ->"
else:
yield LINE_NO_TOKEN, f"{line_number:>3} "
def _find_last_lineno(lines, begin_lineno):
line_index = begin_lineno - 1
while line_index < len(lines):
line = lines[line_index]
if not _inside_test_case_block(line):
break
line_index += 1
return line_index
def _find_first_lineno(lines, begin_lineno):
line_index = begin_lineno - 1
while line_index >= 0:
line_index -= 1
line = lines[line_index]
if not _inside_test_case_block(line):
break
return line_index
def _inside_test_case_block(line):
if line.startswith(" "):
return True
if line.startswith("\t"):
return True
if line.startswith("#"):
return True
return False
def _print_lines(lines, start_index, end_index, current_lineno):
display_lines = lines[start_index:end_index]
for lineno, line in enumerate(display_lines, start_index + 1):
current_line_sign = ""
if lineno == current_lineno:
current_line_sign = "->"
print_output(f"{lineno:>3} {current_line_sign:2}\t", f"{line.rstrip()}") | /robotframework_debug-4.3.4-py3-none-any.whl/RobotDebug/sourcelines.py | 0.532425 | 0.183777 | sourcelines.py | pypi |
from prompt_toolkit import print_formatted_text
from prompt_toolkit.completion import Completion
from prompt_toolkit.formatted_text import FormattedText, PygmentsTokens
from prompt_toolkit.styles import Style, merge_styles, style_from_pygments_cls
from pygments.styles import get_all_styles, get_style_by_name
NORMAL_STYLE = Style.from_dict(
{
"head": "fg:blue",
"message": "fg:silver",
}
)
LOW_VISIBILITY_STYLE = Style.from_dict(
{
"head": "fg:blue",
"message": "fg:#333333",
}
)
ERROR_STYLE = Style.from_dict({"head": "fg:red"})
BASE_STYLE = Style.from_dict(
{
"pygments.name.function": "bold",
"pygments.literal.string": "italic",
"pygments.name.class": "underline",
"bottom-toolbar": "#333333 bg:#ffffff",
"bottom-toolbar-key": "#333333 bg:#aaaaff",
}
)
DEBUG_PROMPT_STYLE = merge_styles(
[
BASE_STYLE,
style_from_pygments_cls(get_style_by_name("solarized-dark")),
]
)
def get_pygments_styles():
"""Get all pygments styles."""
return list(get_all_styles())
def print_pygments_styles(token, style=DEBUG_PROMPT_STYLE):
print_formatted_text(PygmentsTokens(token), style=style)
def print_output(head, message, style=NORMAL_STYLE):
"""Print prompt-toolkit tokens to output."""
tokens = FormattedText(
[
("class:head", f"{head} "),
("class:message", message),
("", ""),
]
)
print_formatted_text(tokens, style=style)
def print_error(head, message, style=ERROR_STYLE):
"""Print to output with error style."""
print_output(head, message, style=style)
def get_debug_prompt_tokens(prompt_text):
"""Print prompt-toolkit prompt."""
return [
("class:prompt", prompt_text),
]
def _get_print_style(style: str) -> Style:
stl = dict(style_from_pygments_cls(get_style_by_name(style)).style_rules)
head = stl.get("pygments.name.function")
message = stl.get("pygments.literal.string")
return Style.from_dict({"head": head, "message": message})
def _get_style_completions(text):
style_part = text.lstrip("style").strip()
start = -len(style_part)
return (
Completion(
name,
start,
display=name,
display_meta="",
style=dict(style_from_pygments_cls(get_style_by_name(name)).style_rules).get(
"pygments.name.function"
),
)
for name in get_pygments_styles()
if (name.lower().strip().startswith(style_part))
) | /robotframework_debug-4.3.4-py3-none-any.whl/RobotDebug/styles.py | 0.464659 | 0.150372 | styles.py | pypi |
from robot.version import get_version
ROBOT_VERION_RUNNER_GET_STEP_LINENO = '3.2'
class RobotNeedUpgrade(Exception):
"""Need upgrade robotframework."""
def check_version():
if get_version() < ROBOT_VERION_RUNNER_GET_STEP_LINENO:
raise RobotNeedUpgrade
def print_source_lines(source_file, lineno, before_and_after=5):
check_version()
if not source_file or not lineno:
return
lines = open(source_file).readlines()
start_index = max(1, lineno - before_and_after - 1)
end_index = min(len(lines) + 1, lineno + before_and_after)
_print_lines(lines, start_index, end_index, lineno)
def print_test_case_lines(source_file, current_lineno):
check_version()
if not source_file or not current_lineno:
return
lines = open(source_file).readlines()
# find the first line of current test case
start_index = _find_first_lineno(lines, current_lineno)
# find the last line of current test case
end_index = _find_last_lineno(lines, current_lineno)
_print_lines(lines, start_index, end_index, current_lineno)
def _find_last_lineno(lines, begin_lineno):
line_index = begin_lineno - 1
while line_index < len(lines):
line = lines[line_index]
if not _inside_test_case_block(line):
break
line_index += 1
return line_index
def _find_first_lineno(lines, begin_lineno):
line_index = begin_lineno - 1
while line_index >= 0:
line_index -= 1
line = lines[line_index]
if not _inside_test_case_block(line):
break
return line_index
def _inside_test_case_block(line):
if line.startswith(' '):
return True
if line.startswith('\t'):
return True
if line.startswith('#'):
return True
return False
def _print_lines(lines, start_index, end_index, current_lineno):
display_lines = lines[start_index:end_index]
for lineno, line in enumerate(display_lines, start_index + 1):
current_line_sign = ''
if lineno == current_lineno:
current_line_sign = '->'
print('{:>3} {:2}\t{}'.format(lineno,
current_line_sign,
line.rstrip())) | /robotframework-debuglibrary-2.3.0.tar.gz/robotframework-debuglibrary-2.3.0/DebugLibrary/sourcelines.py | 0.53048 | 0.282249 | sourcelines.py | pypi |
import re
import subprocess
from typing import AnyStr, Dict, List, Match, Optional, Union
from src.Utils import Const, DotDictionary, Utils
class DockerLibrary:
def create_multiple_containers(self, n_containers: int, image: str) -> \
List[str]:
containers_id: List[str] = list()
for _ in range(n_containers):
con_id = str(self.docker('run', '-dt', image).stdout)
if con_id:
containers_id.append(Utils.parse_containers_ids(con_id)[0])
return containers_id
def docker_command_for_all(self, containers_ids: Union[List[str], str],
parse_to_dotd: bool, *args: Optional[str]) -> Dict[str, Union[DotDictionary, str]]:
result: Dict[str, Union[List[DotDictionary], DotDictionary, str]] = dict()
ids = containers_ids
if isinstance(containers_ids, str):
ids = Utils.parse_containers_ids(containers_ids)
for con_id in ids:
result[con_id] = self.parse_docker_response(
self.docker(*args, con_id).stdout, parse_to_dotd)
return result
def docker_in_docker(self,
host_image: str,
dind_image: str,
n_dind: int,
port: Optional[str] = None) -> Dict[str, List[str]]:
result: Dict[str, List[str]] = dict()
con_id: Optional[str] = None
if host_image.lower() in Const.HOST_IMAGES:
self.docker('build', '-t', host_image + "-dind", Const.HOST_IMAGES[host_image])
if port:
con_id = str(self.docker('run', '-dt', '-p', port, '-v',
'/var/run/docker.sock:/var/run/docker.sock', host_image + "-dind").stdout)
else:
con_id = str(self.docker('run', '-dt', '-v',
'/var/run/docker.sock:/var/run/docker.sock', host_image + "-dind").stdout)
if con_id:
host_id = Utils.parse_containers_ids(con_id)[0]
dind_ids: List[str] = list()
for _ in range(n_dind):
dind_ids.append(Utils.parse_containers_ids(str(
self.docker('exec', host_id, 'docker', 'run', '-dt', dind_image).stdout))[0])
result[host_id] = self.parse_docker_response(str(dind_ids), False)
return result
@staticmethod
def docker(*args: Optional[str]) -> subprocess.CompletedProcess:
return subprocess.run(['docker'] + list(args), stdout=subprocess.PIPE)
def get_containers_ids(self) -> List[str]:
text = str(self.docker('ps', '-a', '-q').stdout)
return Utils.parse_containers_ids(text)
def parse_docker_response(self, text: str, parse_to_dotd: bool) -> \
Union[List[DotDictionary], DotDictionary, str]:
decoded_text: str = str(text)
m: Optional[Match[AnyStr]] = Const.DECODE_RE.match(decoded_text)
if m:
decoded_text: Optional[str] = m.groupdict().get("values")
clean_text = re.sub(r'\s+|\\n+', '', decoded_text)
if parse_to_dotd:
return Utils.parse_docker_response_helper(clean_text)
return clean_text | /robotframework-dockerlibrary-1.0.0.tar.gz/robotframework-dockerlibrary-1.0.0/src/DockerLibrary.py | 0.640299 | 0.158435 | DockerLibrary.py | pypi |
import json
import re
from types import SimpleNamespace
from typing import Any, AnyStr, Dict, Iterable, List, Match, Optional, Union
class DotDictionary(SimpleNamespace):
def __init__(self, data, **kwargs):
super().__init__(**kwargs)
for key, value in data.items():
if isinstance(value, dict):
self.__setattr__(key, DotDictionary(value))
elif isinstance(value, str) or isinstance(value, bytes):
self.__setattr__(key, value)
elif isinstance(value, Iterable):
list_values: List[Any] = []
for v in value:
list_values.append(DotDictionary(v) if isinstance(v, dict) else v)
self.__setattr__(key, list_values)
else:
self.__setattr__(key, value)
class Utils:
@staticmethod
def parse_containers_ids(text: str) -> List[str]:
m: Optional[Match[AnyStr]] = Const.DECODE_RE.match(text)
containers_ids: List[str] = list()
if m:
ids: Optional[str] = m.groupdict().get("values")
if ids:
containers_ids = list(filter(None, ids.split('\\n')))
return containers_ids
@staticmethod
def parse_docker_response_helper(text: str) -> \
Union[List[DotDictionary], DotDictionary, str]:
try:
data = json.loads(text)
if isinstance(data, list):
if len(data) > 1:
result: List[DotDictionary] = list()
for d in data:
result.append(DotDictionary(d))
return result
else:
return DotDictionary(data[0])
else:
DotDictionary(data)
except json.decoder.JSONDecodeError:
return text
class Const:
# matches: b'ba34194ed17a8\\n59625d0a834a\\n216a1d3fb5ce\\n817469edd1ff\\n'
DECODE_RE = re.compile(r'(?i)(b\'(?P<values>.*)\')')
HOST_IMAGES: Dict[str, str] = {
"alpine": "./images/alpine/",
"ubuntu": "./images/ubuntu/",
"centos": "./images/centos/"
} | /robotframework-dockerlibrary-1.0.0.tar.gz/robotframework-dockerlibrary-1.0.0/src/Utils.py | 0.642545 | 0.175644 | Utils.py | pypi |
# robotframework-doctestlibrary
----
[Robot Framework](https://robotframework.org) DocTest library.
Simple Automated Visual Document Testing.
See **keyword documentation** for
- [Visual Document Tests](https://manykarim.github.io/robotframework-doctestlibrary/VisualTest.html)
- [Print Job Tests](https://manykarim.github.io/robotframework-doctestlibrary/PrintJobTest.html)
- [Pdf Tests (very basic)](https://manykarim.github.io/robotframework-doctestlibrary/PdfTest.html)
[](https://youtu.be/qmpwlQoJ-nE "DocTest Library presentation at robocon.io 2021")
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Compare two Images and highlight differences
Compare Images Reference.jpg Candidate.jpg
```
# Installation instructions
`pip install --upgrade robotframework-doctestlibrary`
Only Python 3.X or newer is supported. Tested with Python 3.8/3.9/3.10
In general, an installation via `pip` or `poetry` is possible.
## Install robotframework-doctestlibrary
### Installation via `pip` from PyPI (recommended)
* `pip install --upgrade robotframework-doctestlibrary`
### Installation via `pip` from GitHub
* `pip install git+https://github.com/manykarim/robotframework-doctestlibrary.git`
or
* `git clone https://github.com/manykarim/robotframework-doctestlibrary.git`
* `cd robotframework-doctestlibrary`
* `pip install -e .`
### Installation via `poetry`
* `git clone https://github.com/manykarim/robotframework-doctestlibrary.git`
* `cd robotframework-doctestlibrary`
* `poetry install`
## Install dependencies
Install Tesseract, Ghostscript, GhostPCL, ImageMagick binaries and barcode libraries (libdmtx, zbar) on your system.
<br>Hint: Since `0.2.0` Ghostscript, GhostPCL and ImageMagick are only needed for rendering `.ps` and `.pcl`files.
<br> Rendering and content parsing of `.pdf` is done via `MuPDF`
<br>In the future there might be a separate pypi package for `.pcl` and `.ps` files to get rid of those dependencies.
Linux
```bash
apt-get install imagemagick tesseract-ocr ghostscript libdmtx0b libzbar0
```
Windows
* https://github.com/UB-Mannheim/tesseract/wiki
* https://ghostscript.com/releases/gsdnld.html
* https://ghostscript.com/releases/gpcldnld.html
* https://imagemagick.org/script/download.php
## Some special instructions for Windows
### Rename executable for GhostPCL to pcl6.exe (only needed for `.pcl` support)
The executable for GhostPCL `gpcl6win64.exe` needs to be renamed to `pcl6.exe`
Otherwise it will not be possible to render .pcl files successfully for visual comparison.
### Add tesseract, ghostscript and imagemagick to system path in windows (only needed for OCR, `.pcl` and `.ps` support)
* C:\Program Files\ImageMagick-7.0.10-Q16-HDRI
* C:\Program Files\Tesseract-OCR
* C:\Program Files\gs\gs9.53.1\bin
* C:\Program Files\gs\ghostpcl-9.53.1-win64
(The folder names and versions on your system might be different)
That means: When you open the CMD shell you can run the commands
* `magick.exe`
* `tesseract.exe`
* `gswin64.exe`
* `pcl6.exe`
successfully from any folder/location
### Windows error message regarding pylibdmtx
[How to solve ImportError for pylibdmtx](https://github.com/NaturalHistoryMuseum/pylibdmtx/#windows-error-message)
If you see an ugly `ImportError` when importing `pylibdmtx` on
Windows you will most likely need the [Visual C++ Redistributable Packages for
Visual Studio 2013](https://www.microsoft.com/en-US/download/details.aspx?id=40784). Install `vcredist_x64.exe` if using 64-bit Python, `vcredist_x86.exe` if using 32-bit Python.
## ImageMagick
The library might return the error `File could not be converted by ImageMagick to OpenCV Image: <path to the file>` when comparing PDF files.
This is due to ImageMagick permissions. Verify this as follows with the `sample.pdf` in the `testdata` directory:
```bash
convert sample.pdf sample.jpg
convert-im6.q16: attempt to perform an operation not allowed by the security policy
```
Solution is to copy the `policy.xml` from the repository to the ImageMagick installation directory.
## Docker
You can also use the [docker images](https://github.com/manykarim/robotframework-doctestlibrary/packages) or create your own Docker Image
`docker build -t robotframework-doctest .`
Afterwards you can, e.g., start the container and run the povided examples like this:
* Windows
* `docker run -t -v "%cd%":/opt/test -w /opt/test robotframework-doctest robot atest/Compare.robot`
* Linux
* `docker run -t -v $PWD:/opt/test -w /opt/test robotframework-doctest robot atest/Compare.robot`
## Gitpod.io
[](https://gitpod.io/#https://github.com/manykarim/robotframework-doctestlibrary)
Try out the library using [Gitpod](https://gitpod.io/#https://github.com/manykarim/robotframework-doctestlibrary)
# Examples
Have a look at
* [Visual Comparison Tests](./atest/Compare.robot)
* [PDF Content Tests](./atest/PdfContent.robot)
* [Print Job Tests](./atest/PrintJobs.robot)
for more examples.
### Testing with [Robot Framework](https://robotframework.org)
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Compare two Images and highlight differences
Compare Images Reference.jpg Candidate.jpg
```
### Use masks/placeholders to exclude parts from visual comparison
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Compare two Images and ignore parts by using masks
Compare Images Reference.jpg Candidate.jpg placeholder_file=masks.json
Compare two PDF Docments and ignore parts by using masks
Compare Images Reference.jpg Candidate.jpg placeholder_file=masks.json
Compare two Farm images with date pattern
Compare Images Reference.jpg Candidate.jpg placeholder_file=testdata/pattern_mask.json
Compare two Farm images with area mask as list
${top_mask} Create Dictionary page=1 type=area location=top percent=10
${bottom_mask} Create Dictionary page=all type=area location=bottom percent=10
${masks} Create List ${top_mask} ${bottom_mask}
Compare Images Reference.jpg Candidate.jpg mask=${masks}
Compare two Farm images with area mask as string
Compare Images Reference.jpg Candidate.jpg mask=top:10;bottom:10
```
#### Different Mask Types to Ignore Parts When Comparing
##### Areas, Coordinates, Text Patterns
```python
[
{
"page": "all",
"name": "Date Pattern",
"type": "pattern",
"pattern": ".*[0-9]{2}-[a-zA-Z]{3}-[0-9]{4}.*"
},
{
"page": "1",
"name": "Top Border",
"type": "area",
"location": "top",
"percent": 5
},
{
"page": "1",
"name": "Left Border",
"type": "area",
"location": "left",
"percent": 5
},
{
"page": 1,
"name": "Top Rectangle",
"type": "coordinates",
"x": 0,
"y": 0,
"height": 10,
"width": 210,
"unit": "mm"
}
]
```
### Accept visual different by checking move distance or text content
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Accept if parts are moved up to 20 pixels by pure visual check
Compare Images Reference.jpg Candidate.jpg move_tolerance=20
Accept if parts are moved up to 20 pixels by reading PDF Data
Compare Images Reference.pdf Candidate.pdf move_tolerance=20 get_pdf_content=${true}
Accept differences if text content is the same via OCR
Compare Images Reference.jpg Candidate.jpg check_text_content=${true}
Accept differences if text content is the same from PDF Data
Compare Images Reference.pdf Candidate.pdf check_text_content=${true} get_pdf_content=${true}
```
#### Different options to detect moved parts/objects
```RobotFramework
*** Settings ***
Library DocTest.VisualTest movement_detection=orb
*** Test Cases ***
Accept if parts are moved up to 20 pixels by pure visual check
Compare Images Reference.jpg Candidate.jpg move_tolerance=20
```
```RobotFramework
*** Settings ***
Library DocTest.VisualTest movement_detection=template
*** Test Cases ***
Accept if parts are moved up to 20 pixels by pure visual check
Compare Images Reference.jpg Candidate.jpg move_tolerance=20
```
```RobotFramework
*** Settings ***
Library DocTest.VisualTest movement_detection=classic
*** Test Cases ***
Accept if parts are moved up to 20 pixels by pure visual check
Compare Images Reference.jpg Candidate.jpg move_tolerance=20
```
### Options for taking additional screenshots, screenshot format and render resolution
Take additional screenshots or reference and candidate file.
```RobotFramework
*** Settings ***
Library DocTest.VisualTest take_screenshots=${true} screenshot_format=png
```
Take diff screenshots to highlight differences
```RobotFramework
*** Settings ***
Library DocTest.VisualTest show_diff=${true} DPI=300
```
### Experimental usage of Open CV East Text Detection to improve OCR
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Compare two Farm images with date pattern and east detection
Compare Images Reference.jpg Candidate.jpg placeholder_file=masks.json ocr_engine=east
```
### Check content of PDF files
```RobotFramework
*** Settings ***
Library DocTest.PdfTest
*** Test Cases ***
Check if list of strings exists in PDF File
@{strings}= Create List First String Second String
PDF Should Contain Strings ${strings} Candidate.pdf
Compare two PDF Files and only check text content
Compare Pdf Documents Reference.pdf Candidate.pdf compare=text
Compare two PDF Files and only check text content and metadata
Compare Pdf Documents Reference.pdf Candidate.pdf compare=text,metadata
Compare two PDF Files and check all possible content
Compare Pdf Documents Reference.pdf Candidate.pdf
```
### Ignore Watermarks for Visual Comparisons
Store the watermark in a separate B/W image or PDF.
<br>
Watermark area needs to be filled with black color.
<br>
Watermark content will be subtracted from Visual Comparison result.
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Compare two Images and ignore jpg watermark
Compare Images Reference.jpg Candidate.jpg watermark_file=Watermark.jpg
Compare two Images and ignore pdf watermark
Compare Images Reference.pdf Candidate.pdf watermark_file=Watermark.pdf
Compare two Images and ignore watermark folder
Compare Images Reference.pdf Candidate.pdf watermark_file=${CURDIR}${/}watermarks
```
Watermarks can also be passed on Library import. This setting will apply to all Test Cases in Test Suite
```RobotFramework
*** Settings ***
Library DocTest.VisualTest watermark_file=${CURDIR}${/}watermarks
*** Test Cases ***
Compare two Images and ignore watermarks
Compare Images Reference.jpg Candidate.jpg
```
### Get Text From Documents or Images
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Get Text Content And Compare
${text} Get Text From Document Reference.pdf
List Should Contain Value ${text} Test String
```
### Get Barcodes From Documents or Images
```RobotFramework
*** Settings ***
Library DocTest.VisualTest
*** Test Cases ***
Get Text Content And Compare
${text} Get Barcodes From Document reference.jpg
List Should Contain Value ${text} 123456789
```
### Using pabot to run tests in parallel
Document Testing can be run in parallel using [pabot](https://pabot.org/).
However, you need to pass the additional arguments `--artifacts` and `--artifactsinsubfolders` to the `pabot` command, to move the screenshots to the correct subfolder.
Otherwise the screenshots will not be visible in the `log.html`
```
pabot --testlevelsplit --processes 8 --artifacts png,jpg,pdf,xml --artifactsinsubfolders /path/to/your/tests/
```
### Visual Testing of Web Applications
I experimented a bit and tried to use this library for Visual Testing of Web Applications.
Please have a look at this pilot example [here](https://github.com/manykarim/robotframework-doctestlibrary/blob/main/atest/Browser.robot)
# Development
Feel free to create issues or pull requests.
I'm always happy for any feedback.
## Core team
In order of appearance.
* Many Kasiriha
* April Wang
## Contributors
This project is community driven and becomes a reality only through the work of all the people who contribute.
| /robotframework_doctestlibrary-0.18.1.tar.gz/robotframework_doctestlibrary-0.18.1/README.md | 0.55929 | 0.863794 | README.md | pypi |
from .kwgenerator import DoesIsListener
class DoesIsLibrary(DoesIsListener):
"""
DoesIsLibrary for Robot Framework :)
RobotFramework library which extends imported libraries with *Does* and *Is* keywords.
RobotFramework libraries provides assertion keywords, usually named like *Something Should Exist*, *Another Thing Should Be Eqal*, *Yet Another Should Not Exist*, *Some Should Not Be Equal*. This library extracts such keywords from libraries imported in suite, and extends libraries from where those keywords come from with *Does* and *Is* keywords, like:
Orginal keyword - Newly created keyword
*Something Should Exist* - *Does Somethin Exist*
*Another Thing Should Be Eqal* - *Is Another Thing Equal*
*Yet Another Should Not Exist* - *Does Yest Another Not Exist*
*Some Should Not Be Equal* - *Is Some Not Equal*
Orginal Keywords PASS or FAIL depending of assertion is met or not, while newly created keyword returns `True` or `False`
Use Case is shown in follwing example:
Usage
-----
WithoutLibrary.robot
| ***** Settings *****
| Library SeleniumLibrary
|
| ***** Test Cases *****
| NoLibrary
| ${are_equal}= Run Keyword And Return Status Should Be Equal As Numbers 10 10
| Run Keyword If '${are_equal}'=='True' Log Equal!
| Open Browser http://example.local gc
| ${is_element_visible}= Run Keyword And Return Status Element Should Be Visible id=locator
| Run Keyword If '${is_element_visible}'=='True' Click Element id=locator
WithLibrary.robot
| ***** Settings *****
| Library SeleniumLibrary
| Library DoesIsLibrary
|
| ***** Test Cases *****
| WithLibrary
| ${are_equal}= Is Equal As Numbers 10 10
| Run Keyword If '${are_equal}'=='True' Log Equal!
| Open Browser http://example.local gc
| ${is_element_visible}= Is Element Visible id=locator
| Run Keyword If '${is_element_visible}'=='True' Click Element id=locator
Library Does not provide almost any "static" keywords, except `List Is Keywords` and `List Does keywords` which log names of newly dynamically generated keywords in RF log.html file.
How it works and limitations
----------------------------
Library is looking for imported libraries from ***Settings*** section during start suite phase and then looks for keyword having 'should' in keyword name. Then new keywords are created for each imported library respectively.
As (for now) new keyword generation is triggerd in suite setup phase, new keywords *will not be generated* for libraries imported with RF built in keyword `Import Library`
Example list of generated keywords below:
| BuiltIn Does Contain Should Contain ['container', 'item', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Contain Any Should Contain Any ['container', '*items', '**configuration']
| BuiltIn Does Contain X Times Should Contain X Times ['container', 'item', 'count', 'msg=None', 'ignore_case=False']
| BuiltIn Does End With Should End With ['str1', 'str2', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Keyword Exist Keyword Should Exist ['name', 'msg=None']
| BuiltIn Does Match Should Match ['string', 'pattern', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Match Regexp Should Match Regexp ['string', 'pattern', 'msg=None', 'values=True']
| BuiltIn Does Not Contain Should Not Contain ['container', 'item', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Not Contain Any Should Not Contain Any ['container', '*items', '**configuration']
| BuiltIn Does Not End With Should Not End With ['str1', 'str2', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Not Match Should Not Match ['string', 'pattern', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Not Match Regexp Should Not Match Regexp ['string', 'pattern', 'msg=None', 'values=True']
| BuiltIn Does Not Start With Should Not Start With ['str1', 'str2', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Start With Should Start With ['str1', 'str2', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Does Variable Exist Variable Should Exist ['name', 'msg=None']
| BuiltIn Does Variable Not Exist Variable Should Not Exist ['name', 'msg=None']
| BuiltIn Is Empty Should Be Empty ['item', 'msg=None']
| BuiltIn Is Equal Should Be Equal ['first', 'second', 'msg=None', 'values=True', 'ignore_case=False', 'formatter=str']
| BuiltIn Is Equal As Integers Should Be Equal As Integers ['first', 'second', 'msg=None', 'values=True', 'base=None']
| BuiltIn Is Equal As Numbers Should Be Equal As Numbers ['first', 'second', 'msg=None', 'values=True', 'precision=6']
| BuiltIn Is Equal As Strings Should Be Equal As Strings ['first', 'second', 'msg=None', 'values=True', 'ignore_case=False', 'formatter=str']
| BuiltIn Is Length Length Should Be ['item', 'length', 'msg=None']
| BuiltIn Is Not Empty Should Not Be Empty ['item', 'msg=None']
| BuiltIn Is Not Equal Should Not Be Equal ['first', 'second', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Is Not Equal As Integers Should Not Be Equal As Integers ['first', 'second', 'msg=None', 'values=True', 'base=None']
| BuiltIn Is Not Equal As Numbers Should Not Be Equal As Numbers ['first', 'second', 'msg=None', 'values=True', 'precision=6']
| BuiltIn Is Not Equal As Strings Should Not Be Equal As Strings ['first', 'second', 'msg=None', 'values=True', 'ignore_case=False']
| BuiltIn Is Not True Should Not Be True ['condition', 'msg=None']
| BuiltIn Is True Should Be True ['condition', 'msg=None']
| OperatingSystem Does Directory Exist Directory Should Exist ['path', 'msg=None']
| OperatingSystem Does Directory Not Exist Directory Should Not Exist ['path', 'msg=None']
| OperatingSystem Does Exist Should Exist ['path', 'msg=None']
| OperatingSystem Does File Exist File Should Exist ['path', 'msg=None']
| OperatingSystem Does File Not Exist File Should Not Exist ['path', 'msg=None']
| OperatingSystem Does Not Exist Should Not Exist ['path', 'msg=None']
| OperatingSystem Is Directory Empty Directory Should Be Empty ['path', 'msg=None']
| OperatingSystem Is Directory Not Empty Directory Should Not Be Empty ['path', 'msg=None']
| OperatingSystem Is Environment Variable Not Set Environment Variable Should Not Be Set ['name', 'msg=None']
| OperatingSystem Is Environment Variable Set Environment Variable Should Be Set ['name', 'msg=None']
| OperatingSystem Is File Empty File Should Be Empty ['path', 'msg=None']
| OperatingSystem Is File Not Empty File Should Not Be Empty ['path', 'msg=None']
| Process Is Process Running Process Should Be Running ['handle=None', 'error_message=Process is not running.']
| Process Is Process Stopped Process Should Be Stopped ['handle=None', 'error_message=Process is running.']
| SSHLibrary Does Directory Exist Directory Should Exist ['path']
| SSHLibrary Does Directory Not Exist Directory Should Not Exist ['path']
| SSHLibrary Does File Exist File Should Exist ['path']
| SSHLibrary Does File Not Exist File Should Not Exist ['path']
| SeleniumLibrary Does Current Frame Contain Current Frame Should Contain ['text', 'loglevel=TRACE']
| SeleniumLibrary Does Current Frame Not Contain Current Frame Should Not Contain ['text', 'loglevel=TRACE']
| SeleniumLibrary Does Element Contain Element Should Contain ['locator', 'expected', 'message=None', 'ignore_case=False']
| SeleniumLibrary Does Element Not Contain Element Should Not Contain ['locator', 'expected', 'message=None', 'ignore_case=False']
| SeleniumLibrary Does Frame Contain Frame Should Contain ['locator', 'text', 'loglevel=TRACE']
| SeleniumLibrary Does List Have No Selections List Should Have No Selections ['locator']
| SeleniumLibrary Does Location Contain Location Should Contain ['expected', 'message=None']
| SeleniumLibrary Does Locator Match X Times Locator Should Match X Times ['locator', 'x', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Page Should Contain ['text', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Button Page Should Contain Button ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Checkbox Page Should Contain Checkbox ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Element Page Should Contain Element ['locator', 'message=None', 'loglevel=TRACE', 'limit=None']
| SeleniumLibrary Does Page Contain Image Page Should Contain Image ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Link Page Should Contain Link ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain List Page Should Contain List ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Radio Button Page Should Contain Radio Button ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Contain Textfield Page Should Contain Textfield ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Page Should Not Contain ['text', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Button Page Should Not Contain Button ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Checkbox Page Should Not Contain Checkbox ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Element Page Should Not Contain Element ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Image Page Should Not Contain Image ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Link Page Should Not Contain Link ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain List Page Should Not Contain List ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Radio Button Page Should Not Contain Radio Button ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Page Not Contain Textfield Page Should Not Contain Textfield ['locator', 'message=None', 'loglevel=TRACE']
| SeleniumLibrary Does Table Cell Contain Table Cell Should Contain ['locator', 'row', 'column', 'expected', 'loglevel=TRACE']
| SeleniumLibrary Does Table Column Contain Table Column Should Contain ['locator', 'column', 'expected', 'loglevel=TRACE']
| SeleniumLibrary Does Table Contain Table Should Contain ['locator', 'expected', 'loglevel=TRACE']
| SeleniumLibrary Does Table Footer Contain Table Footer Should Contain ['locator', 'expected', 'loglevel=TRACE']
| SeleniumLibrary Does Table Header Contain Table Header Should Contain ['locator', 'expected', 'loglevel=TRACE']
| SeleniumLibrary Does Table Row Contain Table Row Should Contain ['locator', 'row', 'expected', 'loglevel=TRACE']
| SeleniumLibrary Does Textarea Contain Textarea Should Contain ['locator', 'expected', 'message=None']
| SeleniumLibrary Does Textfield Contain Textfield Should Contain ['locator', 'expected', 'message=None']
| SeleniumLibrary Is Alert Not Present Alert Should Not Be Present ['action=ACCEPT', 'timeout=0']
| SeleniumLibrary Is Alert Present Alert Should Be Present ['text=', 'action=ACCEPT', 'timeout=None']
| SeleniumLibrary Is Checkbox Not Selected Checkbox Should Not Be Selected ['locator']
| SeleniumLibrary Is Checkbox Selected Checkbox Should Be Selected ['locator']
| SeleniumLibrary Is Element Attribute Value Element Attribute Value Should Be ['locator', 'attribute', 'expected', 'message=None']
| SeleniumLibrary Is Element Disabled Element Should Be Disabled ['locator']
| SeleniumLibrary Is Element Enabled Element Should Be Enabled ['locator']
| SeleniumLibrary Is Element Focused Element Should Be Focused ['locator']
| SeleniumLibrary Is Element Not Visible Element Should Not Be Visible ['locator', 'message=None']
| SeleniumLibrary Is Element Text Element Text Should Be ['locator', 'expected', 'message=None', 'ignore_case=False']
| SeleniumLibrary Is Element Text Not Element Text Should Not Be ['locator', 'not_expected', 'message=None', 'ignore_case=False']
| SeleniumLibrary Is Element Visible Element Should Be Visible ['locator', 'message=None']
| SeleniumLibrary Is List Selection List Selection Should Be ['locator', '*expected']
| SeleniumLibrary Is Location Location Should Be ['url', 'message=None']
| SeleniumLibrary Is Radio Button Not Selected Radio Button Should Not Be Selected ['group_name']
| SeleniumLibrary Is Radio Button Set To Radio Button Should Be Set To ['group_name', 'value']
| SeleniumLibrary Is Textarea Value Textarea Value Should Be ['locator', 'expected', 'message=None']
| SeleniumLibrary Is Textfield Value Textfield Value Should Be ['locator', 'expected', 'message=None']
| SeleniumLibrary Is Title Title Should Be ['title', 'message=None']
| String Is Byte String Should Be Byte String ['item', 'msg=None']
| String Is Lowercase Should Be Lowercase ['string', 'msg=None']
| String Is Not String Should Not Be String ['item', 'msg=None']
| String Is String Should Be String ['item', 'msg=None']
| String Is Titlecase Should Be Titlecase ['string', 'msg=None']
| String Is Unicode String Should Be Unicode String ['item', 'msg=None']
| String Is Uppercase Should Be Uppercase ['string', 'msg=None']
""" | /robotframework_doesislibrary-0.1.0-py3-none-any.whl/DoesIsLibrary/__init__.py | 0.73077 | 0.221256 | __init__.py | pypi |
# Robot Framework eggPlant Library
This [dynamic](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#different-test-library-apis)
library for [Robot Framework](https://robotframework.org/) allows calling
[eggPlant Functional](https://www.eggplantsoftware.com/eggplant-functional-downloads) scripts via XML RPC
using [eggDrive](http://docs.testplant.com/ePF/using/epf-about-eggdrive.htm).
It considers **eggPlant scripts as low level keywords** and exposes them for usage in **high level keywords and test cases in Robot Framework**.
So the scripts themselves have to be created in eggPlant, not in Robot Framework.
The eggPlant itself should be launched in eggDrive mode from outside -
see the scripts `start_eggPlant.bat` and `stop_eggPlant.bat` for example.

- [Quick Start](#quick-start)
- [eggPlant compatibility](#eggplant-compatibility)
- [Importing library](#importing-library)
- [Keywords](#keywords)
- [Library usage in VS Code](#library-usage-in-vs-code)
- [Running self-tests](#running-self-tests)
## Quick start
### System requirements
- Windows (Unix not tested yet)
- Python 3.9 or newer
- Robot Framework
#### Running tests requires additionally
- eggplant 21.1.0 or newer
- Valid eggplant license
Apart from test execution **you can use the eggPlant Library without eggplant and license**.
You can still develop test cases and keywords and run tests in the
[dryrun mode](https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#dry-run).
You'd need a file structure created by eggplant though -
to let the library discover your eggplant scripts and expose them as keywords.
### Installation
```shell
pip install robotframework-eggplantlibrary
```
### Test case example
```robotframework
*** Settings ***
Library EggplantLibrary suite=E:/eggPlantScripts/SuiteOne.suite host=http://127.0.0.1 port=5400
# Setting path to the eggplant test suite folder during library import for discovering eggplant scripts as keywords
Suite Setup Open Session
Suite Teardown Close Session
Test Setup Connect SUT Windows_10_1
*** Test Cases ***
Test One
Check Input In Notepad Hello World Some value
# Calling an eggplant script as a keyword
```
### Running tests
1. Start eggPlant in eggdrive mode - see the scripts `start_eggPlant.bat` and `stop_eggPlant.bat` for example
2. Launch tests with a `robot` command as usual
### Check out examples in the folder `tests`
## eggPlant compatibility
The Eggplant Library is compatible with eggPlant 21.1.0 and newer versions.
Older eggPlant versions may work properly sometimes, but in most cases they are incompatible
and tests might either fail or pass unexpectedly.
The library checks the current eggplant version in the `Open Session` keyword and logs a warning
in case of incompatibility.
>There is **no backwards compatibility** with older versions due to significant changes in eggplant -
new lists and properties format, changed movie and screenshot commands, named params and default values etc.
See Release Notes for eggplant [20](http://docs.eggplantsoftware.com/ePF/gettingstarted/epf-v20-release-notes.htm) und [21](http://docs.eggplantsoftware.com/ePF/gettingstarted/epf-v21-release-notes.htm) for more information.
## Importing library
Each library import is bound to a single **eggPlant test suite**, which path can be specified at library import.
The library needs a file access to the ``.suite`` folder in order to get keywords (i.e. eggPlant ``.script`` files),
their arguments and documentation.
### Import parameters
- ``suite``: path to the eggPlant ``.suite`` file.
- If eggPlant runs on a remote server, input here a path from the library host, not relative to the server! And it must be reachable.
- The default value is a first _.suite_ file in the library folder.
- You can also select another eggPlant suite for actual execution using `Open Session` and `Close Session` keywords.
- ``host``: host name or IP address of the eggPlant server running in the eggDrive mode.
- The default value is ``http://127.0.0.1``.
- You can also select another host name for actual execution using `Set eggDrive Connection` keyword.
- **The library has been tested on localhost only!**
It would be a miracle if it worked just like this with a remote eggPlant server.
- ``port``: port of the eggPlant server.
- The default value is ``5400``.
- You can also select another port for actual execution using `Set eggDrive Connection` keyword.
- ``scripts_dir``: folder inside the eggPlant Suite, where all scripts are located.
- The default value is ``Scripts``.
- Subfolders are supported.
#### Each parameter is optional and may stay unset during library import
In this case library looks for it's value in the **config file** `EggplantLib.config` in the library package dir.
If no value found in the config file (or no file exists), the default value is used.
### Config file example
```txt
suite=..\tests\keywords\eggPlantScripts\SuiteOne.suite
scripts_dir=Scripts
host=http://127.0.0.1
port=5400
```
>The config file must be named `EggplantLib.config` and located in the library package dir (e.g. ``<python_dir>\lib\site-packages\EggplantLibrary``).
There is no real XML RPC connection being established during the import, so it's not necessary
to start the eggPlant server before importing the library.
### Import examples
```robotframework
*** Settings ***
Library EggplantLibrary suite=E:/eggPlantScripts/SuiteOne.suite host=http://127.0.0.1 port=5400
Library EggplantLibrary suite=E:/eggPlantScripts/SuiteOne.suite host=http://127.0.0.1 port=5400 WITH NAME MySUT
Library EggplantLibrary
# Import without parameters needs 'EggplantLib.config' in the library package dir
```
## Keywords
- Each library import is bound to a single eggPlant test suite, which path can be specified at library import.
The library needs a file access to the eggPlant .suite file in order to get keywords (i.e. eggPlant .script files), their arguments and documentation.
- The eggPlant scripts are exposed as keywords with script names (without .script extension) using standard RF format - e.g. ``HelloWorld.script`` is exposed as ``Hello World``.
- Scripts can be structured in **subfolders**. In this case a subfolder name is added as prefix following by a dot, e.g. ``Subfolder.Myscript``.
If there are several sufolders in the structure, all of them are added as prefix, separated by a dot, e.g. ``Subfolder.SubSubfolder.Myscript``.
- The eggPlant scripts named with an underscore ('_') at the beginning are considered as **internal scripts** and would not be exposed as keywords to RF.
### Keyword documentation is supported
All comments at the top of a script file are fetched as a keyword documentation and appear in code completion and libdoc.
The [Robot Framework documentation formatting](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#documentation-formatting) is supported:
[Tags](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#keyword-tags) may be set in the last comment row [as usual](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#getting-keyword-tags) in Robot Framework keyword documentation.
```sensetalk
# This is my eggPlant sctipt documentation.
// I can use single line comments
-- with #, // and --
(* And multiline comments
Formatting supported: *bold*, _italic_, List:
- One
- Two
RobotFramewok tags are supported as well:
Tags: first, second
*)
```
### Static keywords
The library also contains several built in keywords (independent from actually available eggPlant scripts) for taking screenshots, opening and closing eggPlant sessions and connections to eggDrive and SUT.
### Creating keyword documentation
You can use _libdoc_ to build the keyword documentation file:
- Static keywords only
```shell
libdoc EggplantLibrary docs_static_keywords.html
```
- All keywords - including eggPlant scripts and static keywords as well
```shell
libdoc EggplantLibrary::../tests/keywords/eggPlantScripts/SuiteOne.suite docs_example_with_eggplant_scripts.html
```
### Keywords accept arguments
Use standard Robot Framework argument format:
```robotframework
MyScript Arg1 String argument with spaces
```
`In Robot Framework you don't need additional quotes for string arguments! Wrong: "String parameter". Right: String parameter.`
- The Library tries to convert arguments from Robot Framework data types into eggPlant data types.
These standard Robot Framework data types are tested snd should work: **int**, **float**, **bool**, **list**, **string**.
- List arguments are supported, including nested lists.
It is still possible to use old eggPlant list format as a string - the values are converted in proper lists. Example:
```robotframework
MyScriptForListParams ("first", "second", "third")
```
- [Named parameters](http://docs.eggplantsoftware.com/ePF/SenseTalk/stk-parameters-and-results.htm#named-params) and [default argument values](http://docs.eggplantsoftware.com/ePF/SenseTalk/stk-handlers.htm#default-values) are supported (support in eggplant added in 21.0.0)
- eggPlant script example:
```sensetalk
params positional_arg_no_default, arg_int:123, arg_bool:True, arg_string:"hello", arg_string_with_space:"hello world"
```
- Robot Framework usage example:
```robotframework
My keyword some value
My keyword some value arg_int=${456}
My keyword some value arg_bool=${False}
My keyword some value arg_string=Skywalker
My keyword some value arg_string_with_space=I am your father
```
### Keywords may return values
All **eggPlant scripts** are executed using [RunWithNewResult](http://docs.testplant.com/ePF/SenseTalk/stk-script-calling.htm)
and the _ReturnValue_ of the _Result_ section from the XML RPC response is returned.
> Due to the usage of the _RunWithNewResult_ mode the _ReturnValue_ is always a **string**.
The Library tries to convert it to one of standard Python data types.
These standard Robot Framework data types are tested snd should work: **int**, **float**, **bool**, **list**.
The **static (included) keywords** are different and might call an eggPlant command directly.
In this case the _Result_ section from the XML RPC response is not parsed and returned directly,
although it might be a result of a previous script.
> No data type conversion is done in this case, as the _Result_ section is able to contain different types.
All eggPlant output is saved into the RF log file.
In case of failed execution the library takes a SUT **screenshot automatically** and embeds it into the RF log file. If **video recording** was active, it would be embedded into the log file as well.
## Library usage in VS Code
The library can be used in VS Code with the
[Robot Framework Language Server extension](https://marketplace.visualstudio.com/items?itemName=robocorp.robotframework-lsp) with most of the features supported (code completion for keywords, go to keyword source, test case run directly from VS Code etc.), but it requires some **additional setup**.
By default the Language Server Plugin for VS Code does not process import parameters of the library - i.e. all necessary initialization options can't be set in a usual way.
You can solve it in one of the following ways:
1. Enable processing library import arguments in the [Language Server Plugin configuration](https://github.com/robocorp/robotframework-lsp/blob/master/robotframework-ls/docs/config.md)
```
//put this line into 'settings.json'
"robot.libraries.libdoc.needsArgs": ["EggplantLibrary"]
```
2. Alternatively you can use the [config file](#config-file-example) to specify library parameters.
- You don't have to change the existing library import with parameters in RF test suite files -
VS code processes the import, but ignores the parameters.
- Direct library import parameters in RF files always have a higher pirority than config file values.
- You may use only some of import parameters - both in RF files and in a config file.
- There is no need to reload VS Code after adding or changing eggplant script files - the Language Server extension should detect the changes and update the keyword names for code completion automatically.
Note that importing library directly as a python file via path doesn't work for VS Code -
instead you should use module name with the correct `robot.pythonpath` in the Language Server extension settings.
It shouldn't be a problem when installing library as a normal user,
but might be necessary for library development and maintenance.
## Running self-tests
Running self-tests ist especially useful during debugging or modifying the library.
You need a **running eggPlant instance** to run tests - means you need an **eggplant license**.
Most of the tests don't need a real SUT connection and use a **screenshot SUT** instead.
The only tests which require a real working RDP/VNC connection have the _real_SUT_needed_ tag.
So you can use the following command:
```
robot --exclude real_SUT_needed tests
```
**Without valid license or eggPlant instance running** you can still run the tests in the **dryrun** mode - it allows to check the library in general and the getting keywords functionality.
| /robotframework-eggplantlibrary-22.1.7.tar.gz/robotframework-eggplantlibrary-22.1.7/README.md | 0.802826 | 0.867598 | README.md | pypi |
from datetime import datetime
import os
import xmlrpc.client
import robot.api.logger as log
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
from .libcore import EggplantLibDynamicCore
from .version import VERSION, EGGPLANT_VERSION_MIN
class EggplantLibrary(EggplantLibDynamicCore):
"""
The Eggplant Library for [https://robotframework.org|Robot Framework] allows calling
[https://www.eggplantsoftware.com/eggplant-functional-downloads|eggPlant Functional] scripts via XML RPC
using [http://docs.testplant.com/ePF/using/epf-about-eggdrive.htm|eggDrive].
It considers *eggPlant scripts as low level keywords*
and exposes them for usage in *high level keywords and test cases in Robot Framework*.
So the scripts themselves have to be created in eggPlant, not in Robot Framework.
The eggPlant itself should be launched in eggDrive mode from outside.
See the [https://github.com/amochin/robotframework-eggplant|Eggplant Library homepage] for more information.
"""
ROBOT_LIBRARY_VERSION = VERSION
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
# ---------- static keywords ------------------------------
@keyword
def set_eggdrive_connection(self, host='http://127.0.0.1', port='5400'):
"""
Defines connection to running instance of eggPlant in the eggDrive mode
(XML RPC Server).
"""
uri = host + ":" + port
self.eggplant_server = xmlrpc.client.ServerProxy(uri)
@keyword
def connect_sut(self, connection_string):
"""
Opens a VNC or RDP connection with a SUT / makes it the active connection.
The `connection_string` might be a name of a saved connection or
a string of params. Examples:
| Connect SUT | Windows10 |
| Connect SUT | {serverID: "localhost", portNum: "10139", password: "secret"} |
See [http://docs.testplant.com/ePF/SenseTalk/stk-sut-information-control.htm#connect-command|eggPlant docs]
for more details.
"""
self.execute("connect {}".format(connection_string))
@keyword
def disconnect_sut(self, connection_string):
"""
Closes the specified VNC or RDP connection with a SUT.
The `connection_string` might be a name of a saved connection or a string of params.
See `Connect Sut` for more examples.
"""
self.execute("disconnect {}".format(connection_string))
@keyword
def screenshot(self, rectangle='', file_path='', highlight_rectangle='', error_if_no_sut_connection=True):
"""
Captures a SUT screen image, saves it into the specified file and logs in the Robot test log.
By default the full screen is captured, otherwise according to the specified rectangle.
The `rectangle` (optional) is a list of 2 values (top left, bottom right) in eggPlant format
indicating a rectangle to capture.
Each value might be a list of two coordinates, an image name or an image location.
If `highlight_rectangle` is provided, an additional frame is drawn on the taken screenshot.
The coordinates are passed as a string of four values: *x0, y0, x1, y1*
The `file_path` (optional) is relative to the current Robot Framework Output Dir.
If not specified, the default name is used.
Normally an error is reported if no SUT connection available for taking a screenshot.
This may be disabled using the `error_if_no_sut` parameter.
Examples:
| Screenshot | (67, 33), imagelocation("OtherCorner") |
| Screenshot | RxLocation, RxLocation + (140,100) | my_screenshot.png | 100, 150, 200, 300 |
See [http://docs.testplant.com/ePF/SenseTalk/stk-results-reporting.htm#capturescreen-command|eggPlant docs]
for details.
"""
screenshot_path = self.take_screenshot(rectangle, file_path, highlight_rectangle, error_if_no_sut_connection)
self.log_embedded_image(screenshot_path)
@keyword
def run_command(self, command):
"""
Sends the requested command to eggPlant server via XML RPC.
Allows you to call any eggPlant function or script beyond available keywords.
Returns the `Result` value of the XML RPC response, although it might be
a result of a previous script.
The `command` is a string in the eggDrive format. Quotes have to be escaped.
Examples:
| Run Command | myScript arg1, arg2 |
| Run Command | click \\"someImage\\" |
"""
result = self.execute(command)
return result
@keyword
def open_session(self, suite='', close_previously_open_session=True):
"""
Opens a session with the specified eggPlant Suite.
Has to be called before test execution.
The keyword also checks current eggpPant version and logs a warning in case of incompatibility.
The `suite` parameter (optional) is a path to the eggPlant `.suite` file which session is to open.
If not specified, the default suite is taken, which was set during library init/import.
By default if the is a previously open session, it is closed automatically.
This can be disabled using the `close_previously_open_session` parameter.
"""
s = suite
if not suite:
s = self.eggplant_suite
log.debug("Open the eggPlant session with the test suite: {}".format(s))
try:
out = self.eggplant_server.startsession(s)
log.debug(out)
except xmlrpc.client.Fault as e:
if close_previously_open_session and "BUSY: Session in progress" in e.faultString:
log.info("Old session busy - close it automatically")
self.close_session()
out = self.eggplant_server.startsession(s)
log.debug(out)
else:
raise e
except ConnectionRefusedError as e:
log.info(f"ConnectionRefusedError - {e}")
raise Exception("Failed connecting to eggPlant - check it's running in eggDrive mode")
# check eggplant version compatibility first - but only once
if not self.eggplant_version_checked:
self.execute(f'if EggplantVersion().eggplant < "{EGGPLANT_VERSION_MIN}" then LogWarning '
'!"Incompatible eggplant version detected - [[EggplantVersion().eggplant]]. '
f'Min. version required - {EGGPLANT_VERSION_MIN}. '
'See README for more information."')
self.eggplant_version_checked = True
@keyword
def close_session(self, suite=''):
"""
Closes the session with the specified eggPlant Suite.
Has to be called after test execution before opening a new session with the same eggPlant Suite.
If the requested session is not open, a warning is logged.
The `suite` parameter (optional) is a path to the eggPlant `.suite` file which session is to close.
If not specified, the last open suite is taken.
"""
s = suite
if not suite:
s = self.eggplant_suite
log.debug("Close the eggPlant session with the test suite: {}".format(s))
try:
out = self.eggplant_server.endsession(s)
log.debug(out)
except xmlrpc.client.Fault as e:
log.info("Fault code:{}. Fault string: {}".format(e.faultCode, e.faultString))
if "Can't End Session -- No Session is Active" in e.faultString:
log.warn("No open eggPlant session to close!")
else:
raise e
except ConnectionRefusedError as e:
log.info(f"ConnectionRefusedError - {e}")
raise Exception("Failed connecting to eggPlant - check it's running in eggDrive mode")
@keyword
def start_movie(self, file_path='', fps=15, compression_rate=1, highlighting=True, extra_time=5):
"""
Starts video recording into the specified file and returns the absolute path to it.
The `file_path` (optional) is relative to the current Robot Framework output dir.
If not specified, the default name is used.
The `fps` parameter defines frames per second.
The `compression_rate` adjusts the compression amount of the movie. The value range is (0, 1].
Set the rate lower to decrease the file size and video quality.
The `highlighting` determines whether the search rectangles are highlighted in the movie.
The recording continues for the `extra_time` seconds after the StopMovie command was executed.
See more in [http://docs.eggplantsoftware.com/ePF/SenseTalk/stk-results-reporting.htm#startmovie-command|eggplant docs].
"""
path = file_path
if not file_path:
path = "Movies\\Movie__{0}.mp4".format(datetime.now().strftime('%Y-%m-%d__%H_%M_%S'))
if path and os.path.isabs(path):
raise RuntimeError("Given file_path='%s' must be relative to Robot output dir" % path)
# image output file path is relative to robot framework output
full_path = os.path.join(BuiltIn().get_variable_value("${OUTPUT DIR}"), path)
if not os.path.exists(os.path.split(full_path)[0]):
os.makedirs(os.path.split(full_path)[0])
self.execute(f'StartMovie "{full_path}", framesPerSecond:{fps}, compressionRate:{compression_rate}, '
f'imageHighlighting:{highlighting}, extraTime:{extra_time}')
# and embed it into the RF log
log.info('Start video recording')
self.log_embedded_video(path)
self.current_movie_path = path # save it to embed video in the log in case of errors
return path
@keyword
def stop_movie(self, error_if_no_movie_started=False):
"""
Stops current video recording.
Normally there is no error thrown in case of no active recording,
but it can be enabled setting the `error_if_no_movie_started` parameter.
"""
log.info("Stop video recording.")
try:
self.execute('StopMovie')
if self.current_movie_path:
self.log_embedded_video(self.current_movie_path)
else:
log.info("Saving video into log failed - current recording file path empty!")
except xmlrpc.client.Fault as e:
no_movie_error = 'StopMovie is not allowed -- there is no movie being recorded'
if no_movie_error in e.faultString:
log.debug("XMLRPC execution failure! Fault code:{}. Fault string: {}".
format(e.faultCode, e.faultString))
if error_if_no_movie_started:
raise Exception(e.faultString)
else:
log.info(e.faultString)
else:
raise e
finally:
self.current_movie_path = None # reset it in any case | /robotframework-eggplantlibrary-22.1.7.tar.gz/robotframework-eggplantlibrary-22.1.7/EggplantLibrary/__init__.py | 0.753557 | 0.298798 | __init__.py | pypi |
from elasticsearch import Elasticsearch
class ElasticSearchLib(object):
"""
RobotFramework lib for querying an elasticsearch server.
It allows to run a query, count docs and manage indices (create, delete)
requires elasticsearch-py : http://elasticsearch-py.readthedocs.org/en/latest/index.html
= Table of contents =
- `Usage`
- `Keywords`
= Usage =
This library has several keywords : es search, es count, es delete index, es create index.
"""
ROBOT_LIBRARY_VERSION = '1.1'
def es_search(self,p_host,p_port,p_index,p_query):
"""
Returns a query result from elastic search
The result is the response from elasticsearch as a dictionnary.
{p_host} Elasticsearch server\n
{p_port} Port of the es server\n
{p_index} Name of the index to query\n
{p_query} Query to run\n
| ${res} = | es search | localhost | 9200 | myIndex | {"query":{"query_string":{"query": "searched value"}}} |
"""
# Es client
try:
param = [{'host':p_host,'port':int(p_port)}]
es = Elasticsearch(param)
except Exception:
raise AssertionError("Connexion error on %s:%i",p_host,int(p_port))
try:
documents = es.search(body=p_query, index=p_index)
except Exception:
raise AssertionError("Search error on %s:%i/%s for query : %s",p_host,int(p_port),p_index,p_query)
return documents
def es_count(self,p_host,p_port,p_index,p_query=None):
"""
Returns the number of documents that match a query
The result is the response from elastic search. The value is in the "count" field of the response.
{p_host} Elasticsearch server\n
{p_port} Port of the es server\n
{p_index} Name of the index to query\n
{p_query} Query to run\n
| ${res} = | es count | localhost | 9200 | myIndex | {"query":{"query_string":{"query": "searched value"}}} |
${res} contains the number of docs
"""
# Es client
try:
param = [{'host':p_host,'port':int(p_port)}]
es = Elasticsearch(param)
except Exception:
raise AssertionError("Connexion error on %s:%i",p_host,int(p_port))
try:
result = es.count(index=p_index, body=p_query)
except Exception:
raise AssertionError("Count error on %s:%i/%s for query : %s",p_host,int(p_port),p_index,p_query)
return result['count']
def es_delete_index(self,p_host,p_port,p_index):
"""
Deletes an index
{p_host} Elasticsearch server\n
{p_port} Port of the es server\n
{p_index} Name of the index to remove\n
| ${res} = | es delete index | localhost | 9200 | myIndex |
"""
# Es client
try:
param = [{'host':p_host,'port':int(p_port)}]
es = Elasticsearch(param)
except Exception:
raise AssertionError("Connexion error on %s:%i",p_host,int(p_port))
try:
es.indices.delete(index=p_index)
except Exception:
raise AssertionError("Can't delete the index %s on %s:%i",p_index,p_host,int(p_port))
def es_create_index(self,p_host,p_port,p_index,p_mapping=None):
"""
Creates an index
{p_host} Elasticsearch server\n
{p_port} Port of the es server\n
{p_index} Name of the index to create\n
{p_mapping} (optional) Dictionnary containing a custom mapping\n
| ${res} = | es create index | localhost | 9200 | myIndex |
| ${res} = | es create index | localhost | 9200 | myIndex | CustomDicMapping |
"""
# Es client
try:
param = [{'host':p_host,'port':int(p_port)}]
es = Elasticsearch(param)
except Exception:
raise AssertionError("Connexion error on %s:%i",p_host,int(p_port))
try:
es.indices.create(index=p_index,body=p_mapping)
except Exception:
raise AssertionError("Can't create the index %s on %s:%i",p_index,p_host,int(p_port))
def es_index(self,p_host,p_port,p_index,p_doctype,p_docid,p_document):
"""
Indexes a document on an elasticsearch index according to a doctype and a docid
{p_host} Elasticsearch server\n
{p_port} Port of the es server\n
{p_index} Name of the index to query\n
{p_doctype} type of the document to index\n
{p_docid} Id of the document to index\n
{p_document} Document to index\n
| es index | localhost | 9200 | myIndex | theDocType | id_457891 | {"adress":{"street":"myAdress", "city":"Wow city"}} |
"""
# Es client
try:
param = [{'host':p_host,'port':int(p_port)}]
es = Elasticsearch(param)
except Exception:
raise AssertionError("Connexion error on %s:%i",p_host,int(p_port))
try:
es.index(doc_type=p_doctype, id=p_docid, body=p_document, index=p_index)
except Exception:
raise AssertionError("Index error on %s:%i/%s for document : %s",p_host,int(p_port),p_index,p_document) | /robotframework-elasticsearch-1.1.tar.gz/robotframework-elasticsearch-1.1/ElasticSearchLib/ElasticSearchLib.py | 0.698946 | 0.405331 | ElasticSearchLib.py | pypi |
import json
from typing import Dict, Optional, Union
from elasticsearch import Elasticsearch
from robot.api import logger
from robot.utils import ConnectionCache
class ElasticsearchLibrary(object):
"""
Library for working with Elasticsearch.
Based on:
| Python client for Elasticsearch | https://pypi.python.org/pypi/elasticsearch |
== Dependencies ==
| Python client for Elasticsearch | https://pypi.python.org/pypi/elasticsearch |
| robot framework | http://robotframework.org |
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self) -> None:
""" Initialization. """
self._connection: Optional[Elasticsearch] = None
self._cache = ConnectionCache()
@property
def connection(self) -> Elasticsearch:
"""Check and return connection to Elasticsearch.
*Raises:*\n
RuntimeError: if connection to Elasticsearch hasn't been created yet.
*Returns:*\n
Current connection to Elasticsearch.
"""
if self._connection is None:
raise RuntimeError('There is no open connection to Elasticsearch.')
return self._connection
def connect_to_elasticsearch(self, host: str, port: Union[int, str], alias: str = 'default') -> int:
"""
Open connection to Elasticsearch.
*Args:*\n
_host_ - server host name;\n
_port_ - port number;\n
_alias_ - http-connection alias;\n
*Returns:*\n
Connection index.
*Example:*\n
| Connect To Elasticsearch | 192.168.1.108 | 9200 | alias=cluster1 |
"""
port = int(port)
try:
self._connection = Elasticsearch([{'host': host, 'port': port}])
self._connection.host = host
self._connection.port = port
return self._cache.register(self._connection, alias=alias)
except Exception as e:
raise Exception(f'Connect to Elasticsearch error: {e}')
def disconnect_from_elasticsearch(self) -> None:
"""
Close connection to Elasticsearch.
*Example:*\n
| Connect To Elasticsearch | 192.168.1.108 | alias=cluster1 |
| Disconnect From Elasticsearch |
"""
self._connection = None
def close_all_elasticsearch_connections(self) -> None:
"""
Close all connections to ElasticSearch.
This keyword is used to close all connections in case if there are several open connections.
After execution of this keyword connection index returned by
[#Connect To Elasticsearch|Connect To Elasticsearch] starts from 1.
*Example:*\n
| Connect To Elasticsearch | 192.168.1.108 | alias=cluster1 |
| Connect To Elasticsearch | 192.168.1.208 | alias=cluster2 |
| Close All Elasticsearch Connections |
"""
self._connection = None
self._cache.empty_cache()
def switch_elasticsearch_connection(self, index_or_alias: Union[int, str]) -> int:
"""
Switch between active connections with several clusters using their index or alias.
Alias is set in keyword [#Connect To Elasticsearch|Connect To Elasticsearch]
which also returns connection index.
*Args:*\n
_index_or_alias_ - connection index or alias;
*Returns:*\n
Previous connection index.
*Example:* (switch by alias)\n
| Connect To Elasticsearch | 192.168.1.108 | 9200 | alias=cluster1 |
| Connect To Elasticsearch | 192.168.1.208 | 9200 | alias=cluster2 |
| Switch Elasticsearch Connection | cluster1 |
*Example:* (switch by index)\n
| ${cluster1}= | Connect To Elasticsearch | 192.168.1.108 | 9200 |
| ${cluster2}= | Connect To Elasticsearch | 192.168.1.208 | 9200 |
| ${previous_index}= | Switch Elasticsearch Connection | ${cluster1} |
| Switch Elasticsearch Connection | ${previous_index} |
=>\n
${cluster1}= 1\n
${cluster2}= 2\n
${previous_index}= 2\n
"""
old_index = self._cache.current_index
self._connection = self._cache.switch(index_or_alias)
return old_index
def is_alive(self) -> bool:
"""
Check availability of Elasticsearch.
Sending GET-request of the following format: 'http://<host>:<port>/'
*Returns:*\n
bool True, if Elasticsearch is available.\n
bool False in other cases.
*Raises:*\n
Exception if sending GET-request is impossible.
*Example:*\n
| ${live}= | Is Alive |
=>\n
True
"""
try:
info = self.connection.info()
return info["cluster_name"] == "elasticsearch"
except Exception as e:
logger.debug(f"Exception {e} raised working with Elasticsearch on "
f"{self.connection.host} and {self.connection.port}") # type: ignore
raise
def es_save_data(self, es_string: str) -> None:
"""
Add data to Elasticsearch.
*Args:*\n
_es_string_ - string with data for Elasticsearch;\n
*Example:*\n
| Connect To Elasticsearch | 192.168.1.108 | 9200 |
| Es Save Data | some_string1 |
| Close All Elasticsearch Connections |
"""
json_str = json.dumps({"key": es_string})
body = json.loads(json_str)
self.connection.index(index='es', doc_type='es', id=1, body=body)
def es_retrieve_data(self) -> Dict:
"""
Get data from Elasticsearch.
*Returns:*\n
Data from Elastcisearch.
*Example:*\n
| Connect To Elasticsearch | 192.168.1.108 | 9200 |
| ${data}= | Wait Until Keyword Succeeds | 5x | 10s | Es Retrieve Data |
| Close All Elasticsearch Connections |
"""
try:
data = self.connection.get(index='es', doc_type='es', id=1)
return data
except Exception as e:
logger.debug(f"Exception {e} raised working with Elasticsearch on "
f"{self.connection.host} and {self.connection.port}") # type: ignore
raise
def es_search(self, es_string: str) -> Dict:
"""
Search for data in Elasticsearch.
*Args:*\n
_es_string_ - string for searching in Elasticsearch;\n
*Returns:*\n
Search results from Elastcisearch.
*Example:*\n
| Connect To Elasticsearch | 192.168.1.108 | 9200 |
| ${search_result}= | Es Search | some_string2 |
| Close All Elasticsearch Connections |
"""
try:
search_result = self.connection.search(
index="es",
body={"query": {"match": {'key': es_string}}})
return search_result
except Exception as e:
logger.debug(f"Exception {e} raised working with Elasticsearch on "
f"{self.connection.host} and {self.connection.port}") # type: ignore
raise | /robotframework-elasticsearchlibrary-2.0.0.tar.gz/robotframework-elasticsearchlibrary-2.0.0/src/ElasticsearchLibrary.py | 0.858807 | 0.287736 | ElasticsearchLibrary.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.