robotframework-browserpom 0.6.0__tar.gz → 0.7.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/BrowserPOM/__init__.py +20 -1
  2. robotframework_browserpom-0.7.0/BrowserPOM/cli/__init__.py +5 -0
  3. robotframework_browserpom-0.7.0/BrowserPOM/cli/__main__.py +6 -0
  4. robotframework_browserpom-0.7.0/BrowserPOM/cli/cli.py +68 -0
  5. robotframework_browserpom-0.7.0/BrowserPOM/cli/config.py +63 -0
  6. robotframework_browserpom-0.7.0/BrowserPOM/cli/exceptions.py +13 -0
  7. robotframework_browserpom-0.7.0/BrowserPOM/cli/formatting.py +98 -0
  8. robotframework_browserpom-0.7.0/BrowserPOM/cli/scanner.py +616 -0
  9. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/BrowserPOM/pageobject.py +3 -3
  10. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/BrowserPOM/uiobject.py +1 -1
  11. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/PKG-INFO +2 -2
  12. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/pyproject.toml +8 -1
  13. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/.gitignore +0 -0
  14. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/BrowserPOM/addons/filter_locator.js +0 -0
  15. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/BrowserPOM/decorator.py +0 -0
  16. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/BrowserPOM/pom_stubs.py +0 -0
  17. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/LICENSE +0 -0
  18. {robotframework_browserpom-0.6.0 → robotframework_browserpom-0.7.0}/readme.md +0 -0
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, cast
7
7
 
8
8
  from Browser import Browser
9
9
  from Browser.utils import ScreenshotFileTypes, ScreenshotReturnType
10
+ from robot.api import logger
10
11
  from robot.api.deco import keyword
11
12
  from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
12
13
 
@@ -135,7 +136,25 @@ class BrowserPOM(Browser):
135
136
  kwargs["jsextension"] = jsextensions
136
137
 
137
138
  browser_init = cast("Callable[..., None]", super().__init__)
138
- browser_init(*args, **kwargs)
139
+ try:
140
+ browser_init(*args, **kwargs)
141
+ except Exception as error: # noqa: BLE001
142
+ # Passing a ``jsextension`` makes BrowserLibrary eagerly start the
143
+ # Playwright Node.js process during ``__init__`` (to register the JS
144
+ # keywords). When BrowserPOM is only imported so another library or
145
+ # tool can gather its keywords, that spawn can fail in fork-unsafe
146
+ # contexts (e.g. grpc already initialised, pabot,
147
+ # pytest_robotframework), raising errors such as
148
+ # "TypeError: 'NoneType' object is not callable" from subprocess.
149
+ # Fall back to a plain init so keyword gathering does not crash the
150
+ # importing library.
151
+ logger.warn(
152
+ "BrowserPOM: failed to load the 'filter_locator' jsextension "
153
+ f"during import ({error}). The library was initialised without "
154
+ "it so keyword gathering can continue.",
155
+ )
156
+ kwargs["jsextension"] = [extension for extension in jsextensions if extension != str(addon_path)] or None
157
+ browser_init(*args, **kwargs)
139
158
 
140
159
  @keyword
141
160
  def take_screenshot(self, *args, **kwargs): # noqa:ANN002,ANN003,ANN201
@@ -0,0 +1,5 @@
1
+ """browserpom CLI — entry point package."""
2
+
3
+ from BrowserPOM.cli.cli import main
4
+
5
+ __all__ = ["main"]
@@ -0,0 +1,6 @@
1
+ """Allow `python -m BrowserPOM.cli` invocation."""
2
+
3
+ from BrowserPOM.cli.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,68 @@
1
+ """Entry point for the `browserpom` command-line tool."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from BrowserPOM.cli.config import load
10
+ from BrowserPOM.cli.exceptions import BrowserPOMCLIError
11
+ from BrowserPOM.cli.formatting import format_pageobject, format_uiobject
12
+ from BrowserPOM.cli.scanner import Scanner
13
+
14
+
15
+ def cmd_discover_pages(_args: argparse.Namespace) -> None:
16
+ """Run `browserpom discover pages`, raising domain exceptions on failure."""
17
+ config = load()
18
+ scanner = Scanner(Path.cwd(), config.paths)
19
+ pages = scanner.scan_pages()
20
+ blocks = [format_pageobject(page, Path.cwd()) for page in pages]
21
+ if blocks:
22
+ print("\n\n".join(blocks)) # noqa: T201
23
+
24
+
25
+ def cmd_discover_objects(_args: argparse.Namespace) -> None:
26
+ """Run `browserpom discover objects`, raising domain exceptions on failure."""
27
+ config = load()
28
+ scanner = Scanner(Path.cwd(), config.paths)
29
+ classes = scanner.scan()
30
+ blocks = [format_uiobject(cls, Path.cwd()) for cls in classes]
31
+ print("\n\n".join(blocks)) # noqa: T201
32
+
33
+
34
+ def build_parser() -> argparse.ArgumentParser:
35
+ """Build and return the top-level argument parser."""
36
+ parser = argparse.ArgumentParser(
37
+ prog="browserpom",
38
+ description="CLI tools for robotframework-browserpom.",
39
+ )
40
+ sub = parser.add_subparsers(dest="command")
41
+
42
+ discover = sub.add_parser("discover", help="Discover PageObjects and UIObjects.")
43
+ discover_sub = discover.add_subparsers(dest="subcommand")
44
+
45
+ discover_sub.add_parser("pages", help="List all PageObjects.")
46
+ discover_sub.add_parser("objects", help="List all UIObject subclasses.")
47
+
48
+ return parser
49
+
50
+
51
+ def main(argv: list[str] | None = None) -> None:
52
+ """Entry point for the `browserpom` console script."""
53
+ parser = build_parser()
54
+ args = parser.parse_args(argv)
55
+
56
+ try:
57
+ if args.command == "discover":
58
+ if args.subcommand == "pages":
59
+ cmd_discover_pages(args)
60
+ elif args.subcommand == "objects":
61
+ cmd_discover_objects(args)
62
+ else:
63
+ parser.parse_args(["discover", "--help"])
64
+ else:
65
+ parser.print_help()
66
+ except BrowserPOMCLIError as exc:
67
+ print(str(exc), file=sys.stderr) # noqa: T201
68
+ raise SystemExit(1) from exc
@@ -0,0 +1,63 @@
1
+ """Read and validate [tool.browserpom.discover] from pyproject.toml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from BrowserPOM.cli.exceptions import ConfigError
10
+
11
+
12
+ @dataclass
13
+ class DiscoverConfig:
14
+ """Validated contents of [tool.browserpom.discover]."""
15
+
16
+ paths: list[str] = field(default_factory=list)
17
+
18
+
19
+ def load(project_root: Path | None = None) -> DiscoverConfig:
20
+ """Load and validate [tool.browserpom.discover] from pyproject.toml.
21
+
22
+ Args:
23
+ project_root: Directory containing pyproject.toml. Defaults to cwd.
24
+
25
+ Returns:
26
+ A DiscoverConfig with the configured paths.
27
+
28
+ Raises:
29
+ ConfigError: If pyproject.toml is missing, the [tool.browserpom.discover]
30
+ section is absent, types are wrong, or no scan targets are configured.
31
+
32
+ """
33
+ root = project_root or Path.cwd()
34
+ pyproject = root / "pyproject.toml"
35
+
36
+ if not pyproject.exists():
37
+ raise ConfigError(
38
+ "No pyproject.toml found. Create one and add a [tool.browserpom.discover] section with 'paths'.",
39
+ )
40
+
41
+ with pyproject.open("rb") as fh:
42
+ data = tomllib.load(fh)
43
+
44
+ discover = data.get("tool", {}).get("browserpom", {}).get("discover")
45
+
46
+ if discover is None:
47
+ raise ConfigError(
48
+ "No [tool.browserpom.discover] section found in pyproject.toml. Add 'paths' to configure discovery.",
49
+ )
50
+
51
+ paths = discover.get("paths", [])
52
+
53
+ if not isinstance(paths, list):
54
+ raise ConfigError(
55
+ f"[tool.browserpom.discover] 'paths' must be a list, got {type(paths).__name__!r}",
56
+ )
57
+
58
+ if not paths:
59
+ raise ConfigError(
60
+ "[tool.browserpom.discover] requires at least one entry in 'paths'.",
61
+ )
62
+
63
+ return DiscoverConfig(paths=paths)
@@ -0,0 +1,13 @@
1
+ """Domain-specific exceptions for the browserpom CLI."""
2
+
3
+
4
+ class BrowserPOMCLIError(Exception):
5
+ """Base class for all browserpom CLI errors."""
6
+
7
+
8
+ class ConfigError(BrowserPOMCLIError):
9
+ """Raised when [tool.browserpom.discover] configuration is invalid."""
10
+
11
+
12
+ class DiscoveryError(BrowserPOMCLIError):
13
+ """Raised when AST-based discovery of PageObjects or UIObjects fails."""
@@ -0,0 +1,98 @@
1
+ """Text rendering for `browserpom discover` output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from pathlib import Path
9
+
10
+ from BrowserPOM.cli.scanner import ChildUIObject, PageObjectClass, UIObjectClass
11
+
12
+
13
+ def _rel_path(project_root: Path, file_path: Path) -> str:
14
+ try:
15
+ return str(file_path.relative_to(project_root))
16
+ except ValueError:
17
+ return str(file_path)
18
+
19
+
20
+ def _format_child(child: "ChildUIObject", indent: int = 2) -> str:
21
+ spacer = " " * indent
22
+ locator_str = f'"{child.locator}"' if child.locator else ""
23
+ lines = [f"{spacer}{child.name}: {child.type_name}({locator_str})"]
24
+ lines.extend(_format_child(grandchild, indent + 2) for grandchild in child.children)
25
+ return "\n".join(lines)
26
+
27
+
28
+ def _format_child_pages(child: "ChildUIObject", indent: int = 2) -> str:
29
+ """Format a UIObject child for the pages command (no locators, no properties)."""
30
+ spacer = " " * indent
31
+ lines = [f"{spacer}{child.name}: {child.type_name}"]
32
+ lines.extend(_format_child_pages(grandchild, indent + 2) for grandchild in child.children)
33
+ return "\n".join(lines)
34
+
35
+
36
+ def _format_section(lines: list[str], name: str, indent: int, items: list[str]) -> None:
37
+ """Append a section to `lines`: a header + indented items, or `Name: None` when empty."""
38
+ prefix = " " * indent
39
+ if items:
40
+ lines.append(f"{prefix}{name}:")
41
+ lines.extend(items)
42
+ else:
43
+ lines.append(f"{prefix}{name}: None")
44
+
45
+
46
+ def format_pageobject(cls: "PageObjectClass", project_root: Path) -> str:
47
+ """Format a PageObjectClass for the pages command output."""
48
+ lines: list[str] = [f"{cls.name}: {_rel_path(project_root, cls.file_path)}"]
49
+ if cls.page_url is not None:
50
+ lines.append(f" PAGE_URL: {cls.page_url}")
51
+
52
+ _format_section(
53
+ lines,
54
+ "Children",
55
+ indent=2,
56
+ items=[_format_child_pages(child, indent=4) for child in cls.children],
57
+ )
58
+ _format_section(
59
+ lines,
60
+ "Properties",
61
+ indent=2,
62
+ items=[f" {prop.name}" for prop in cls.properties],
63
+ )
64
+
65
+ keyword_lines = []
66
+ for kw in cls.keywords:
67
+ params = ", ".join(kw.params)
68
+ suffix = f" -> {kw.return_type}" if kw.return_type else ""
69
+ keyword_lines.append(f" {kw.robot_name}({params}){suffix}")
70
+ _format_section(lines, "Keywords", indent=2, items=keyword_lines)
71
+
72
+ return "\n".join(lines)
73
+
74
+
75
+ def format_uiobject(cls: "UIObjectClass", project_root: Path) -> str:
76
+ """Format a UIObjectClass for the objects command output."""
77
+ lines: list[str] = [f"{cls.name}: {_rel_path(project_root, cls.file_path)}"]
78
+
79
+ _format_section(
80
+ lines,
81
+ "Children",
82
+ indent=2,
83
+ items=[_format_child(child, indent=4) for child in cls.children],
84
+ )
85
+ _format_section(
86
+ lines,
87
+ "Properties",
88
+ indent=2,
89
+ items=[f" {prop.name}" for prop in cls.properties],
90
+ )
91
+
92
+ method_lines = []
93
+ for method in cls.methods:
94
+ params = ", ".join(method.params)
95
+ method_lines.append(f" {method.name}({params})")
96
+ _format_section(lines, "Methods", indent=2, items=method_lines)
97
+
98
+ return "\n".join(lines)
@@ -0,0 +1,616 @@
1
+ """AST-based discovery of UIObject subclasses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path # noqa: TC003
8
+ from typing import TYPE_CHECKING
9
+
10
+ from BrowserPOM.cli.exceptions import DiscoveryError
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Iterator, Sequence
14
+
15
+
16
+ @dataclass
17
+ class MethodInfo:
18
+ """A directly-defined method on a UIObject subclass."""
19
+
20
+ name: str
21
+ params: list[str]
22
+
23
+
24
+ @dataclass
25
+ class PropertyInfo:
26
+ """A directly-defined @property on a UIObject subclass."""
27
+
28
+ name: str
29
+
30
+
31
+ @dataclass
32
+ class ChildUIObject:
33
+ """A child UIObject attribute with its locator and resolved children."""
34
+
35
+ name: str
36
+ type_name: str
37
+ locator: str | None
38
+ children: list[ChildUIObject] = field(default_factory=list)
39
+ properties: list[PropertyInfo] = field(default_factory=list)
40
+
41
+
42
+ @dataclass
43
+ class KeywordInfo:
44
+ """A @keyword method on a PageObject."""
45
+
46
+ name: str
47
+ robot_name: str
48
+ params: list[str]
49
+ return_type: str | None
50
+
51
+
52
+ @dataclass
53
+ class PageObjectClass:
54
+ """Discovered information about a PageObject subclass."""
55
+
56
+ name: str
57
+ module_path: str
58
+ file_path: Path
59
+ page_url: str | None = None
60
+ children: list[ChildUIObject] = field(default_factory=list)
61
+ properties: list[PropertyInfo] = field(default_factory=list)
62
+ keywords: list[KeywordInfo] = field(default_factory=list)
63
+
64
+
65
+ @dataclass
66
+ class UIObjectClass:
67
+ """Discovered information about a UIObject subclass."""
68
+
69
+ name: str
70
+ module_path: str
71
+ file_path: Path
72
+ children: list[ChildUIObject] = field(default_factory=list)
73
+ properties: list[PropertyInfo] = field(default_factory=list)
74
+ methods: list[MethodInfo] = field(default_factory=list)
75
+
76
+
77
+ class _ModuleImports:
78
+ """Tracks import mappings for a single module."""
79
+
80
+ def __init__(self) -> None:
81
+ # local_name -> (module_path, imported_name)
82
+ self._mappings: dict[str, tuple[str, str]] = {}
83
+
84
+ def add(self, local_name: str, module_path: str, imported_name: str) -> None:
85
+ self._mappings[local_name] = (module_path, imported_name)
86
+
87
+ def resolve(self, local_name: str) -> tuple[str | None, str]:
88
+ """Return (module_path, imported_name) for a local name, or (None, local_name)."""
89
+ if local_name in self._mappings:
90
+ return self._mappings[local_name]
91
+ return (None, local_name)
92
+
93
+
94
+ @dataclass
95
+ class _RawClass:
96
+ """Raw parsed information about a class, before UIObject filtering."""
97
+
98
+ name: str
99
+ module_name: str
100
+ file_path: Path
101
+ bases: list[str]
102
+ body: list[ast.stmt]
103
+ init_body: list[ast.stmt]
104
+ imports: _ModuleImports
105
+
106
+ @property
107
+ def full_name(self) -> str:
108
+ """The fully-qualified `module.ClassName` name used as a registry/index key."""
109
+ return f"{self.module_name}.{self.name}"
110
+
111
+
112
+ def _extract_locator(call: ast.Call) -> str | None:
113
+ """Extract the locator string from a UIObject constructor call.
114
+
115
+ Checks the first positional string argument, then a keyword argument
116
+ named ``locator``.
117
+ """
118
+ for arg in call.args:
119
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
120
+ return arg.value
121
+ for kw in call.keywords:
122
+ if kw.arg == "locator" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
123
+ return kw.value.value
124
+ return None
125
+
126
+
127
+ def _has_decorator(func: ast.FunctionDef | ast.AsyncFunctionDef, name: str) -> bool:
128
+ for dec in func.decorator_list:
129
+ # bare: @keyword
130
+ if isinstance(dec, ast.Name) and dec.id == name:
131
+ return True
132
+ # dotted: @deco.keyword
133
+ if isinstance(dec, ast.Attribute) and dec.attr == name:
134
+ return True
135
+ # called: @keyword("Custom Name") or @deco.keyword(...)
136
+ if isinstance(dec, ast.Call):
137
+ inner = dec.func
138
+ if isinstance(inner, ast.Name) and inner.id == name:
139
+ return True
140
+ if isinstance(inner, ast.Attribute) and inner.attr == name:
141
+ return True
142
+ return False
143
+
144
+
145
+ def _is_property(func: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
146
+ return _has_decorator(func, "property")
147
+
148
+
149
+ def _is_keyword(func: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
150
+ return _has_decorator(func, "keyword")
151
+
152
+
153
+ def _method_params(func: ast.FunctionDef | ast.AsyncFunctionDef) -> list[str]:
154
+ """Return parameter names excluding self/cls."""
155
+ params = [arg.arg for arg in func.args.posonlyargs if arg.arg not in {"self", "cls"}]
156
+ params.extend(arg.arg for arg in func.args.args if arg.arg not in {"self", "cls"})
157
+ params.extend(arg.arg for arg in func.args.kwonlyargs)
158
+ if func.args.vararg:
159
+ params.append(f"*{func.args.vararg.arg}")
160
+ if func.args.kwarg:
161
+ params.append(f"**{func.args.kwarg.arg}")
162
+ return params
163
+
164
+
165
+ def _is_private(name: str) -> bool:
166
+ return name.startswith("_")
167
+
168
+
169
+ def _is_dunder(name: str) -> bool:
170
+ return name.startswith("__") and name.endswith("__")
171
+
172
+
173
+ def _class_name(node: ast.expr) -> str | None:
174
+ if isinstance(node, ast.Name):
175
+ return node.id
176
+ if isinstance(node, ast.Attribute):
177
+ parts = []
178
+ current: ast.expr = node
179
+ while isinstance(current, ast.Attribute):
180
+ parts.append(current.attr)
181
+ current = current.value
182
+ if isinstance(current, ast.Name):
183
+ parts.append(current.id)
184
+ return ".".join(reversed(parts))
185
+ return None
186
+
187
+
188
+ def _build_module_name(file_path: Path, root: Path) -> str:
189
+ """Build a dotted module name from a file path relative to a root."""
190
+ try:
191
+ rel = file_path.relative_to(root)
192
+ except ValueError:
193
+ rel = file_path
194
+ parts = list(rel.with_suffix("").parts)
195
+ # Strip leading empty part from absolute-path fallback
196
+ if parts and parts[0] == "/":
197
+ parts = parts[1:]
198
+ # `__init__.py` modules are addressed by their package name, not
199
+ # `<package>.__init__` — strip the trailing component so relative-import
200
+ # resolution (which reasons about a module's *package*) lines up with
201
+ # how classes defined in `__init__.py` are keyed.
202
+ if parts and parts[-1] == "__init__":
203
+ parts = parts[:-1]
204
+ return ".".join(parts)
205
+
206
+
207
+ def _package_name(module_name: str, file_path: Path) -> str:
208
+ """Return the dotted package name that `module_name` belongs to.
209
+
210
+ For a package's `__init__.py`, the module *is* the package. For any
211
+ other module, the package is everything but the last component.
212
+ """
213
+ if not module_name:
214
+ return ""
215
+ if file_path.name == "__init__.py":
216
+ return module_name
217
+ if "." in module_name:
218
+ return module_name.rsplit(".", 1)[0]
219
+ return ""
220
+
221
+
222
+ def _resolve_relative_module(module: str, level: int, package: str) -> str:
223
+ """Resolve a relative import's absolute module path (mirrors importlib._bootstrap._resolve_name)."""
224
+ bits = package.rsplit(".", level - 1)
225
+ base = bits[0] if bits else ""
226
+ if module:
227
+ return f"{base}.{module}" if base else module
228
+ return base
229
+
230
+
231
+ def _child_from_call(name: str, call: ast.Call) -> ChildUIObject | None:
232
+ """Build a ChildUIObject from an attribute name and a constructor Call node.
233
+
234
+ Returns ``None`` when the callable cannot be resolved to a name.
235
+ """
236
+ type_name = _class_name(call.func)
237
+ if type_name is None:
238
+ return None
239
+ return ChildUIObject(name=name, type_name=type_name, locator=_extract_locator(call))
240
+
241
+
242
+ def _extract_class_level_children(body: list[ast.stmt]) -> list[ChildUIObject]:
243
+ """Extract children from class-level `name = SomeType(...)` assignments."""
244
+ children: list[ChildUIObject] = []
245
+ for item in body:
246
+ if not isinstance(item, ast.Assign) or not isinstance(item.value, ast.Call):
247
+ continue
248
+ for target in item.targets:
249
+ if isinstance(target, ast.Name) and not _is_private(target.id):
250
+ child = _child_from_call(target.id, item.value)
251
+ if child is not None:
252
+ children.append(child)
253
+ return children
254
+
255
+
256
+ def _extract_init_children(init_body: list[ast.stmt]) -> list[ChildUIObject]:
257
+ """Extract children from `self.name = SomeType(...)` assignments in `__init__`."""
258
+ children: list[ChildUIObject] = []
259
+ for stmt in init_body:
260
+ if not isinstance(stmt, ast.Assign) or not isinstance(stmt.value, ast.Call):
261
+ continue
262
+ for target in stmt.targets:
263
+ if (
264
+ isinstance(target, ast.Attribute)
265
+ and isinstance(target.value, ast.Name)
266
+ and target.value.id == "self"
267
+ and not _is_private(target.attr)
268
+ ):
269
+ child = _child_from_call(target.attr, stmt.value)
270
+ if child is not None:
271
+ children.append(child)
272
+ return children
273
+
274
+
275
+ def _extract_properties(body: list[ast.stmt]) -> list[PropertyInfo]:
276
+ """Extract `@property` members from a class body, excluding private/dunder names."""
277
+ return [
278
+ PropertyInfo(name=item.name)
279
+ for item in body
280
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))
281
+ and _is_property(item)
282
+ and not _is_private(item.name)
283
+ and not _is_dunder(item.name)
284
+ ]
285
+
286
+
287
+ def _resolve_base_name(base_name: str, imports: _ModuleImports) -> str:
288
+ """Resolve a local base class name to its fully qualified name."""
289
+ mod, name = imports.resolve(base_name)
290
+ if mod:
291
+ return f"{mod}.{name}"
292
+ return name
293
+
294
+
295
+ def _parse_module(file_path: Path, root: Path) -> list[_RawClass] | None: # noqa: C901
296
+ """Parse a single Python file and return raw class definitions."""
297
+ module_name = _build_module_name(file_path, root)
298
+ package_name = _package_name(module_name, file_path)
299
+ imports = _ModuleImports()
300
+
301
+ try:
302
+ source = file_path.read_text(encoding="utf-8")
303
+ except OSError:
304
+ return None
305
+
306
+ try:
307
+ tree = ast.parse(source)
308
+ except SyntaxError:
309
+ return None
310
+
311
+ for node in ast.walk(tree):
312
+ if isinstance(node, ast.Import):
313
+ for alias in node.names:
314
+ local = alias.asname or alias.name
315
+ imports.add(local, alias.name, alias.name)
316
+ elif isinstance(node, ast.ImportFrom):
317
+ module = node.module or ""
318
+ if node.level:
319
+ module = _resolve_relative_module(module, node.level, package_name)
320
+ for alias in node.names:
321
+ local = alias.asname or alias.name
322
+ imports.add(local, module, alias.name)
323
+
324
+ raw_classes: list[_RawClass] = []
325
+ for node in ast.walk(tree):
326
+ if isinstance(node, ast.ClassDef):
327
+ bases = [bname for base in node.bases if (bname := _class_name(base)) is not None]
328
+
329
+ init_body: list[ast.stmt] = []
330
+ for item in node.body:
331
+ if isinstance(item, ast.FunctionDef) and item.name == "__init__":
332
+ init_body = item.body
333
+
334
+ raw_classes.append(
335
+ _RawClass(
336
+ name=node.name,
337
+ module_name=module_name,
338
+ file_path=file_path,
339
+ bases=bases,
340
+ body=node.body,
341
+ init_body=init_body,
342
+ imports=imports,
343
+ ),
344
+ )
345
+
346
+ return raw_classes
347
+
348
+
349
+ def _to_robot_title_case(name: str) -> str:
350
+ """Convert a Python snake_case name to Robot Framework Title Case."""
351
+ return " ".join(word.capitalize() for word in name.split("_"))
352
+
353
+
354
+ def _extract_return_type(func: ast.FunctionDef | ast.AsyncFunctionDef) -> str | None:
355
+ """Extract the return type annotation as a string, or None if absent or None-typed."""
356
+ if func.returns is None:
357
+ return None
358
+ unparsed = ast.unparse(func.returns)
359
+ if unparsed in {"None", "type[None]"}:
360
+ return None
361
+ return unparsed
362
+
363
+
364
+ def _extract_page_url(body: list[ast.stmt]) -> str | None:
365
+ """Extract the PAGE_URL string constant from a class body, if present."""
366
+ for item in body:
367
+ if isinstance(item, ast.Assign):
368
+ for target in item.targets:
369
+ if (
370
+ isinstance(target, ast.Name)
371
+ and target.id == "PAGE_URL"
372
+ and isinstance(item.value, ast.Constant)
373
+ and isinstance(item.value.value, str)
374
+ ):
375
+ return item.value.value
376
+ elif (
377
+ isinstance(item, ast.AnnAssign)
378
+ and isinstance(item.target, ast.Name)
379
+ and item.target.id == "PAGE_URL"
380
+ and item.value is not None
381
+ and isinstance(item.value, ast.Constant)
382
+ and isinstance(item.value.value, str)
383
+ ):
384
+ return item.value.value
385
+ return None
386
+
387
+
388
+ class Scanner:
389
+ """Scans configured paths for UIObject subclasses."""
390
+
391
+ def __init__(self, project_root: Path, paths: Sequence[str]) -> None:
392
+ """Initialize a new Scanner."""
393
+ self.project_root = project_root
394
+ self.paths = list(paths)
395
+ self._raw_classes: list[_RawClass] = []
396
+ self._raw_classes_by_full_name: dict[str, _RawClass] = {}
397
+ self._raw_classes_by_name_and_file: dict[tuple[str, Path], _RawClass] = {}
398
+ self._registry: dict[str, UIObjectClass] = {}
399
+
400
+ def _collect_files(self) -> Iterator[Path]:
401
+ for p in self.paths:
402
+ target = self.project_root / p
403
+ if not target.exists():
404
+ raise DiscoveryError(
405
+ f"Configured scan target does not exist on disk: {p}",
406
+ )
407
+ if target.is_file() and target.suffix == ".py":
408
+ yield target
409
+ elif target.is_dir():
410
+ yield from target.rglob("*.py")
411
+
412
+ @staticmethod
413
+ def _is_subclass_of(raw: _RawClass, base_name: str, resolved_set: set[str]) -> bool:
414
+ """Return True if `raw` directly or transitively subclasses `base_name`.
415
+
416
+ `resolved_set` holds the fully-qualified names of classes already
417
+ confirmed to be subclasses of `base_name`, so this also picks up
418
+ indirect (multi-level) inheritance as the set grows via fixed-point
419
+ iteration.
420
+ """
421
+ for base in raw.bases:
422
+ resolved = _resolve_base_name(base, raw.imports)
423
+ if resolved == base_name or resolved.endswith(f".{base_name}"):
424
+ return True
425
+ if resolved in resolved_set:
426
+ return True
427
+ # Also check short name
428
+ if resolved.split(".")[-1] == base_name:
429
+ return True
430
+ return False
431
+
432
+ def _resolve_subclasses(self, base_name: str) -> set[str]:
433
+ """Resolve the fully-qualified names of all classes subclassing `base_name`.
434
+
435
+ Repeatedly walks `self._raw_classes_by_full_name`, propagating
436
+ subclass membership until a fixed point is reached (so indirect
437
+ subclasses are also found).
438
+ """
439
+ resolved_set: set[str] = set()
440
+ changed = True
441
+ while changed:
442
+ changed = False
443
+ for full_name, raw in self._raw_classes_by_full_name.items():
444
+ if full_name in resolved_set:
445
+ continue
446
+ if raw.name == base_name:
447
+ continue
448
+ if self._is_subclass_of(raw, base_name, resolved_set):
449
+ resolved_set.add(full_name)
450
+ changed = True
451
+ return resolved_set
452
+
453
+ def _resolve_type(
454
+ self,
455
+ type_name: str,
456
+ local_imports: _ModuleImports,
457
+ ) -> UIObjectClass | None:
458
+ """Resolve a type name to its UIObjectClass definition, if any."""
459
+ mod, name = local_imports.resolve(type_name)
460
+ full_name = f"{mod}.{name}" if mod else name
461
+ # Try exact match
462
+ if full_name in self._registry:
463
+ return self._registry[full_name]
464
+ # Try just the name if unique
465
+ candidates = [cls for key, cls in self._registry.items() if key.endswith(f".{name}") or key == name]
466
+ if len(candidates) == 1:
467
+ return candidates[0]
468
+ return None
469
+
470
+ def _expand_children(
471
+ self,
472
+ children: list[ChildUIObject],
473
+ local_imports: _ModuleImports,
474
+ ) -> None:
475
+ for child in children:
476
+ resolved = self._resolve_type(child.type_name, local_imports)
477
+ if resolved is not None:
478
+ child.properties = list(resolved.properties)
479
+ child.children = [
480
+ ChildUIObject(
481
+ name=c.name,
482
+ type_name=c.type_name,
483
+ locator=c.locator,
484
+ children=[],
485
+ )
486
+ for c in resolved.children
487
+ ]
488
+ self._expand_children(
489
+ child.children,
490
+ self._get_imports_for_class(resolved),
491
+ )
492
+
493
+ def _get_imports_for_class(self, cls: UIObjectClass) -> _ModuleImports:
494
+ raw = self._raw_classes_by_name_and_file.get((cls.name, cls.file_path))
495
+ if raw is not None:
496
+ return raw.imports
497
+ return _ModuleImports()
498
+
499
+ def _build_indexes(self) -> None:
500
+ """Build lookup indexes over `self._raw_classes`, once per scan."""
501
+ self._raw_classes_by_full_name = {raw.full_name: raw for raw in self._raw_classes}
502
+ self._raw_classes_by_name_and_file = {(raw.name, raw.file_path): raw for raw in self._raw_classes}
503
+
504
+ @staticmethod
505
+ def _extract_children_and_properties(raw: _RawClass) -> tuple[list[ChildUIObject], list[PropertyInfo]]:
506
+ """Extract class-level and `__init__`-assigned children plus `@property` members.
507
+
508
+ Shared between UIObject and PageObject extraction, which each layer
509
+ their own extras (methods, or page_url/keywords) on top.
510
+ """
511
+ children = _extract_class_level_children(raw.body)
512
+ properties = _extract_properties(raw.body)
513
+ children.extend(_extract_init_children(raw.init_body))
514
+ return children, properties
515
+
516
+ @classmethod
517
+ def _extract_class_info(cls, raw: _RawClass) -> UIObjectClass:
518
+ children, properties = cls._extract_children_and_properties(raw)
519
+ uiobject = UIObjectClass(
520
+ name=raw.name,
521
+ module_path=raw.module_name,
522
+ file_path=raw.file_path,
523
+ children=children,
524
+ properties=properties,
525
+ )
526
+
527
+ for item in raw.body:
528
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and (
529
+ not _is_property(item) and not _is_keyword(item) and not _is_private(item.name) and not _is_dunder(item.name)
530
+ ):
531
+ uiobject.methods.append(
532
+ MethodInfo(name=item.name, params=_method_params(item)),
533
+ )
534
+
535
+ return uiobject
536
+
537
+ @classmethod
538
+ def _extract_page_info(cls, raw: _RawClass) -> PageObjectClass:
539
+ children, properties = cls._extract_children_and_properties(raw)
540
+ page = PageObjectClass(
541
+ name=raw.name,
542
+ module_path=raw.module_name,
543
+ file_path=raw.file_path,
544
+ page_url=_extract_page_url(raw.body),
545
+ children=children,
546
+ properties=properties,
547
+ )
548
+
549
+ for item in raw.body:
550
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and (
551
+ _is_keyword(item) and not _is_private(item.name) and not _is_dunder(item.name)
552
+ ):
553
+ page.keywords.append(
554
+ KeywordInfo(
555
+ name=item.name,
556
+ robot_name=_to_robot_title_case(item.name),
557
+ params=_method_params(item),
558
+ return_type=_extract_return_type(item),
559
+ ),
560
+ )
561
+
562
+ return page
563
+
564
+ def scan_pages(self) -> list[PageObjectClass]:
565
+ """Scan all configured targets and return PageObject subclasses alphabetically."""
566
+ # Ensure UIObject registry is built first (needed for hierarchy expansion)
567
+ if not self._raw_classes:
568
+ self.scan()
569
+
570
+ pageobject_set = self._resolve_subclasses("PageObject")
571
+
572
+ pages: list[PageObjectClass] = []
573
+ for full_name, raw in self._raw_classes_by_full_name.items():
574
+ if full_name not in pageobject_set:
575
+ continue
576
+ page = self._extract_page_info(raw)
577
+ self._expand_children(page.children, raw.imports)
578
+ pages.append(page)
579
+
580
+ pages.sort(key=lambda p: p.name)
581
+ return pages
582
+
583
+ def scan(self) -> list[UIObjectClass]:
584
+ """Scan all configured targets and return UIObject subclasses alphabetically."""
585
+ # First pass: collect raw classes from all files
586
+ for file_path in self._collect_files():
587
+ raw_list = _parse_module(file_path, self.project_root)
588
+ if raw_list is None:
589
+ continue
590
+ self._raw_classes.extend(raw_list)
591
+
592
+ # Build lookup indexes once, used throughout the remaining passes
593
+ # instead of repeated O(n) linear scans over `self._raw_classes`.
594
+ self._build_indexes()
595
+
596
+ # Second pass: determine which classes are UIObject subclasses
597
+ # Start with direct UIObject subclasses, then propagate
598
+ uiobject_set = self._resolve_subclasses("UIObject")
599
+
600
+ # Third pass: build registry from UIObject subclasses
601
+ for full_name, raw in self._raw_classes_by_full_name.items():
602
+ if full_name not in uiobject_set:
603
+ continue
604
+ cls = self._extract_class_info(raw)
605
+ self._registry[full_name] = cls
606
+
607
+ # Fourth pass: expand children recursively
608
+ for full_name, raw in self._raw_classes_by_full_name.items():
609
+ if full_name in self._registry:
610
+ cls = self._registry[full_name]
611
+ self._expand_children(cls.children, raw.imports)
612
+
613
+ # Return flat alphabetical list
614
+ result = list(self._registry.values())
615
+ result.sort(key=lambda c: c.name)
616
+ return result
@@ -62,7 +62,7 @@ class PageObject:
62
62
  heading or element on the page.
63
63
 
64
64
  """
65
- actual_title = self.browser.get_title()
65
+ actual_title = cast("str", self.browser.get_title())
66
66
  expected_title = self.PAGE_TITLE
67
67
 
68
68
  if actual_title.lower() == expected_title.lower():
@@ -101,8 +101,8 @@ class PageObject:
101
101
  Tags: selenium, page-object
102
102
 
103
103
  """
104
- url = page_root if page_root is not None else self.browser.get_url()
105
- (scheme, netloc, _, _, _, _) = urlparse(url)
104
+ url = page_root if page_root is not None else cast("str", self.browser.get_url())
105
+ scheme, netloc, _, _, _, _ = urlparse(url)
106
106
  url = f"{scheme}://{netloc}{self.PAGE_URL}"
107
107
 
108
108
  self.browser.go_to(url)
@@ -58,7 +58,7 @@ class UIObject:
58
58
  return self.filter(f"hasText: '{index}'")
59
59
  raise TypeError("Index must be an int or a str.")
60
60
 
61
- def filter(self, filter_text: str) -> UIObject:
61
+ def filter(self, filter_text: str) -> Self:
62
62
  """Filters the UI object by a given filter.
63
63
 
64
64
  See: https://playwright.dev/docs/locators#filtering-locators for more details
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: robotframework-browserpom
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: robotframework-browser library extension to create Page Objects
5
5
  Author-email: Hasan Alp Zengin <hasanalpzengin@gmail.com>
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "robotframework-browserpom"
3
- version = "0.6.0"
3
+ version = "0.7.0"
4
4
  description = "robotframework-browser library extension to create Page Objects"
5
5
  authors = [{ name = "Hasan Alp Zengin", email = "hasanalpzengin@gmail.com" }]
6
6
  requires-python = ">=3.9,<4.0"
@@ -21,10 +21,14 @@ dependencies = [
21
21
  ]
22
22
  repository = "https://github.com/hasanalpzengin/robotframework-browserpom"
23
23
 
24
+ [project.scripts]
25
+ browserpom = "BrowserPOM.cli:main"
26
+
24
27
  [dependency-groups]
25
28
  test = [
26
29
  "prek>=0.2.19",
27
30
  "pyrefly>=1.1.1",
31
+ "pytest>=8.4.2",
28
32
  "pytest_robotframework>=4.3.0,<5",
29
33
  "ruff>=0.11.0,<0.12",
30
34
  "robotframework-browser-batteries>=19.9.0",
@@ -76,3 +80,6 @@ exclude = [
76
80
  ".venv",
77
81
  "env"
78
82
  ]
83
+
84
+ [tool.pyrefly]
85
+ project-includes = ["BrowserPOM"]