From 9cbf700b95d150d96f58a86f524b0b3b7fc66129 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Thu, 20 Jun 2019 15:36:55 -0400 Subject: [PATCH 001/128] Fix small bug with repr() for basic types I was calling __repr__ with a (self) argument, but that turned out not to work. (Not sure why.) I switched to `super().__repr__()` and this works fine. --- build/generate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/generate.py b/build/generate.py index 09a8385..eaa8ba1 100644 --- a/build/generate.py +++ b/build/generate.py @@ -503,7 +503,7 @@ def generate_basic_type(type_): code += ' return cls(json)\n' code += '\n' code += ' def __repr__(self):\n' - code += " return '{}({{}})'.format({}.__repr__(self))\n".format( + code += " return '{}({{}})'.format(super().__repr__())\n".format( cdp_type, py_type) code += '\n\n' return code From 5bb1f43dccd10db4583160741bebf03d73282ce2 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Fri, 21 Jun 2019 15:01:45 -0400 Subject: [PATCH 002/128] Regenerating code. Co-authored-by: Brian Mackintosh --- cdp/accessibility/types.py | 2 +- cdp/browser/types.py | 2 +- cdp/cache_storage/types.py | 2 +- cdp/css/events.py | 5 ++- cdp/css/types.py | 2 +- cdp/database/types.py | 2 +- cdp/debugger/events.py | 90 ++++++++++++++++++++++--------------- cdp/debugger/types.py | 4 +- cdp/dom/types.py | 6 +-- cdp/dom_snapshot/types.py | 6 +-- cdp/dom_storage/types.py | 2 +- cdp/fetch/events.py | 20 +++++---- cdp/fetch/types.py | 2 +- cdp/heap_profiler/events.py | 5 ++- cdp/heap_profiler/types.py | 2 +- cdp/input/types.py | 2 +- cdp/io/types.py | 2 +- cdp/layer_tree/events.py | 5 ++- cdp/layer_tree/types.py | 6 +-- cdp/network/events.py | 80 ++++++++++++++++++++------------- cdp/network/types.py | 10 ++--- cdp/page/events.py | 10 +++-- cdp/page/types.py | 4 +- cdp/profiler/events.py | 10 +++-- cdp/runtime/events.py | 10 +++-- cdp/runtime/types.py | 14 +++--- cdp/security/events.py | 5 ++- cdp/security/types.py | 2 +- cdp/service_worker/types.py | 2 +- cdp/target/events.py | 10 +++-- cdp/target/types.py | 6 +-- cdp/tracing/events.py | 30 ++++++++----- cdp/web_audio/types.py | 2 +- 33 files changed, 209 insertions(+), 153 deletions(-) diff --git a/cdp/accessibility/types.py b/cdp/accessibility/types.py index eece334..60b56a1 100644 --- a/cdp/accessibility/types.py +++ b/cdp/accessibility/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: str) -> 'AXNodeId': return cls(json) def __repr__(self): - return 'AXNodeId({})'.format(str.__repr__(self)) + return 'AXNodeId({})'.format(super().__repr__()) class AXValueType(enum.Enum): diff --git a/cdp/browser/types.py b/cdp/browser/types.py index ad7f7e2..3ecda92 100644 --- a/cdp/browser/types.py +++ b/cdp/browser/types.py @@ -23,7 +23,7 @@ def from_json(cls, json: int) -> 'WindowID': return cls(json) def __repr__(self): - return 'WindowID({})'.format(int.__repr__(self)) + return 'WindowID({})'.format(super().__repr__()) class WindowState(enum.Enum): diff --git a/cdp/cache_storage/types.py b/cdp/cache_storage/types.py index b582886..17196c6 100644 --- a/cdp/cache_storage/types.py +++ b/cdp/cache_storage/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: str) -> 'CacheId': return cls(json) def __repr__(self): - return 'CacheId({})'.format(str.__repr__(self)) + return 'CacheId({})'.format(super().__repr__()) class CachedResponseType(enum.Enum): diff --git a/cdp/css/events.py b/cdp/css/events.py index 9b38468..cf6358a 100644 --- a/cdp/css/events.py +++ b/cdp/css/events.py @@ -24,7 +24,7 @@ class FontsUpdated: ''' #: Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded #: web font - font: FontFace + font: typing.Optional[FontFace] = None # These fields are used for internal purposes and are not part of CDP _domain = 'CSS' @@ -32,8 +32,9 @@ class FontsUpdated: @classmethod def from_json(cls, json: dict) -> 'FontsUpdated': + font = FontFace.from_json(json['font']) if 'font' in json else None return cls( - font=FontFace.from_json(json['font']), + font=font, ) diff --git a/cdp/css/types.py b/cdp/css/types.py index f1c044e..b5daefd 100644 --- a/cdp/css/types.py +++ b/cdp/css/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: str) -> 'StyleSheetId': return cls(json) def __repr__(self): - return 'StyleSheetId({})'.format(str.__repr__(self)) + return 'StyleSheetId({})'.format(super().__repr__()) class StyleSheetOrigin(enum.Enum): diff --git a/cdp/database/types.py b/cdp/database/types.py index fb9518c..dcf216a 100644 --- a/cdp/database/types.py +++ b/cdp/database/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: str) -> 'DatabaseId': return cls(json) def __repr__(self): - return 'DatabaseId({})'.format(str.__repr__(self)) + return 'DatabaseId({})'.format(super().__repr__()) @dataclass diff --git a/cdp/debugger/events.py b/cdp/debugger/events.py index 2c66ee2..a920881 100644 --- a/cdp/debugger/events.py +++ b/cdp/debugger/events.py @@ -53,19 +53,19 @@ class Paused: reason: str #: Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - data: dict + data: typing.Optional[dict] = None #: Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - hit_breakpoints: typing.List['str'] + hit_breakpoints: typing.Optional[typing.List['str']] = None #: Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - async_stack_trace: runtime.StackTrace + async_stack_trace: typing.Optional[runtime.StackTrace] = None #: Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - async_stack_trace_id: runtime.StackTraceId + async_stack_trace_id: typing.Optional[runtime.StackTraceId] = None #: Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - async_call_stack_trace_id: runtime.StackTraceId + async_call_stack_trace_id: typing.Optional[runtime.StackTraceId] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Debugger' @@ -73,14 +73,19 @@ class Paused: @classmethod def from_json(cls, json: dict) -> 'Paused': + data = dict(json['data']) if 'data' in json else None + hit_breakpoints = [str(i) for i in json['hitBreakpoints']] if 'hitBreakpoints' in json else None + async_stack_trace = runtime.StackTrace.from_json(json['asyncStackTrace']) if 'asyncStackTrace' in json else None + async_stack_trace_id = runtime.StackTraceId.from_json(json['asyncStackTraceId']) if 'asyncStackTraceId' in json else None + async_call_stack_trace_id = runtime.StackTraceId.from_json(json['asyncCallStackTraceId']) if 'asyncCallStackTraceId' in json else None return cls( call_frames=[CallFrame.from_json(i) for i in json['callFrames']], reason=str(json['reason']), - data=dict(json['data']), - hit_breakpoints=[str(i) for i in json['hitBreakpoints']], - async_stack_trace=runtime.StackTrace.from_json(json['asyncStackTrace']), - async_stack_trace_id=runtime.StackTraceId.from_json(json['asyncStackTraceId']), - async_call_stack_trace_id=runtime.StackTraceId.from_json(json['asyncCallStackTraceId']), + data=data, + hit_breakpoints=hit_breakpoints, + async_stack_trace=async_stack_trace, + async_stack_trace_id=async_stack_trace_id, + async_call_stack_trace_id=async_call_stack_trace_id, ) @@ -129,22 +134,22 @@ class ScriptFailedToParse: hash: str #: Fired when virtual machine fails to parse the script. - execution_context_aux_data: dict + execution_context_aux_data: typing.Optional[dict] = None #: Fired when virtual machine fails to parse the script. - source_map_url: str + source_map_url: typing.Optional[str] = None #: Fired when virtual machine fails to parse the script. - has_source_url: bool + has_source_url: typing.Optional[bool] = None #: Fired when virtual machine fails to parse the script. - is_module: bool + is_module: typing.Optional[bool] = None #: Fired when virtual machine fails to parse the script. - length: int + length: typing.Optional[int] = None #: Fired when virtual machine fails to parse the script. - stack_trace: runtime.StackTrace + stack_trace: typing.Optional[runtime.StackTrace] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Debugger' @@ -152,6 +157,12 @@ class ScriptFailedToParse: @classmethod def from_json(cls, json: dict) -> 'ScriptFailedToParse': + execution_context_aux_data = dict(json['executionContextAuxData']) if 'executionContextAuxData' in json else None + source_map_url = str(json['sourceMapURL']) if 'sourceMapURL' in json else None + has_source_url = bool(json['hasSourceURL']) if 'hasSourceURL' in json else None + is_module = bool(json['isModule']) if 'isModule' in json else None + length = int(json['length']) if 'length' in json else None + stack_trace = runtime.StackTrace.from_json(json['stackTrace']) if 'stackTrace' in json else None return cls( script_id=runtime.ScriptId.from_json(json['scriptId']), url=str(json['url']), @@ -161,12 +172,12 @@ def from_json(cls, json: dict) -> 'ScriptFailedToParse': end_column=int(json['endColumn']), execution_context_id=runtime.ExecutionContextId.from_json(json['executionContextId']), hash=str(json['hash']), - execution_context_aux_data=dict(json['executionContextAuxData']), - source_map_url=str(json['sourceMapURL']), - has_source_url=bool(json['hasSourceURL']), - is_module=bool(json['isModule']), - length=int(json['length']), - stack_trace=runtime.StackTrace.from_json(json['stackTrace']), + execution_context_aux_data=execution_context_aux_data, + source_map_url=source_map_url, + has_source_url=has_source_url, + is_module=is_module, + length=length, + stack_trace=stack_trace, ) @@ -210,31 +221,31 @@ class ScriptParsed: #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - execution_context_aux_data: dict + execution_context_aux_data: typing.Optional[dict] = None #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - is_live_edit: bool + is_live_edit: typing.Optional[bool] = None #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - source_map_url: str + source_map_url: typing.Optional[str] = None #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - has_source_url: bool + has_source_url: typing.Optional[bool] = None #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - is_module: bool + is_module: typing.Optional[bool] = None #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - length: int + length: typing.Optional[int] = None #: Fired when virtual machine parses script. This event is also fired for all known and uncollected #: scripts upon enabling debugger. - stack_trace: runtime.StackTrace + stack_trace: typing.Optional[runtime.StackTrace] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Debugger' @@ -242,6 +253,13 @@ class ScriptParsed: @classmethod def from_json(cls, json: dict) -> 'ScriptParsed': + execution_context_aux_data = dict(json['executionContextAuxData']) if 'executionContextAuxData' in json else None + is_live_edit = bool(json['isLiveEdit']) if 'isLiveEdit' in json else None + source_map_url = str(json['sourceMapURL']) if 'sourceMapURL' in json else None + has_source_url = bool(json['hasSourceURL']) if 'hasSourceURL' in json else None + is_module = bool(json['isModule']) if 'isModule' in json else None + length = int(json['length']) if 'length' in json else None + stack_trace = runtime.StackTrace.from_json(json['stackTrace']) if 'stackTrace' in json else None return cls( script_id=runtime.ScriptId.from_json(json['scriptId']), url=str(json['url']), @@ -251,12 +269,12 @@ def from_json(cls, json: dict) -> 'ScriptParsed': end_column=int(json['endColumn']), execution_context_id=runtime.ExecutionContextId.from_json(json['executionContextId']), hash=str(json['hash']), - execution_context_aux_data=dict(json['executionContextAuxData']), - is_live_edit=bool(json['isLiveEdit']), - source_map_url=str(json['sourceMapURL']), - has_source_url=bool(json['hasSourceURL']), - is_module=bool(json['isModule']), - length=int(json['length']), - stack_trace=runtime.StackTrace.from_json(json['stackTrace']), + execution_context_aux_data=execution_context_aux_data, + is_live_edit=is_live_edit, + source_map_url=source_map_url, + has_source_url=has_source_url, + is_module=is_module, + length=length, + stack_trace=stack_trace, ) diff --git a/cdp/debugger/types.py b/cdp/debugger/types.py index 9fb6791..ad349c8 100644 --- a/cdp/debugger/types.py +++ b/cdp/debugger/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: str) -> 'BreakpointId': return cls(json) def __repr__(self): - return 'BreakpointId({})'.format(str.__repr__(self)) + return 'BreakpointId({})'.format(super().__repr__()) class CallFrameId(str): @@ -43,7 +43,7 @@ def from_json(cls, json: str) -> 'CallFrameId': return cls(json) def __repr__(self): - return 'CallFrameId({})'.format(str.__repr__(self)) + return 'CallFrameId({})'.format(super().__repr__()) @dataclass diff --git a/cdp/dom/types.py b/cdp/dom/types.py index 05653e8..1ebba47 100644 --- a/cdp/dom/types.py +++ b/cdp/dom/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: int) -> 'NodeId': return cls(json) def __repr__(self): - return 'NodeId({})'.format(int.__repr__(self)) + return 'NodeId({})'.format(super().__repr__()) class BackendNodeId(int): @@ -44,7 +44,7 @@ def from_json(cls, json: int) -> 'BackendNodeId': return cls(json) def __repr__(self): - return 'BackendNodeId({})'.format(int.__repr__(self)) + return 'BackendNodeId({})'.format(super().__repr__()) class PseudoType(enum.Enum): @@ -103,7 +103,7 @@ def from_json(cls, json: typing.List['float']) -> 'Quad': return cls(json) def __repr__(self): - return 'Quad({})'.format(typing.List['float'].__repr__(self)) + return 'Quad({})'.format(super().__repr__()) @dataclass diff --git a/cdp/dom_snapshot/types.py b/cdp/dom_snapshot/types.py index 030235d..ba14921 100644 --- a/cdp/dom_snapshot/types.py +++ b/cdp/dom_snapshot/types.py @@ -30,7 +30,7 @@ def from_json(cls, json: int) -> 'StringIndex': return cls(json) def __repr__(self): - return 'StringIndex({})'.format(int.__repr__(self)) + return 'StringIndex({})'.format(super().__repr__()) class ArrayOfStrings(typing.List['StringIndex']): @@ -45,7 +45,7 @@ def from_json(cls, json: typing.List['StringIndex']) -> 'ArrayOfStrings': return cls(json) def __repr__(self): - return 'ArrayOfStrings({})'.format(typing.List['StringIndex'].__repr__(self)) + return 'ArrayOfStrings({})'.format(super().__repr__()) class Rectangle(typing.List['float']): @@ -57,7 +57,7 @@ def from_json(cls, json: typing.List['float']) -> 'Rectangle': return cls(json) def __repr__(self): - return 'Rectangle({})'.format(typing.List['float'].__repr__(self)) + return 'Rectangle({})'.format(super().__repr__()) @dataclass diff --git a/cdp/dom_storage/types.py b/cdp/dom_storage/types.py index c074447..dbbc6f9 100644 --- a/cdp/dom_storage/types.py +++ b/cdp/dom_storage/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: typing.List['str']) -> 'Item': return cls(json) def __repr__(self): - return 'Item({})'.format(typing.List['str'].__repr__(self)) + return 'Item({})'.format(super().__repr__()) @dataclass diff --git a/cdp/fetch/events.py b/cdp/fetch/events.py index 275d97b..dff8d82 100644 --- a/cdp/fetch/events.py +++ b/cdp/fetch/events.py @@ -67,7 +67,7 @@ class RequestPaused: #: The stage of the request can be determined by presence of responseErrorReason #: and responseStatusCode -- the request is at the response stage if either #: of these fields is present and in the request stage otherwise. - response_error_reason: network.ErrorReason + response_error_reason: typing.Optional[network.ErrorReason] = None #: Issued when the domain is enabled and the request URL matches the #: specified filter. The request is paused until the client responds @@ -75,7 +75,7 @@ class RequestPaused: #: The stage of the request can be determined by presence of responseErrorReason #: and responseStatusCode -- the request is at the response stage if either #: of these fields is present and in the request stage otherwise. - response_status_code: int + response_status_code: typing.Optional[int] = None #: Issued when the domain is enabled and the request URL matches the #: specified filter. The request is paused until the client responds @@ -83,7 +83,7 @@ class RequestPaused: #: The stage of the request can be determined by presence of responseErrorReason #: and responseStatusCode -- the request is at the response stage if either #: of these fields is present and in the request stage otherwise. - response_headers: typing.List['HeaderEntry'] + response_headers: typing.Optional[typing.List['HeaderEntry']] = None #: Issued when the domain is enabled and the request URL matches the #: specified filter. The request is paused until the client responds @@ -91,7 +91,7 @@ class RequestPaused: #: The stage of the request can be determined by presence of responseErrorReason #: and responseStatusCode -- the request is at the response stage if either #: of these fields is present and in the request stage otherwise. - network_id: RequestId + network_id: typing.Optional[RequestId] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Fetch' @@ -99,15 +99,19 @@ class RequestPaused: @classmethod def from_json(cls, json: dict) -> 'RequestPaused': + response_error_reason = network.ErrorReason.from_json(json['responseErrorReason']) if 'responseErrorReason' in json else None + response_status_code = int(json['responseStatusCode']) if 'responseStatusCode' in json else None + response_headers = [HeaderEntry.from_json(i) for i in json['responseHeaders']] if 'responseHeaders' in json else None + network_id = RequestId.from_json(json['networkId']) if 'networkId' in json else None return cls( request_id=RequestId.from_json(json['requestId']), request=network.Request.from_json(json['request']), frame_id=page.FrameId.from_json(json['frameId']), resource_type=network.ResourceType.from_json(json['resourceType']), - response_error_reason=network.ErrorReason.from_json(json['responseErrorReason']), - response_status_code=int(json['responseStatusCode']), - response_headers=[HeaderEntry.from_json(i) for i in json['responseHeaders']], - network_id=RequestId.from_json(json['networkId']), + response_error_reason=response_error_reason, + response_status_code=response_status_code, + response_headers=response_headers, + network_id=network_id, ) diff --git a/cdp/fetch/types.py b/cdp/fetch/types.py index 292ac80..97070f3 100644 --- a/cdp/fetch/types.py +++ b/cdp/fetch/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: str) -> 'RequestId': return cls(json) def __repr__(self): - return 'RequestId({})'.format(str.__repr__(self)) + return 'RequestId({})'.format(super().__repr__()) class RequestStage(enum.Enum): diff --git a/cdp/heap_profiler/events.py b/cdp/heap_profiler/events.py index a202e8a..0bc9f8f 100644 --- a/cdp/heap_profiler/events.py +++ b/cdp/heap_profiler/events.py @@ -85,7 +85,7 @@ class ReportHeapSnapshotProgress: total: int - finished: bool + finished: typing.Optional[bool] = None # These fields are used for internal purposes and are not part of CDP _domain = 'HeapProfiler' @@ -93,10 +93,11 @@ class ReportHeapSnapshotProgress: @classmethod def from_json(cls, json: dict) -> 'ReportHeapSnapshotProgress': + finished = bool(json['finished']) if 'finished' in json else None return cls( done=int(json['done']), total=int(json['total']), - finished=bool(json['finished']), + finished=finished, ) diff --git a/cdp/heap_profiler/types.py b/cdp/heap_profiler/types.py index 54eb156..d6f6f5e 100644 --- a/cdp/heap_profiler/types.py +++ b/cdp/heap_profiler/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: str) -> 'HeapSnapshotObjectId': return cls(json) def __repr__(self): - return 'HeapSnapshotObjectId({})'.format(str.__repr__(self)) + return 'HeapSnapshotObjectId({})'.format(super().__repr__()) @dataclass diff --git a/cdp/input/types.py b/cdp/input/types.py index 350c8db..fa6359b 100644 --- a/cdp/input/types.py +++ b/cdp/input/types.py @@ -39,7 +39,7 @@ def from_json(cls, json: float) -> 'TimeSinceEpoch': return cls(json) def __repr__(self): - return 'TimeSinceEpoch({})'.format(float.__repr__(self)) + return 'TimeSinceEpoch({})'.format(super().__repr__()) @dataclass diff --git a/cdp/io/types.py b/cdp/io/types.py index fefc29e..e59ad4a 100644 --- a/cdp/io/types.py +++ b/cdp/io/types.py @@ -27,6 +27,6 @@ def from_json(cls, json: str) -> 'StreamHandle': return cls(json) def __repr__(self): - return 'StreamHandle({})'.format(str.__repr__(self)) + return 'StreamHandle({})'.format(super().__repr__()) diff --git a/cdp/layer_tree/events.py b/cdp/layer_tree/events.py index 5a9a110..221ab89 100644 --- a/cdp/layer_tree/events.py +++ b/cdp/layer_tree/events.py @@ -38,7 +38,7 @@ def from_json(cls, json: dict) -> 'LayerPainted': @dataclass class LayerTreeDidChange: - layers: typing.List['Layer'] + layers: typing.Optional[typing.List['Layer']] = None # These fields are used for internal purposes and are not part of CDP _domain = 'LayerTree' @@ -46,7 +46,8 @@ class LayerTreeDidChange: @classmethod def from_json(cls, json: dict) -> 'LayerTreeDidChange': + layers = [Layer.from_json(i) for i in json['layers']] if 'layers' in json else None return cls( - layers=[Layer.from_json(i) for i in json['layers']], + layers=layers, ) diff --git a/cdp/layer_tree/types.py b/cdp/layer_tree/types.py index 66ff187..147bc0e 100644 --- a/cdp/layer_tree/types.py +++ b/cdp/layer_tree/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: str) -> 'LayerId': return cls(json) def __repr__(self): - return 'LayerId({})'.format(str.__repr__(self)) + return 'LayerId({})'.format(super().__repr__()) class SnapshotId(str): @@ -43,7 +43,7 @@ def from_json(cls, json: str) -> 'SnapshotId': return cls(json) def __repr__(self): - return 'SnapshotId({})'.format(str.__repr__(self)) + return 'SnapshotId({})'.format(super().__repr__()) class PaintProfile(typing.List['float']): @@ -58,7 +58,7 @@ def from_json(cls, json: typing.List['float']) -> 'PaintProfile': return cls(json) def __repr__(self): - return 'PaintProfile({})'.format(typing.List['float'].__repr__(self)) + return 'PaintProfile({})'.format(super().__repr__()) @dataclass diff --git a/cdp/network/events.py b/cdp/network/events.py index 243ebd8..6247205 100644 --- a/cdp/network/events.py +++ b/cdp/network/events.py @@ -102,10 +102,10 @@ class LoadingFailed: error_text: str #: Fired when HTTP request has failed to load. - canceled: bool + canceled: typing.Optional[bool] = None #: Fired when HTTP request has failed to load. - blocked_reason: BlockedReason + blocked_reason: typing.Optional[BlockedReason] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Network' @@ -113,13 +113,15 @@ class LoadingFailed: @classmethod def from_json(cls, json: dict) -> 'LoadingFailed': + canceled = bool(json['canceled']) if 'canceled' in json else None + blocked_reason = BlockedReason.from_json(json['blockedReason']) if 'blockedReason' in json else None return cls( request_id=RequestId.from_json(json['requestId']), timestamp=MonotonicTime.from_json(json['timestamp']), type=ResourceType.from_json(json['type']), error_text=str(json['errorText']), - canceled=bool(json['canceled']), - blocked_reason=BlockedReason.from_json(json['blockedReason']), + canceled=canceled, + blocked_reason=blocked_reason, ) @@ -138,7 +140,7 @@ class LoadingFinished: encoded_data_length: float #: Fired when HTTP request has finished loading. - should_report_corb_blocking: bool + should_report_corb_blocking: typing.Optional[bool] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Network' @@ -146,11 +148,12 @@ class LoadingFinished: @classmethod def from_json(cls, json: dict) -> 'LoadingFinished': + should_report_corb_blocking = bool(json['shouldReportCorbBlocking']) if 'shouldReportCorbBlocking' in json else None return cls( request_id=RequestId.from_json(json['requestId']), timestamp=MonotonicTime.from_json(json['timestamp']), encoded_data_length=float(json['encodedDataLength']), - should_report_corb_blocking=bool(json['shouldReportCorbBlocking']), + should_report_corb_blocking=should_report_corb_blocking, ) @@ -182,31 +185,31 @@ class RequestIntercepted: #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - is_download: bool + is_download: typing.Optional[bool] = None #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - redirect_url: str + redirect_url: typing.Optional[str] = None #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - auth_challenge: AuthChallenge + auth_challenge: typing.Optional[AuthChallenge] = None #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - response_error_reason: ErrorReason + response_error_reason: typing.Optional[ErrorReason] = None #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - response_status_code: int + response_status_code: typing.Optional[int] = None #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - response_headers: Headers + response_headers: typing.Optional[Headers] = None #: Details of an intercepted HTTP request, which must be either allowed, blocked, modified or #: mocked. - request_id: RequestId + request_id: typing.Optional[RequestId] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Network' @@ -214,19 +217,26 @@ class RequestIntercepted: @classmethod def from_json(cls, json: dict) -> 'RequestIntercepted': + is_download = bool(json['isDownload']) if 'isDownload' in json else None + redirect_url = str(json['redirectUrl']) if 'redirectUrl' in json else None + auth_challenge = AuthChallenge.from_json(json['authChallenge']) if 'authChallenge' in json else None + response_error_reason = ErrorReason.from_json(json['responseErrorReason']) if 'responseErrorReason' in json else None + response_status_code = int(json['responseStatusCode']) if 'responseStatusCode' in json else None + response_headers = Headers.from_json(json['responseHeaders']) if 'responseHeaders' in json else None + request_id = RequestId.from_json(json['requestId']) if 'requestId' in json else None return cls( interception_id=InterceptionId.from_json(json['interceptionId']), request=Request.from_json(json['request']), frame_id=page.FrameId.from_json(json['frameId']), resource_type=ResourceType.from_json(json['resourceType']), is_navigation_request=bool(json['isNavigationRequest']), - is_download=bool(json['isDownload']), - redirect_url=str(json['redirectUrl']), - auth_challenge=AuthChallenge.from_json(json['authChallenge']), - response_error_reason=ErrorReason.from_json(json['responseErrorReason']), - response_status_code=int(json['responseStatusCode']), - response_headers=Headers.from_json(json['responseHeaders']), - request_id=RequestId.from_json(json['requestId']), + is_download=is_download, + redirect_url=redirect_url, + auth_challenge=auth_challenge, + response_error_reason=response_error_reason, + response_status_code=response_status_code, + response_headers=response_headers, + request_id=request_id, ) @@ -276,16 +286,16 @@ class RequestWillBeSent: initiator: Initiator #: Fired when page is about to send HTTP request. - redirect_response: Response + redirect_response: typing.Optional[Response] = None #: Fired when page is about to send HTTP request. - type: ResourceType + type: typing.Optional[ResourceType] = None #: Fired when page is about to send HTTP request. - frame_id: page.FrameId + frame_id: typing.Optional[page.FrameId] = None #: Fired when page is about to send HTTP request. - has_user_gesture: bool + has_user_gesture: typing.Optional[bool] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Network' @@ -293,6 +303,10 @@ class RequestWillBeSent: @classmethod def from_json(cls, json: dict) -> 'RequestWillBeSent': + redirect_response = Response.from_json(json['redirectResponse']) if 'redirectResponse' in json else None + type = ResourceType.from_json(json['type']) if 'type' in json else None + frame_id = page.FrameId.from_json(json['frameId']) if 'frameId' in json else None + has_user_gesture = bool(json['hasUserGesture']) if 'hasUserGesture' in json else None return cls( request_id=RequestId.from_json(json['requestId']), loader_id=LoaderId.from_json(json['loaderId']), @@ -301,10 +315,10 @@ def from_json(cls, json: dict) -> 'RequestWillBeSent': timestamp=MonotonicTime.from_json(json['timestamp']), wall_time=TimeSinceEpoch.from_json(json['wallTime']), initiator=Initiator.from_json(json['initiator']), - redirect_response=Response.from_json(json['redirectResponse']), - type=ResourceType.from_json(json['type']), - frame_id=page.FrameId.from_json(json['frameId']), - has_user_gesture=bool(json['hasUserGesture']), + redirect_response=redirect_response, + type=type, + frame_id=frame_id, + has_user_gesture=has_user_gesture, ) @@ -379,7 +393,7 @@ class ResponseReceived: response: Response #: Fired when HTTP response is available. - frame_id: page.FrameId + frame_id: typing.Optional[page.FrameId] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Network' @@ -387,13 +401,14 @@ class ResponseReceived: @classmethod def from_json(cls, json: dict) -> 'ResponseReceived': + frame_id = page.FrameId.from_json(json['frameId']) if 'frameId' in json else None return cls( request_id=RequestId.from_json(json['requestId']), loader_id=LoaderId.from_json(json['loaderId']), timestamp=MonotonicTime.from_json(json['timestamp']), type=ResourceType.from_json(json['type']), response=Response.from_json(json['response']), - frame_id=page.FrameId.from_json(json['frameId']), + frame_id=frame_id, ) @@ -432,7 +447,7 @@ class WebSocketCreated: url: str #: Fired upon WebSocket creation. - initiator: Initiator + initiator: typing.Optional[Initiator] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Network' @@ -440,10 +455,11 @@ class WebSocketCreated: @classmethod def from_json(cls, json: dict) -> 'WebSocketCreated': + initiator = Initiator.from_json(json['initiator']) if 'initiator' in json else None return cls( request_id=RequestId.from_json(json['requestId']), url=str(json['url']), - initiator=Initiator.from_json(json['initiator']), + initiator=initiator, ) diff --git a/cdp/network/types.py b/cdp/network/types.py index 0bf0eb9..dd58421 100644 --- a/cdp/network/types.py +++ b/cdp/network/types.py @@ -58,7 +58,7 @@ def from_json(cls, json: str) -> 'LoaderId': return cls(json) def __repr__(self): - return 'LoaderId({})'.format(str.__repr__(self)) + return 'LoaderId({})'.format(super().__repr__()) class RequestId(str): @@ -73,7 +73,7 @@ def from_json(cls, json: str) -> 'RequestId': return cls(json) def __repr__(self): - return 'RequestId({})'.format(str.__repr__(self)) + return 'RequestId({})'.format(super().__repr__()) class InterceptionId(str): @@ -88,7 +88,7 @@ def from_json(cls, json: str) -> 'InterceptionId': return cls(json) def __repr__(self): - return 'InterceptionId({})'.format(str.__repr__(self)) + return 'InterceptionId({})'.format(super().__repr__()) class ErrorReason(enum.Enum): @@ -130,7 +130,7 @@ def from_json(cls, json: float) -> 'TimeSinceEpoch': return cls(json) def __repr__(self): - return 'TimeSinceEpoch({})'.format(float.__repr__(self)) + return 'TimeSinceEpoch({})'.format(super().__repr__()) class MonotonicTime(float): @@ -145,7 +145,7 @@ def from_json(cls, json: float) -> 'MonotonicTime': return cls(json) def __repr__(self): - return 'MonotonicTime({})'.format(float.__repr__(self)) + return 'MonotonicTime({})'.format(super().__repr__()) class ConnectionType(enum.Enum): diff --git a/cdp/page/events.py b/cdp/page/events.py index 3ce4c48..3e70757 100644 --- a/cdp/page/events.py +++ b/cdp/page/events.py @@ -46,7 +46,7 @@ class FrameAttached: parent_frame_id: FrameId #: Fired when frame has been attached to its parent. - stack: runtime.StackTrace + stack: typing.Optional[runtime.StackTrace] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Page' @@ -54,10 +54,11 @@ class FrameAttached: @classmethod def from_json(cls, json: dict) -> 'FrameAttached': + stack = runtime.StackTrace.from_json(json['stack']) if 'stack' in json else None return cls( frame_id=FrameId.from_json(json['frameId']), parent_frame_id=FrameId.from_json(json['parentFrameId']), - stack=runtime.StackTrace.from_json(json['stack']), + stack=stack, ) @@ -333,7 +334,7 @@ class JavascriptDialogOpening: #: Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) is about to #: open. - default_prompt: str + default_prompt: typing.Optional[str] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Page' @@ -341,12 +342,13 @@ class JavascriptDialogOpening: @classmethod def from_json(cls, json: dict) -> 'JavascriptDialogOpening': + default_prompt = str(json['defaultPrompt']) if 'defaultPrompt' in json else None return cls( url=str(json['url']), message=str(json['message']), type=DialogType.from_json(json['type']), has_browser_handler=bool(json['hasBrowserHandler']), - default_prompt=str(json['defaultPrompt']), + default_prompt=default_prompt, ) diff --git a/cdp/page/types.py b/cdp/page/types.py index 957e864..6424d3c 100644 --- a/cdp/page/types.py +++ b/cdp/page/types.py @@ -28,7 +28,7 @@ def from_json(cls, json: str) -> 'FrameId': return cls(json) def __repr__(self): - return 'FrameId({})'.format(str.__repr__(self)) + return 'FrameId({})'.format(super().__repr__()) class ScriptIdentifier(str): @@ -43,7 +43,7 @@ def from_json(cls, json: str) -> 'ScriptIdentifier': return cls(json) def __repr__(self): - return 'ScriptIdentifier({})'.format(str.__repr__(self)) + return 'ScriptIdentifier({})'.format(super().__repr__()) class TransitionType(enum.Enum): diff --git a/cdp/profiler/events.py b/cdp/profiler/events.py index a749c31..0880244 100644 --- a/cdp/profiler/events.py +++ b/cdp/profiler/events.py @@ -26,7 +26,7 @@ class ConsoleProfileFinished: profile: Profile - title: str + title: typing.Optional[str] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Profiler' @@ -34,11 +34,12 @@ class ConsoleProfileFinished: @classmethod def from_json(cls, json: dict) -> 'ConsoleProfileFinished': + title = str(json['title']) if 'title' in json else None return cls( id=str(json['id']), location=debugger.Location.from_json(json['location']), profile=Profile.from_json(json['profile']), - title=str(json['title']), + title=title, ) @@ -54,7 +55,7 @@ class ConsoleProfileStarted: location: debugger.Location #: Sent when new profile recording is started using console.profile() call. - title: str + title: typing.Optional[str] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Profiler' @@ -62,9 +63,10 @@ class ConsoleProfileStarted: @classmethod def from_json(cls, json: dict) -> 'ConsoleProfileStarted': + title = str(json['title']) if 'title' in json else None return cls( id=str(json['id']), location=debugger.Location.from_json(json['location']), - title=str(json['title']), + title=title, ) diff --git a/cdp/runtime/events.py b/cdp/runtime/events.py index 4bf6fc5..da2bfb4 100644 --- a/cdp/runtime/events.py +++ b/cdp/runtime/events.py @@ -61,10 +61,10 @@ class ConsoleAPICalled: timestamp: Timestamp #: Issued when console API was called. - stack_trace: StackTrace + stack_trace: typing.Optional[StackTrace] = None #: Issued when console API was called. - context: str + context: typing.Optional[str] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Runtime' @@ -72,13 +72,15 @@ class ConsoleAPICalled: @classmethod def from_json(cls, json: dict) -> 'ConsoleAPICalled': + stack_trace = StackTrace.from_json(json['stackTrace']) if 'stackTrace' in json else None + context = str(json['context']) if 'context' in json else None return cls( type=str(json['type']), args=[RemoteObject.from_json(i) for i in json['args']], execution_context_id=ExecutionContextId.from_json(json['executionContextId']), timestamp=Timestamp.from_json(json['timestamp']), - stack_trace=StackTrace.from_json(json['stackTrace']), - context=str(json['context']), + stack_trace=stack_trace, + context=context, ) diff --git a/cdp/runtime/types.py b/cdp/runtime/types.py index dbcb5d0..6d1c6ff 100644 --- a/cdp/runtime/types.py +++ b/cdp/runtime/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: str) -> 'ScriptId': return cls(json) def __repr__(self): - return 'ScriptId({})'.format(str.__repr__(self)) + return 'ScriptId({})'.format(super().__repr__()) class RemoteObjectId(str): @@ -41,7 +41,7 @@ def from_json(cls, json: str) -> 'RemoteObjectId': return cls(json) def __repr__(self): - return 'RemoteObjectId({})'.format(str.__repr__(self)) + return 'RemoteObjectId({})'.format(super().__repr__()) class UnserializableValue(str): @@ -57,7 +57,7 @@ def from_json(cls, json: str) -> 'UnserializableValue': return cls(json) def __repr__(self): - return 'UnserializableValue({})'.format(str.__repr__(self)) + return 'UnserializableValue({})'.format(super().__repr__()) class ExecutionContextId(int): @@ -72,7 +72,7 @@ def from_json(cls, json: int) -> 'ExecutionContextId': return cls(json) def __repr__(self): - return 'ExecutionContextId({})'.format(int.__repr__(self)) + return 'ExecutionContextId({})'.format(super().__repr__()) class Timestamp(float): @@ -87,7 +87,7 @@ def from_json(cls, json: float) -> 'Timestamp': return cls(json) def __repr__(self): - return 'Timestamp({})'.format(float.__repr__(self)) + return 'Timestamp({})'.format(super().__repr__()) class TimeDelta(float): @@ -102,7 +102,7 @@ def from_json(cls, json: float) -> 'TimeDelta': return cls(json) def __repr__(self): - return 'TimeDelta({})'.format(float.__repr__(self)) + return 'TimeDelta({})'.format(super().__repr__()) class UniqueDebuggerId(str): @@ -117,7 +117,7 @@ def from_json(cls, json: str) -> 'UniqueDebuggerId': return cls(json) def __repr__(self): - return 'UniqueDebuggerId({})'.format(str.__repr__(self)) + return 'UniqueDebuggerId({})'.format(super().__repr__()) @dataclass diff --git a/cdp/security/events.py b/cdp/security/events.py index 006d2dc..ecd85f4 100644 --- a/cdp/security/events.py +++ b/cdp/security/events.py @@ -73,7 +73,7 @@ class SecurityStateChanged: insecure_content_status: InsecureContentStatus #: The security state of the page changed. - summary: str + summary: typing.Optional[str] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Security' @@ -81,11 +81,12 @@ class SecurityStateChanged: @classmethod def from_json(cls, json: dict) -> 'SecurityStateChanged': + summary = str(json['summary']) if 'summary' in json else None return cls( security_state=SecurityState.from_json(json['securityState']), scheme_is_cryptographic=bool(json['schemeIsCryptographic']), explanations=[SecurityStateExplanation.from_json(i) for i in json['explanations']], insecure_content_status=InsecureContentStatus.from_json(json['insecureContentStatus']), - summary=str(json['summary']), + summary=summary, ) diff --git a/cdp/security/types.py b/cdp/security/types.py index f5806e9..e4df68f 100644 --- a/cdp/security/types.py +++ b/cdp/security/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: int) -> 'CertificateId': return cls(json) def __repr__(self): - return 'CertificateId({})'.format(int.__repr__(self)) + return 'CertificateId({})'.format(super().__repr__()) class MixedContentType(enum.Enum): diff --git a/cdp/service_worker/types.py b/cdp/service_worker/types.py index 02a7333..9818ec2 100644 --- a/cdp/service_worker/types.py +++ b/cdp/service_worker/types.py @@ -25,7 +25,7 @@ def from_json(cls, json: str) -> 'RegistrationID': return cls(json) def __repr__(self): - return 'RegistrationID({})'.format(str.__repr__(self)) + return 'RegistrationID({})'.format(super().__repr__()) class ServiceWorkerVersionRunningStatus(enum.Enum): diff --git a/cdp/target/events.py b/cdp/target/events.py index 6325aff..d755f24 100644 --- a/cdp/target/events.py +++ b/cdp/target/events.py @@ -55,7 +55,7 @@ class DetachedFromTarget: #: Issued when detached from target for any reason (including `detachFromTarget` command). Can be #: issued multiple times per target if multiple sessions have been attached to it. - target_id: TargetID + target_id: typing.Optional[TargetID] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Target' @@ -63,9 +63,10 @@ class DetachedFromTarget: @classmethod def from_json(cls, json: dict) -> 'DetachedFromTarget': + target_id = TargetID.from_json(json['targetId']) if 'targetId' in json else None return cls( session_id=SessionID.from_json(json['sessionId']), - target_id=TargetID.from_json(json['targetId']), + target_id=target_id, ) @@ -85,7 +86,7 @@ class ReceivedMessageFromTarget: #: Notifies about a new protocol message received from the session (as reported in #: `attachedToTarget` event). - target_id: TargetID + target_id: typing.Optional[TargetID] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Target' @@ -93,10 +94,11 @@ class ReceivedMessageFromTarget: @classmethod def from_json(cls, json: dict) -> 'ReceivedMessageFromTarget': + target_id = TargetID.from_json(json['targetId']) if 'targetId' in json else None return cls( session_id=SessionID.from_json(json['sessionId']), message=str(json['message']), - target_id=TargetID.from_json(json['targetId']), + target_id=target_id, ) diff --git a/cdp/target/types.py b/cdp/target/types.py index 034b722..d400d7b 100644 --- a/cdp/target/types.py +++ b/cdp/target/types.py @@ -23,7 +23,7 @@ def from_json(cls, json: str) -> 'TargetID': return cls(json) def __repr__(self): - return 'TargetID({})'.format(str.__repr__(self)) + return 'TargetID({})'.format(super().__repr__()) class SessionID(str): @@ -38,7 +38,7 @@ def from_json(cls, json: str) -> 'SessionID': return cls(json) def __repr__(self): - return 'SessionID({})'.format(str.__repr__(self)) + return 'SessionID({})'.format(super().__repr__()) class BrowserContextID(str): @@ -50,7 +50,7 @@ def from_json(cls, json: str) -> 'BrowserContextID': return cls(json) def __repr__(self): - return 'BrowserContextID({})'.format(str.__repr__(self)) + return 'BrowserContextID({})'.format(super().__repr__()) @dataclass diff --git a/cdp/tracing/events.py b/cdp/tracing/events.py index 553a720..7aea76f 100644 --- a/cdp/tracing/events.py +++ b/cdp/tracing/events.py @@ -20,11 +20,11 @@ @dataclass class BufferUsage: - percent_full: float + percent_full: typing.Optional[float] = None - event_count: float + event_count: typing.Optional[float] = None - value: float + value: typing.Optional[float] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Tracing' @@ -32,10 +32,13 @@ class BufferUsage: @classmethod def from_json(cls, json: dict) -> 'BufferUsage': + percent_full = float(json['percentFull']) if 'percentFull' in json else None + event_count = float(json['eventCount']) if 'eventCount' in json else None + value = float(json['value']) if 'value' in json else None return cls( - percent_full=float(json['percentFull']), - event_count=float(json['eventCount']), - value=float(json['value']), + percent_full=percent_full, + event_count=event_count, + value=value, ) @@ -68,15 +71,15 @@ class TracingComplete: ''' #: Signals that tracing is stopped and there is no trace buffers pending flush, all data were #: delivered via dataCollected events. - stream: io.StreamHandle + stream: typing.Optional[io.StreamHandle] = None #: Signals that tracing is stopped and there is no trace buffers pending flush, all data were #: delivered via dataCollected events. - trace_format: StreamFormat + trace_format: typing.Optional[StreamFormat] = None #: Signals that tracing is stopped and there is no trace buffers pending flush, all data were #: delivered via dataCollected events. - stream_compression: StreamCompression + stream_compression: typing.Optional[StreamCompression] = None # These fields are used for internal purposes and are not part of CDP _domain = 'Tracing' @@ -84,9 +87,12 @@ class TracingComplete: @classmethod def from_json(cls, json: dict) -> 'TracingComplete': + stream = io.StreamHandle.from_json(json['stream']) if 'stream' in json else None + trace_format = StreamFormat.from_json(json['traceFormat']) if 'traceFormat' in json else None + stream_compression = StreamCompression.from_json(json['streamCompression']) if 'streamCompression' in json else None return cls( - stream=io.StreamHandle.from_json(json['stream']), - trace_format=StreamFormat.from_json(json['traceFormat']), - stream_compression=StreamCompression.from_json(json['streamCompression']), + stream=stream, + trace_format=trace_format, + stream_compression=stream_compression, ) diff --git a/cdp/web_audio/types.py b/cdp/web_audio/types.py index 1c7c282..bba6f9c 100644 --- a/cdp/web_audio/types.py +++ b/cdp/web_audio/types.py @@ -26,7 +26,7 @@ def from_json(cls, json: str) -> 'ContextId': return cls(json) def __repr__(self): - return 'ContextId({})'.format(str.__repr__(self)) + return 'ContextId({})'.format(super().__repr__()) class ContextType(enum.Enum): From 20eed523df54e1c50dfa9df328e440f1482026d3 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Fri, 28 Jun 2019 11:52:49 -0400 Subject: [PATCH 003/128] Change package name Don't need "python-" prefix --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index c212491..2a1d406 100644 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ long_description = f.read() setup( - name='python-chrome-devtools-protocol', + name='chrome-devtools-protocol', version='0.1.0-dev', description='Python type wrappers for Chrome DevTools Protocol (CDP)', long_description=long_description, From 337bcec5b44cd018c4413656c0b2f66a3067efe6 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Mon, 26 Aug 2019 10:10:05 -0400 Subject: [PATCH 004/128] Refactor build script This is step 1 of a series of commits to refactor the build script. It is currently very messy and unmaintainable, because the first time we wrote we wanted to read the protocol spec and emit code in a single pass. As we implemented all of the features, this approach became more and more burdernsome, but we stuck with it in the interest of finishing a completely working version as quickly as possible. The new approach is going to be parsing the JSON up front, processing it in memory, and then emitting Python code. This approach should be much cleaner and will enable us to move from 4 files per CDP domain to just 1 file per domain. In this first commit, I've just added data classes to read in the CDP spec. No changes to codegen, yet. --- build/generate.py | 154 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 143 insertions(+), 11 deletions(-) diff --git a/build/generate.py b/build/generate.py index eaa8ba1..d753678 100644 --- a/build/generate.py +++ b/build/generate.py @@ -1,3 +1,5 @@ +from dataclasses import dataclass +from enum import Enum import json import logging import operator @@ -12,22 +14,22 @@ logging.basicConfig(level=log_level) logger = logging.getLogger('generate') -init_header = '''\'\'\' -DO NOT EDIT THIS FILE +shared_header = '''DO NOT EDIT THIS FILE This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. +edit the generator and regenerate all of the modules.''' + +init_header = '''\'\'\' +{} \'\'\' -''' -module_header = '''\'\'\' -DO NOT EDIT THIS FILE +'''.format(shared_header) -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. +module_header = '''\'\'\' +{} -Domain: {} -Experimental: {} +Domain: {{}} +Experimental: {{}} \'\'\' from cdp.util import T_JSON_DICT @@ -35,7 +37,7 @@ import enum import typing -''' +'''.format(shared_header) def clear_dirs(package_path): @@ -58,6 +60,134 @@ def rmdir(path): rmdir(subpath) +class CdpPrimitiveType(Enum): + ''' All of the CDP types that map directly to Python types. ''' + any: typing.Any + boolean = bool + integer = int + number = float + object = dict + string = str + + +@dataclass +class CdpProperty: + ''' A property belonging to a non-primitive CDP type. ''' + name: str + description: str + type: str + ref: str + enum: typing.List[str] + optional: bool + + @classmethod + def from_json(cls, property): + return cls( + property['name'], + property.get('description'), + property.get('type'), + property.get('$ref'), + property.get('enum'), + property.get('optional', False), + ) + + +@dataclass +class CdpType: + ''' A top-level CDP type. ''' + id: str + description: str + type: str + enum: typing.List[str] + properties: typing.List[CdpProperty] + + @classmethod + def from_json(cls, type): + return cls( + type['id'], + type.get('description'), + type['type'], + type.get('enum'), + type.get('properties'), + ) + + +class CdpParameter(CdpProperty): + ''' + A parameter to a CDP command. + + This is an empty subclass of CdpProperty because they seem to share the same + behavior, but I want to allow the flexibility to change the behavior later + on. + ''' + + +class CdpReturn(CdpProperty): + ''' + A return value from a CDP command. + + This is an empty subclass of CdpProperty because they seem to share the same + behavior, but I want to allow the flexibility to change the behavior later + on. + ''' + + +@dataclass +class CdpCommand: + ''' A CDP command. ''' + name: str + description: str + experimental: bool + parameters: typing.List[CdpParameter] + returns: typing.List[CdpReturn] + + @classmethod + def from_json(cls, command): + parameters = command.get('parameters', list()) + returns = command.get('returns', list()) + + return cls( + command['name'], + command.get('description'), + command.get('experimental', False), + [CdpParameter.from_json(p) for p in parameters], + [CdpReturn.from_json(r) for r in returns], + ) + +@dataclass +class CdpEvent: + ''' A CDP event object. ''' + name: str + description: str + parameters: typing.List[CdpParameter] + + +@dataclass +class CdpDomain: + ''' A CDP domain contains metadata, types, commands, and events. ''' + domain: str + experimental: bool + dependencies: typing.List[str] + types: typing.List[CdpType] + commands: typing.List[CdpCommand] + events: typing.List[CdpEvent] + + @classmethod + def from_json(cls, domain): + types = domain.get('types', list()) + commands = domain.get('commands', list()) + events = domain.get('events', list()) + + return cls( + domain['domain'], + domain.get('experimental', False), + domain.get('dependencies', list()), + [CdpType.from_json(type) for type in types], + [CdpCommand.from_json(command) for command in commands], + list(), + ) + + def parse(json_path, output_path): ''' Parse JSON protocol description and generate module files. @@ -72,7 +202,9 @@ def parse(json_path, output_path): version = schema['version'] assert (version['major'], version['minor']) == ('1', '3') modules = list() + domains = list() for domain in schema['domains']: + domains.append(CdpDomain.from_json(domain)) modules.append( generate_domain_module(domain, output_path)) return modules From 48b2a90ea6f718c0a1f4cef4b91b4ee2a0c9346b Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Mon, 26 Aug 2019 11:55:17 -0400 Subject: [PATCH 005/128] Added a test script I added a pytest script so that I can test the codegen as I go through refactoring everything. This commit breaks the project: all modules emit "foobar" instead of real code. I added codegen for primitive types but that code isn't producing any output in the generated modules yet. --- build/generate.py | 410 +++++++++++++++++++++-------------------- build/test_generate.py | 67 +++++++ 2 files changed, 274 insertions(+), 203 deletions(-) create mode 100644 build/test_generate.py diff --git a/build/generate.py b/build/generate.py index d753678..addcb10 100644 --- a/build/generate.py +++ b/build/generate.py @@ -5,6 +5,7 @@ import operator import os from pathlib import Path +from textwrap import dedent, indent import typing import inflection @@ -62,12 +63,11 @@ def rmdir(path): class CdpPrimitiveType(Enum): ''' All of the CDP types that map directly to Python types. ''' - any: typing.Any - boolean = bool - integer = int - number = float - object = dict - string = str + boolean = 'bool' + integer = 'int' + number = 'float' + object = 'dict' + string = 'str' @dataclass @@ -82,6 +82,7 @@ class CdpProperty: @classmethod def from_json(cls, property): + ''' Instantiate a CDP property from a JSON object. ''' return cls( property['name'], property.get('description'), @@ -103,6 +104,7 @@ class CdpType: @classmethod def from_json(cls, type): + ''' Instantiate a CDP type from a JSON object. ''' return cls( type['id'], type.get('description'), @@ -111,6 +113,88 @@ def from_json(cls, type): type.get('properties'), ) + def generate_code(self): + ''' + Generate Python code for this type. + + :returns: code as a string + ''' + # todo handle exports and emitted types somewhere else? + # exports = list() + # exports.append(type_name) + # emitted_types = set() + logger.debug('Generating type %s: %s', self.id, self.type) + if self.enum: + return self.generate_enum_code() + elif self.properties: + return self.generate_object_code() + else: + return self.generate_primitive_code() + + def generate_primitive_code(self): + ''' + Generate code for a primitive type. + + :returns: code as a string + ''' + py_type = CdpPrimitiveType[self.type].value + + def_to_json = dedent(f'''\ + def to_json(self) -> {py_type}: + return self''') + + def_from_json = dedent(f'''\ + @classmethod + def from_json(cls, json: {py_type}) -> '{self.id}': + return cls(json)''') + + def_repr = dedent(f'''\ + def __repr__(self): + return '{self.id}({{}})'.format(super().__repr__())''') + + code = f'class {self.id}({py_type}):' + doc = docstring(self.description) + if doc: + code += '\n' + indent(doc, 4 * ' ') + code += '\n' + indent(def_to_json, 4 * ' ') + code += '\n\n' + indent(def_from_json, 4 * ' ') + code += '\n\n' + indent(def_repr, 4 * ' ') + + return code + + def generate_enum_code(self): + return '' + + def generate_object_code(self): + return '' + + + # Todo how to resolve dependencies? + # The classes have dependencies on each other, so we have to emit them in + # a specific order. If we can't resolve these dependencies after a certain + # number of iterations, it suggests a cyclical dependency that this code + # cannot handle. + # tries_remaining = 1000 + # while classes: + # class_ = classes.pop(0) + # if not class_['children']: + # code += class_['code'] + # emitted_types.add(class_['name']) + # continue + # if all(child in emitted_types for child in class_['children']): + # code += class_['code'] + # emitted_types.add(class_['name']) + # continue + # classes.append(class_) + # tries_remaining -= 1 + # if not tries_remaining: + # logger.error('Class resolution failed. Emitted these types: %s', + # emitted_types) + # logger.error('Class resolution failed. Cannot emit these types: %s', + # json.dumps(classes, indent=2)) + # raise Exception('Failed to resolve class dependencies.' + # ' See output above.') + class CdpParameter(CdpProperty): ''' @@ -143,6 +227,7 @@ class CdpCommand: @classmethod def from_json(cls, command): + ''' Instantiate a CDP command from a JSON object. ''' parameters = command.get('parameters', list()) returns = command.get('returns', list()) @@ -172,8 +257,14 @@ class CdpDomain: commands: typing.List[CdpCommand] events: typing.List[CdpEvent] + @property + def module(self): + ''' The name of the Python module for this CDP domain. ''' + return inflection.underscore(self.domain) + @classmethod def from_json(cls, domain): + ''' Instantiate a CDP domain from a JSON object. ''' types = domain.get('types', list()) commands = domain.get('commands', list()) events = domain.get('events', list()) @@ -187,123 +278,118 @@ def from_json(cls, domain): list(), ) + def generate_code(self): + ''' + Generate a Python module for a given CDP domain. + + :param dict domain: domain schema + :param Path output_path: a directory path to create the module in + :returns: module name and a list of exported names + ''' + logger.info('Generating module: %s → %s.py', self.domain, self.module) + return 'foobar' + name = domain['domain'] + experimental = domain.get('experimental', False) + + # The dependencies listed in the JSON don't match the actual dependencies + # encountered when building the types. So we ignore the declared + # dependencies and compute it ourself. + type_dependencies = set() + domain_types = domain.get('types', list()) + for type_ in domain_types: + for prop in type_.get('properties', list()): + dependency = get_dependency(prop) + if dependency: + type_dependencies.add(dependency) + if type_dependencies: + logger.debug('Computed type_dependencies: %s', ','.join( + type_dependencies)) + + event_dependencies = set() + domain_events = domain.get('events', list()) + for event in domain_events: + for param in event.get('parameters', list()): + dependency = get_dependency(param) + if dependency: + event_dependencies.add(dependency) + if event_dependencies: + logger.debug('Computed event_dependencies: %s', ','.join( + event_dependencies)) + + command_dependencies = set() + domain_commands = domain.get('commands', list()) + for command in domain_commands: + for param in command.get('parameters', list()): + dependency = get_dependency(param) + if dependency: + command_dependencies.add(dependency) + for return_ in command.get('returns', list()): + dependency = get_dependency(return_) + if dependency: + command_dependencies.add(dependency) + if command_dependencies: + logger.debug('Computed command_dependencies: %s', ','.join( + command_dependencies)) + + # Generate code for this module. + module_path = output_path / module_name + module_path.mkdir(parents=True, exist_ok=True) + init_path = module_path / '__init__.py' + with init_path.open('w'): + # Zero out this file + pass + + types_path = module_path / 'types.py' + with types_path.open('w') as types_file: + types_file.write(module_header.format(module_name, experimental)) + for dependency in sorted(type_dependencies): + types_file.write(import_dependency(dependency)) + if type_dependencies: + types_file.write('\n') + type_exports, type_code = generate_types(domain_types) + types_file.write(type_code) + + events_path = module_path / 'events.py' + with events_path.open('w') as events_file: + events_file.write(module_header.format(module_name, experimental)) + events_file.write('from .types import *\n') + for dependency in sorted(event_dependencies): + events_file.write(import_dependency(dependency)) + if event_dependencies: + events_file.write('\n') + event_exports, event_code = generate_events(name, domain_events) + events_file.write(event_code) + + commands_path = module_path / 'commands.py' + with commands_path.open('w') as commands_file: + commands_file.write(module_header.format(module_name, experimental)) + commands_file.write('from .types import *\n') + for dependency in sorted(command_dependencies): + commands_file.write(import_dependency(dependency)) + if command_dependencies: + commands_file.write('\n') + command_exports, command_code = generate_commands(name, domain_commands) + commands_file.write(command_code) + + return module_name, type_exports, event_exports, command_exports + def parse(json_path, output_path): ''' - Parse JSON protocol description and generate module files. + Parse JSON protocol description and return domain objects. :param Path json_path: path to a JSON CDP schema :param Path output_path: a directory path to create the modules in - :returns: a list of 2-tuples containing (module name, list of exported - symbols) + :returns: a list of CDP domain objects ''' with json_path.open() as json_file: schema = json.load(json_file) version = schema['version'] assert (version['major'], version['minor']) == ('1', '3') - modules = list() domains = list() for domain in schema['domains']: domains.append(CdpDomain.from_json(domain)) - modules.append( - generate_domain_module(domain, output_path)) - return modules - - -def generate_domain_module(domain, output_path): - ''' - Generate a Python module for a given CDP domain. - - :param dict domain: domain schema - :param Path output_path: a directory path to create the module in - :returns: module name and a list of exported names - ''' - name = domain['domain'] - module_name = inflection.underscore(name) - logger.info('Generating module: %s → %s.py', name, module_name) - experimental = domain.get('experimental', False) - - # The dependencies listed in the JSON don't match the actual dependencies - # encountered when building the types. So we ignore the declared - # dependencies and compute it ourself. - type_dependencies = set() - domain_types = domain.get('types', list()) - for type_ in domain_types: - for prop in type_.get('properties', list()): - dependency = get_dependency(prop) - if dependency: - type_dependencies.add(dependency) - if type_dependencies: - logger.debug('Computed type_dependencies: %s', ','.join( - type_dependencies)) - - event_dependencies = set() - domain_events = domain.get('events', list()) - for event in domain_events: - for param in event.get('parameters', list()): - dependency = get_dependency(param) - if dependency: - event_dependencies.add(dependency) - if event_dependencies: - logger.debug('Computed event_dependencies: %s', ','.join( - event_dependencies)) - - command_dependencies = set() - domain_commands = domain.get('commands', list()) - for command in domain_commands: - for param in command.get('parameters', list()): - dependency = get_dependency(param) - if dependency: - command_dependencies.add(dependency) - for return_ in command.get('returns', list()): - dependency = get_dependency(return_) - if dependency: - command_dependencies.add(dependency) - if command_dependencies: - logger.debug('Computed command_dependencies: %s', ','.join( - command_dependencies)) - - # Generate code for this module. - module_path = output_path / module_name - module_path.mkdir(parents=True, exist_ok=True) - init_path = module_path / '__init__.py' - with init_path.open('w'): - # Zero out this file - pass - - types_path = module_path / 'types.py' - with types_path.open('w') as types_file: - types_file.write(module_header.format(module_name, experimental)) - for dependency in sorted(type_dependencies): - types_file.write(import_dependency(dependency)) - if type_dependencies: - types_file.write('\n') - type_exports, type_code = generate_types(domain_types) - types_file.write(type_code) - - events_path = module_path / 'events.py' - with events_path.open('w') as events_file: - events_file.write(module_header.format(module_name, experimental)) - events_file.write('from .types import *\n') - for dependency in sorted(event_dependencies): - events_file.write(import_dependency(dependency)) - if event_dependencies: - events_file.write('\n') - event_exports, event_code = generate_events(name, domain_events) - events_file.write(event_code) - - commands_path = module_path / 'commands.py' - with commands_path.open('w') as commands_file: - commands_file.write(module_header.format(module_name, experimental)) - commands_file.write('from .types import *\n') - for dependency in sorted(command_dependencies): - commands_file.write(import_dependency(dependency)) - if command_dependencies: - commands_file.write('\n') - command_exports, command_code = generate_commands(name, domain_commands) - commands_file.write(command_code) - - return module_name, type_exports, event_exports, command_exports + return domains def get_dependency(cdp_meta): @@ -333,60 +419,6 @@ def import_dependency(dependency): return 'from ..{} import types as {}\n'.format(module_name, module_name) -def generate_types(types): - ''' - Generate type definitions as Python code. - - :param list types: a list of CDP type definitions - :returns: a tuple (list of types, code as string) - ''' - code = '\n' - exports = list() - classes = list() - emitted_types = set() - for type_ in types: - cdp_type = type_['type'] - type_name = type_['id'] - exports.append(type_name) - description = type_.get('description') - logger.debug('Generating type %s: %s', type_name, cdp_type) - if 'enum' in type_: - code += generate_enum_type(type_) - emitted_types.add(type_name) - elif cdp_type == 'object': - classes.append(generate_class_type(type_)) - else: - code += generate_basic_type(type_) - emitted_types.add(type_name) - - # The classes have dependencies on each other, so we have to emit them in - # a specific order. If we can't resolve these dependencies after a certain - # number of iterations, it suggests a cyclical dependency that this code - # cannot handle. - tries_remaining = 1000 - while classes: - class_ = classes.pop(0) - if not class_['children']: - code += class_['code'] - emitted_types.add(class_['name']) - continue - if all(child in emitted_types for child in class_['children']): - code += class_['code'] - emitted_types.add(class_['name']) - continue - classes.append(class_) - tries_remaining -= 1 - if not tries_remaining: - logger.error('Class resolution failed. Emitted these types: %s', - emitted_types) - logger.error('Class resolution failed. Cannot emit these types: %s', - json.dumps(classes, indent=2)) - raise Exception('Failed to resolve class dependencies.' - ' See output above.') - - return exports, code - - def inline_doc(description, indent=0): ''' Generate an inline doc, e.g. ``#: This type is a ...`` @@ -402,23 +434,16 @@ def inline_doc(description, indent=0): return ''.join(lines) -def docstring(description, indent=4): +def docstring(description): ''' Generate a docstring from a description. :param str description: - :param int indent: the number of spaces to indent the docstring ''' if not description: return '' - i = ' ' * indent - start_stop = "{}'''".format(i) - lines = [start_stop] - for line in description.split('\n'): - lines.append('{}{}'.format(i, line)) - lines.append(start_stop) - return '\n'.join(lines) + '\n' + return dedent("'''\n{}\n'''").format(description) def generate_enum_type(type_): @@ -451,7 +476,7 @@ def generate_enum_type(type_): return code -def get_python_type(cdp_meta): +def get_python_type(cdp_type): ''' Generate a name for the Python type that corresponds to the the given CDP type. @@ -614,33 +639,6 @@ def generate_class_type(type_): } -def generate_basic_type(type_): - ''' - Generate one of the "basic" types, i.e. type aliases for Python built-ins. - - :param dict type_: CDP type metadata - ''' - code = '' - cdp_type = type_['id'] - py_type = get_python_type(type_) - description = type_.get('description') - code += 'class {}({}):\n'.format(cdp_type, py_type) - code += docstring(description) - code += ' def to_json(self) -> {}:\n'.format(py_type) - code += ' return self\n' - code += '\n' - code += ' @classmethod\n' - code += " def from_json(cls, json: {}) -> '{}':\n".format( - py_type, cdp_type) - code += ' return cls(json)\n' - code += '\n' - code += ' def __repr__(self):\n' - code += " return '{}({{}})'.format(super().__repr__())\n".format( - cdp_type, py_type) - code += '\n\n' - return code - - def generate_events(domain, events): exports = list() code = '\n' @@ -866,15 +864,21 @@ def main(): here / 'js_protocol.json', ] output_path = here.parent / 'cdp' + output_path.mkdir(exist_ok=True) clear_dirs(output_path) - modules = list() + domains = list() for json_path in json_paths: logger.info('Parsing JSON file %s', json_path) - modules.extend(parse(json_path, output_path)) + domains.extend(parse(json_path, output_path)) + + for domain in domains: + module_path = output_path / f'{domain.module}.py' + with module_path.open('w') as module_file: + module_file.write(domain.generate_code()) init_path = output_path / '__init__.py' - generate_init(init_path, modules) + # generate_init(init_path, domains) py_typed_path = output_path / 'py.typed' py_typed_path.touch() diff --git a/build/test_generate.py b/build/test_generate.py new file mode 100644 index 0000000..6d98ed8 --- /dev/null +++ b/build/test_generate.py @@ -0,0 +1,67 @@ +''' +A combination of unit tests and integration tests. + +The main purpose of the tests is to make sure that the CDP spec is converted +into Python code correctly, i.e. integration testing. But some of the most +complicated logic is also covered by unit tests. + +Tests that generate code will typically print the expected and actual values. +Pytest doesn't display stdout by default unless a test fails, and debugging +codegen tests is almost always easier with the values displayed on stdout. +''' + +from textwrap import dedent + +from generate import CdpType, docstring + + +def test_docstring(): + description = \ + "Values of AXProperty name:\n- from 'busy' to 'roledescription': " \ + "states which apply to every AX node\n- from 'live' to 'root': " \ + "attributes which apply to nodes in live regions\n- from " \ + "'autocomplete' to 'valuetext': attributes which apply to " \ + "widgets\n- from 'checked' to 'selected': states which apply to " \ + "widgets\n- from 'activedescendant' to 'owns' - relationships " \ + "between elements other than parent/child/sibling." + expected = dedent("""\ + ''' + Values of AXProperty name: + - from 'busy' to 'roledescription': states which apply to every AX node + - from 'live' to 'root': attributes which apply to nodes in live regions + - from 'autocomplete' to 'valuetext': attributes which apply to widgets + - from 'checked' to 'selected': states which apply to widgets + - from 'activedescendant' to 'owns' - relationships between elements other than parent/child/sibling. + '''""") + actual = docstring(description) + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_primitive_type(): + json_type = { + "id": "AXNodeId", + "description": "Unique accessibility node identifier.", + "type": "string" + } + expected = dedent("""\ + class AXNodeId(str): + ''' + Unique accessibility node identifier. + ''' + def to_json(self) -> str: + return self + + @classmethod + def from_json(cls, json: str) -> 'AXNodeId': + return cls(json) + + def __repr__(self): + return 'AXNodeId({})'.format(super().__repr__())""") + + type = CdpType.from_json(json_type) + actual = type.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual From 8b7b8d466fc47340d9d1a84694faa5c48c0d7bc7 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Tue, 27 Aug 2019 11:31:34 -0400 Subject: [PATCH 006/128] Add support for CDP enum types and class types These are both covered by tests. --- build/generate.py | 436 ++++++++++++++++++++++------------------- build/test_generate.py | 122 ++++++++++++ 2 files changed, 361 insertions(+), 197 deletions(-) diff --git a/build/generate.py b/build/generate.py index addcb10..6886f9d 100644 --- a/build/generate.py +++ b/build/generate.py @@ -5,7 +5,7 @@ import operator import os from pathlib import Path -from textwrap import dedent, indent +from textwrap import dedent, indent as tw_indent import typing import inflection @@ -41,7 +41,11 @@ '''.format(shared_header) -def clear_dirs(package_path): +def indent(s: str, n: int): + ''' A shortcut for ``textwrap.indent`` that always uses spaces. ''' + return tw_indent(s, n * ' ') + +def clear_dirs(package_path: Path): ''' Remove generated code. ''' def rmdir(path): for subpath in path.iterdir(): @@ -61,8 +65,38 @@ def rmdir(path): rmdir(subpath) +def inline_doc(description) -> str: + ''' Generate an inline doc, e.g. ``#: This type is a ...`` ''' + if not description: + return '' + + lines = ['#: {}\n'.format(l) for l in description.split('\n')] + return ''.join(lines) + + +def docstring(description: typing.Optional[str]) -> str: + ''' Generate a docstring from a description. ''' + if not description: + return '' + + return dedent("'''\n{}\n'''").format(description) + + +def ref_to_python(ref: str) -> str: + ''' + Convert a CDP ``$ref`` to the name of a Python type. + + For a dotted ref, the part before the dot is snake cased. + ''' + if '.' in ref: + domain, subtype = ref.split('.') + ref = '{}.{}'.format(inflection.underscore(domain), subtype) + return f"{ref}" + + class CdpPrimitiveType(Enum): - ''' All of the CDP types that map directly to Python types. ''' + ''' All of the CDP types that map directly to a Python type annotation. ''' + any = 'typing.Any' boolean = 'bool' integer = 'int' number = 'float' @@ -70,6 +104,27 @@ class CdpPrimitiveType(Enum): string = 'str' +@dataclass +class CdpItemType: + ''' The type of a repeated item. ''' + type: str + ref: str + + @property + def py_annotation(self) -> str: + if self.type: + annotation = CdpPrimitiveType[self.type].value + else: + py_ref = ref_to_python(self.ref) + annotation = f"'{py_ref}'" + + return annotation + + @classmethod + def from_json(cls, type) -> 'CdpItemType': + return cls(type.get('type'), type.get('$ref')) + + @dataclass class CdpProperty: ''' A property belonging to a non-primitive CDP type. ''' @@ -78,10 +133,30 @@ class CdpProperty: type: str ref: str enum: typing.List[str] + items: CdpItemType optional: bool + @property + def py_name(self) -> str: + ''' Get this property's Python name. ''' + return inflection.underscore(self.name) + + @property + def py_annotation(self) -> str: + ''' This property's Python type annotation. ''' + if self.type == 'array': + ann = f'typing.List[{self.items.py_annotation}]' + elif self.ref: + py_ref = ref_to_python(self.ref) + ann = f"'{py_ref}'" + else: + ann = CdpPrimitiveType[self.type].value + if self.optional: + ann = f'typing.Optional[{ann}]' + return ann + @classmethod - def from_json(cls, property): + def from_json(cls, property) -> 'CdpProperty': ''' Instantiate a CDP property from a JSON object. ''' return cls( property['name'], @@ -89,9 +164,68 @@ def from_json(cls, property): property.get('type'), property.get('$ref'), property.get('enum'), + CdpItemType.from_json(property['items']) if 'items' in property else None, property.get('optional', False), ) + def generate_decl(self) -> str: + ''' Generate the code that declares this property. ''' + code = inline_doc(self.description) + # todo handle dependencies later + # elif '$ref' in prop and '.' not in prop_ann: + # # If the type lives in this module and is not a type that refers + # # to itself, then add it to the set of children so that + # # inter-class dependencies can be resolved later on. + # children.add(prop_ann) + code += f'{self.py_name}: {self.py_annotation}' + if self.optional: + code += ' = None' + return code + + def generate_to_json(self) -> str: + ''' Generate the code that exports this property to a JSON dict named + ``json``. ''' + if self.items: + if self.items.ref: + assign = f"json['{self.name}'] = " \ + f"[i.to_json() for i in self.{self.py_name}]" + else: + raise NotImplemented() + else: + if self.ref: + assign = f"json['{self.name}'] = self.{self.py_name}.to_json()" + else: + assign = f"json['{self.name}'] = self.{self.py_name}" + if self.optional: + code = dedent(f'''\ + if self.{self.py_name} is not None: + {assign}''') + else: + code = assign + return code + + def generate_from_json(self) -> str: + ''' Generate the code that creates an instance from a JSON dict named + ``json``. ''' + # todo this is one of the few places where a real dependency is created + # (most of the deps are type annotations and can be avoided by quoting + # the annotation) + if self.items: + if self.items.ref: + py_ref = ref_to_python(self.items.ref) + expr = f"[{py_ref}.from_json(i) for i in json['{self.name}']]" + else: + raise NotImplemented() + else: + if self.ref: + py_ref = ref_to_python(self.ref) + expr = f"{py_ref}.from_json(json['{self.name}'])" + else: + expr = f"json['{self.name}']" + if self.optional: + expr = f"{expr} if '{self.name}' in json else None" + return f'{self.name}={expr},' + @dataclass class CdpType: @@ -103,22 +237,18 @@ class CdpType: properties: typing.List[CdpProperty] @classmethod - def from_json(cls, type): + def from_json(cls, type) -> 'CdpType': ''' Instantiate a CDP type from a JSON object. ''' return cls( type['id'], type.get('description'), type['type'], type.get('enum'), - type.get('properties'), + [CdpProperty.from_json(p) for p in type.get('properties', list())], ) - def generate_code(self): - ''' - Generate Python code for this type. - - :returns: code as a string - ''' + def generate_code(self) -> str: + ''' Generate Python code for this type. ''' # todo handle exports and emitted types somewhere else? # exports = list() # exports.append(type_name) @@ -127,16 +257,12 @@ def generate_code(self): if self.enum: return self.generate_enum_code() elif self.properties: - return self.generate_object_code() + return self.generate_class_code() else: return self.generate_primitive_code() - def generate_primitive_code(self): - ''' - Generate code for a primitive type. - - :returns: code as a string - ''' + def generate_primitive_code(self) -> str: + ''' Generate code for a primitive type. ''' py_type = CdpPrimitiveType[self.type].value def_to_json = dedent(f'''\ @@ -152,22 +278,103 @@ def from_json(cls, json: {py_type}) -> '{self.id}': def __repr__(self): return '{self.id}({{}})'.format(super().__repr__())''') - code = f'class {self.id}({py_type}):' + code = f'class {self.id}({py_type}):\n' doc = docstring(self.description) if doc: - code += '\n' + indent(doc, 4 * ' ') - code += '\n' + indent(def_to_json, 4 * ' ') - code += '\n\n' + indent(def_from_json, 4 * ' ') - code += '\n\n' + indent(def_repr, 4 * ' ') + code += indent(doc, 4) + '\n' + code += indent(def_to_json, 4) + code += '\n\n' + indent(def_from_json, 4) + code += '\n\n' + indent(def_repr, 4) return code - def generate_enum_code(self): - return '' + def generate_enum_code(self) -> str: + ''' + Generate an "enum" type. - def generate_object_code(self): - return '' + Enums are handled by making a python class that contains only class + members. Each class member is upper snaked case, e.g. + ``MyTypeClass.MY_ENUM_VALUE`` and is assigned a string value from the + CDP metadata. + ''' + def_to_json = dedent('''\ + def to_json(self) -> str: + return self.value''') + + def_from_json = dedent(f'''\ + @classmethod + def from_json(cls, json: str) -> '{self.id}': + return cls(json)''') + + code = f'class {self.id}(enum.Enum):\n' + doc = docstring(self.description) + if doc: + code += indent(doc, 4) + '\n' + for enum_member in self.enum: + snake_case = inflection.underscore(enum_member).upper() + enum_code = f'{snake_case} = "{enum_member}"\n' + code += indent(enum_code, 4) + code += '\n' + indent(def_to_json, 4) + code += '\n\n' + indent(def_from_json, 4) + + return code + + def generate_class_code(self) -> str: + ''' + Generate a class type. + + Top-level types that are defined as a CDP ``object`` are turned into Python + dataclasses. + ''' + # children = set() + code = dedent(f'''\ + @dataclass + class {self.id}:\n''') + doc = docstring(self.description) + if doc: + code += indent(doc, 4) + '\n' + + # Emit property declarations. These are sorted so that optional + # properties come after required properties, which is required to make + # the dataclass constructor work. + props = list(self.properties) + props.sort(key=operator.attrgetter('optional')) + code += '\n\n'.join(indent(p.generate_decl(), 4) for p in props) + code += '\n\n' + # Emit to_json() method. The properties are sorted in the same order as + # above for readability. + def_to_json = dedent('''\ + def to_json(self) -> T_JSON_DICT: + json: T_JSON_DICT = dict() + ''') + def_to_json += indent('\n'.join(p.generate_to_json() for p in props), 4) + def_to_json += '\n' + def_to_json += indent('return json', 4) + code += indent(def_to_json, 4) + '\n\n' + + # Emit to_json() method. The properties are sorted in the same order as + # above for readability. + def_from_json = dedent(f'''\ + @classmethod + def from_json(cls, json: T_JSON_DICT) -> '{self.id}': + return cls( + ''') + def_from_json += indent( + '\n'.join(p.generate_from_json() for p in props), 8) + def_from_json += '\n' + def_from_json += indent(')', 4) + code += indent(def_from_json, 4) + + # todo we used to return a dict but i'm not sure if that's sitll needed? + # return { + # 'name': self.id, + # 'code': code, + # Don't emit children that live in a different module. We assume that + # modules do not have cyclical dependencies on each other. + # 'children': [c for c in children if '.' not in c], + # } + return code # Todo how to resolve dependencies? # The classes have dependencies on each other, so we have to emit them in @@ -226,7 +433,7 @@ class CdpCommand: returns: typing.List[CdpReturn] @classmethod - def from_json(cls, command): + def from_json(cls, command) -> 'CdpCommand': ''' Instantiate a CDP command from a JSON object. ''' parameters = command.get('parameters', list()) returns = command.get('returns', list()) @@ -391,6 +598,9 @@ def parse(json_path, output_path): domains.append(CdpDomain.from_json(domain)) return domains +###################################################### +## All refactored code is above. Old code is below. ## +###################################################### def get_dependency(cdp_meta): if 'type' in cdp_meta and cdp_meta['type'] != 'array': @@ -419,63 +629,6 @@ def import_dependency(dependency): return 'from ..{} import types as {}\n'.format(module_name, module_name) -def inline_doc(description, indent=0): - ''' - Generate an inline doc, e.g. ``#: This type is a ...`` - - :param str description: - :returns: a string - ''' - if not description: - return '' - - i = ' ' * indent - lines = ['{}#: {}\n'.format(i, l) for l in description.split('\n')] - return ''.join(lines) - - -def docstring(description): - ''' - Generate a docstring from a description. - - :param str description: - ''' - if not description: - return '' - - return dedent("'''\n{}\n'''").format(description) - - -def generate_enum_type(type_): - ''' - Generate an "enum" type. - - Enums are handled by making a python class that contains only class members. - Each class member is upper snaked case, e.g. ``MyTypeClass.MY_ENUM_VALUE`` - and is assigned a string value from the CDP metadata. - - :param dict type_: CDP type metadata - ''' - code = '' - if type_['type'] != 'string': - raise Exception('Unexpected enum type: {!r}'.format(type_)) - code += 'class {}(enum.Enum):\n'.format(type_['id']) - description = type_.get('description') - code += docstring(description) - for enum_member in type_['enum']: - snake_case = inflection.underscore(enum_member).upper() - code += ' {} = "{}"\n'.format(snake_case, enum_member) - code += '\n' - code += ' def to_json(self) -> str:\n' - code += ' return self.value\n' - code += '\n' - code += ' @classmethod\n' - code += " def from_json(cls, json: str) -> '{}':\n".format(type_['id']) - code += ' return cls(json)\n' - code += '\n\n' - return code - - def get_python_type(cdp_type): ''' Generate a name for the Python type that corresponds to the the given CDP @@ -528,117 +681,6 @@ def is_builtin_type(python_type): return python_type in ('bool', 'int', 'dict', 'float', 'str') -def generate_class_type(type_): - ''' - Generate a class type. - - Top-level types that are defined as a CDP ``object`` are turned into Python - dataclasses. - - :param dict type_: CDP type metadata - ''' - description = type_.get('description') - type_name = type_['id'] - children = set() - class_code = '@dataclass\n' - class_code += 'class {}:\n'.format(type_name) - class_code += docstring(description) - from_json = list() - properties = list() - to_json = list() - for prop in type_.get('properties', []): - prop_name = prop['name'] - optional = prop.get('optional', False) - snake_name = inflection.underscore(prop_name) - prop_code = '' - prop_description = prop.get('description') - if prop_description: - prop_code += inline_doc(prop_description, indent=4) - prop_type = get_python_type(prop) - prop_decl = prop_type - if prop_type == type_name: - # If a type refers to itself, e.g. StackTrace has a member - # called ``parent`` that is itself a StackTrace, then the type - # name must be quoted or else Python will not be able to compile - # the module. - prop_decl = "'{}'".format(prop_decl) - elif '$ref' in prop and '.' not in prop_type: - # If the type lives in this module and is not a type that refers - # to itself, then add it to the set of children so that - # inter-class dependencies can be resolved later on. - children.add(prop_type) - if optional: - prop_decl = 'typing.Optional[{}] = None'.format(prop_decl) - prop_code += ' {}: {}\n\n'.format(snake_name, prop_decl) - properties.append((prop_code, optional)) - getter = "json['{}']".format(prop_name) - if 'type' in prop: - if prop['type'] != 'array': - from_json.append((snake_name, "{}".format(getter), prop_name, - optional)) - to_json.append((snake_name, prop_name, optional, - 'self.{}'.format(snake_name))) - elif '$ref' in prop['items']: - subtype = get_python_type(prop['items']) - from_json.append((snake_name, "[{}.from_json(i) for i in {}]".format( - subtype, getter), prop_name, optional)) - to_json.append((snake_name, prop_name, optional, - '[i.to_json() for i in self.{}]'.format(snake_name))) - elif 'type' in prop['items']: - subtype = get_python_type(prop['items']) - from_json.append((snake_name, "[i for i in {}]".format(getter), - prop_name, optional)) - to_json.append((snake_name, prop_name, optional, - '[i for i in self.{}]'.format(snake_name))) - else: - from_json.append((snake_name, "{}.from_json({})".format( - prop_type, getter), prop_name, optional)) - to_json.append((snake_name, prop_name, optional, - 'self.{}.to_json()'.format(snake_name))) - # Sort properties so that optional properties come after required - # properties, otherwise the dataclass will raise an error. - properties.sort(key=operator.itemgetter(1)) - for prop_code, _ in properties: - class_code += prop_code - class_code += ' def to_json(self) -> T_JSON_DICT:\n' - class_code += ' json: T_JSON_DICT = {\n' - for snake_name, prop_name, optional, code in to_json: - if optional: - continue - class_code += " '{}': {},\n".format(prop_name, code) - class_code += ' }\n' - for snake_name, prop_name, optional, code in to_json: - if not optional: - continue - class_code += " if self.{} is not None:\n".format(snake_name) - class_code += " json['{}'] = {}\n".format(prop_name, code) - class_code += ' return json\n' - class_code += '\n' - class_code += ' @classmethod\n' - class_code += " def from_json(cls, json: T_JSON_DICT) -> '{}':\n".format(type_name) - for snake_name, code, prop_name, optional in from_json: - if not optional: - continue - class_code += " {} = {} if '{}' in json else None\n".format( - snake_name, code, prop_name) - class_code += ' return cls(\n' - for snake_name, code, prop_name, optional in from_json: - if optional: - class_code += " {}={},\n".format(snake_name, snake_name) - else: - class_code += " {}={},\n".format(snake_name, code) - class_code += ' )\n' - class_code += '\n' - - return { - 'name': type_name, - 'code': class_code, - # Don't emit children that live in a different module. We assume that - # modules do not have cyclical dependencies on each other. - 'children': [c for c in children if '.' not in c], - } - - def generate_events(domain, events): exports = list() code = '\n' diff --git a/build/test_generate.py b/build/test_generate.py index 6d98ed8..6340a38 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -65,3 +65,125 @@ def __repr__(self): print('EXPECTED:', expected) print('ACTUAL:', actual) assert expected == actual + + +def test_cdp_enum_type(): + json_type = { + "id": "AXValueSourceType", + "description": "Enum of possible property sources.", + "type": "string", + "enum": [ + "attribute", + "implicit", + "style", + "contents", + "placeholder", + "relatedElement" + ] + } + expected = dedent("""\ + class AXValueSourceType(enum.Enum): + ''' + Enum of possible property sources. + ''' + ATTRIBUTE = "attribute" + IMPLICIT = "implicit" + STYLE = "style" + CONTENTS = "contents" + PLACEHOLDER = "placeholder" + RELATED_ELEMENT = "relatedElement" + + def to_json(self) -> str: + return self.value + + @classmethod + def from_json(cls, json: str) -> 'AXValueSourceType': + return cls(json)""") + + type = CdpType.from_json(json_type) + actual = type.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_class_type(): + json_type = { + "id": "AXValue", + "description": "A single computed AX property.", + "type": "object", + "properties": [ + { + "name": "type", + "description": "The type of this value.", + "$ref": "AXValueType" + }, + { + "name": "value", + "description": "The computed value of this property.", + "optional": True, + "type": "any" + }, + { + "name": "relatedNodes", + "description": "One or more related nodes, if applicable.", + "optional": True, + "type": "array", + "items": { + "$ref": "AXRelatedNode" + } + }, + { + "name": "sources", + "description": "The sources which contributed to the computation of this property.", + "optional": True, + "type": "array", + "items": { + "$ref": "AXValueSource" + } + } + ] + } + expected = dedent("""\ + @dataclass + class AXValue: + ''' + A single computed AX property. + ''' + #: The type of this value. + type: 'AXValueType' + + #: The computed value of this property. + value: typing.Optional[typing.Any] = None + + #: One or more related nodes, if applicable. + related_nodes: typing.Optional[typing.List['AXRelatedNode']] = None + + #: The sources which contributed to the computation of this property. + sources: typing.Optional[typing.List['AXValueSource']] = None + + def to_json(self) -> T_JSON_DICT: + json: T_JSON_DICT = dict() + json['type'] = self.type.to_json() + if self.value is not None: + json['value'] = self.value + if self.related_nodes is not None: + json['relatedNodes'] = [i.to_json() for i in self.related_nodes] + if self.sources is not None: + json['sources'] = [i.to_json() for i in self.sources] + return json + + @classmethod + def from_json(cls, json: T_JSON_DICT) -> 'AXValue': + return cls( + type=AXValueType.from_json(json['type']), + value=json['value'] if 'value' in json else None, + relatedNodes=[AXRelatedNode.from_json(i) for i in json['relatedNodes']] if 'relatedNodes' in json else None, + sources=[AXValueSource.from_json(i) for i in json['sources']] if 'sources' in json else None, + )""") + + type = CdpType.from_json(json_type) + actual = type.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual From e077760de71db78c3f977d45089831b6fa7ba4a2 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Tue, 27 Aug 2019 11:54:47 -0400 Subject: [PATCH 007/128] Flesh out the code for generating modules Now that types are implemented, I added some code to the CdpDomain object so that it can generate the code for a module file. (It outputs "TODO" for commands and events, which are not implemented yet.) I didn't write a test for this because it depends on functionality that isn't finished, but also I think we'll notice quickly if the module generation code is broken. (If I'm wrong about this, I'll add a test later on.) --- build/generate.py | 200 ++++++++++++++++++++++++---------------------- 1 file changed, 103 insertions(+), 97 deletions(-) diff --git a/build/generate.py b/build/generate.py index 6886f9d..0fca0e7 100644 --- a/build/generate.py +++ b/build/generate.py @@ -1,5 +1,6 @@ from dataclasses import dataclass from enum import Enum +import itertools import json import logging import operator @@ -15,18 +16,18 @@ logging.basicConfig(level=log_level) logger = logging.getLogger('generate') -shared_header = '''DO NOT EDIT THIS FILE +SHARED_HEADER = '''DO NOT EDIT THIS FILE -This file is generated from the CDP definitions. If you need to make changes, +This file is generated from the CDP specification. If you need to make changes, edit the generator and regenerate all of the modules.''' -init_header = '''\'\'\' +INIT_HEADER = '''\'\'\' {} \'\'\' -'''.format(shared_header) +'''.format(SHARED_HEADER) -module_header = '''\'\'\' +MODULE_HEADER = '''\'\'\' {} Domain: {{}} @@ -38,7 +39,8 @@ import enum import typing -'''.format(shared_header) + +'''.format(SHARED_HEADER) def indent(s: str, n: int): @@ -97,6 +99,7 @@ def ref_to_python(ref: str) -> str: class CdpPrimitiveType(Enum): ''' All of the CDP types that map directly to a Python type annotation. ''' any = 'typing.Any' + array = 'typing.List' boolean = 'bool' integer = 'int' number = 'float' @@ -190,7 +193,7 @@ def generate_to_json(self) -> str: assign = f"json['{self.name}'] = " \ f"[i.to_json() for i in self.{self.py_name}]" else: - raise NotImplemented() + raise NotImplementedError() else: if self.ref: assign = f"json['{self.name}'] = self.{self.py_name}.to_json()" @@ -446,6 +449,11 @@ def from_json(cls, command) -> 'CdpCommand': [CdpReturn.from_json(r) for r in returns], ) + def generate_code(self) -> str: + ''' Generate code for a CDP command. ''' + return 'TODO' + + @dataclass class CdpEvent: ''' A CDP event object. ''' @@ -453,6 +461,10 @@ class CdpEvent: description: str parameters: typing.List[CdpParameter] + def generate_code(self) -> str: + ''' Generate code for a CDP event. ''' + return 'TODO' + @dataclass class CdpDomain: @@ -485,100 +497,91 @@ def from_json(cls, domain): list(), ) - def generate_code(self): - ''' - Generate a Python module for a given CDP domain. - - :param dict domain: domain schema - :param Path output_path: a directory path to create the module in - :returns: module name and a list of exported names - ''' - logger.info('Generating module: %s → %s.py', self.domain, self.module) - return 'foobar' - name = domain['domain'] - experimental = domain.get('experimental', False) + def generate_code(self) -> str: + ''' Generate the Python module code for a given CDP domain. ''' + code = MODULE_HEADER.format(self.domain, self.experimental) + item_iter = itertools.chain( + iter(self.types), + iter(self.commands), + iter(self.events), + ) + code += '\n\n\n'.join(item.generate_code() for item in item_iter) + return code + # todo update dependencies # The dependencies listed in the JSON don't match the actual dependencies # encountered when building the types. So we ignore the declared # dependencies and compute it ourself. - type_dependencies = set() - domain_types = domain.get('types', list()) - for type_ in domain_types: - for prop in type_.get('properties', list()): - dependency = get_dependency(prop) - if dependency: - type_dependencies.add(dependency) - if type_dependencies: - logger.debug('Computed type_dependencies: %s', ','.join( - type_dependencies)) - - event_dependencies = set() - domain_events = domain.get('events', list()) - for event in domain_events: - for param in event.get('parameters', list()): - dependency = get_dependency(param) - if dependency: - event_dependencies.add(dependency) - if event_dependencies: - logger.debug('Computed event_dependencies: %s', ','.join( - event_dependencies)) - - command_dependencies = set() - domain_commands = domain.get('commands', list()) - for command in domain_commands: - for param in command.get('parameters', list()): - dependency = get_dependency(param) - if dependency: - command_dependencies.add(dependency) - for return_ in command.get('returns', list()): - dependency = get_dependency(return_) - if dependency: - command_dependencies.add(dependency) - if command_dependencies: - logger.debug('Computed command_dependencies: %s', ','.join( - command_dependencies)) - - # Generate code for this module. - module_path = output_path / module_name - module_path.mkdir(parents=True, exist_ok=True) - init_path = module_path / '__init__.py' - with init_path.open('w'): - # Zero out this file - pass - - types_path = module_path / 'types.py' - with types_path.open('w') as types_file: - types_file.write(module_header.format(module_name, experimental)) - for dependency in sorted(type_dependencies): - types_file.write(import_dependency(dependency)) - if type_dependencies: - types_file.write('\n') - type_exports, type_code = generate_types(domain_types) - types_file.write(type_code) - - events_path = module_path / 'events.py' - with events_path.open('w') as events_file: - events_file.write(module_header.format(module_name, experimental)) - events_file.write('from .types import *\n') - for dependency in sorted(event_dependencies): - events_file.write(import_dependency(dependency)) - if event_dependencies: - events_file.write('\n') - event_exports, event_code = generate_events(name, domain_events) - events_file.write(event_code) - - commands_path = module_path / 'commands.py' - with commands_path.open('w') as commands_file: - commands_file.write(module_header.format(module_name, experimental)) - commands_file.write('from .types import *\n') - for dependency in sorted(command_dependencies): - commands_file.write(import_dependency(dependency)) - if command_dependencies: - commands_file.write('\n') - command_exports, command_code = generate_commands(name, domain_commands) - commands_file.write(command_code) - - return module_name, type_exports, event_exports, command_exports + # type_dependencies = set() + # domain_types = domain.get('types', list()) + # for type_ in domain_types: + # for prop in type_.get('properties', list()): + # dependency = get_dependency(prop) + # if dependency: + # type_dependencies.add(dependency) + # if type_dependencies: + # logger.debug('Computed type_dependencies: %s', ','.join( + # type_dependencies)) + # + # event_dependencies = set() + # domain_events = domain.get('events', list()) + # for event in domain_events: + # for param in event.get('parameters', list()): + # dependency = get_dependency(param) + # if dependency: + # event_dependencies.add(dependency) + # if event_dependencies: + # logger.debug('Computed event_dependencies: %s', ','.join( + # event_dependencies)) + # + # command_dependencies = set() + # domain_commands = domain.get('commands', list()) + # for command in domain_commands: + # for param in command.get('parameters', list()): + # dependency = get_dependency(param) + # if dependency: + # command_dependencies.add(dependency) + # for return_ in command.get('returns', list()): + # dependency = get_dependency(return_) + # if dependency: + # command_dependencies.add(dependency) + # if command_dependencies: + # logger.debug('Computed command_dependencies: %s', ','.join( + # command_dependencies)) + + # types_path = module_path / 'types.py' + # with types_path.open('w') as types_file: + # types_file.write(module_header.format(module_name, self.experimental)) + # for dependency in sorted(type_dependencies): + # types_file.write(import_dependency(dependency)) + # if type_dependencies: + # types_file.write('\n') + # type_exports, type_code = generate_types(domain_types) + # types_file.write(type_code) + # + # events_path = module_path / 'events.py' + # with events_path.open('w') as events_file: + # events_file.write(module_header.format(module_name, self.experimental)) + # events_file.write('from .types import *\n') + # for dependency in sorted(event_dependencies): + # events_file.write(import_dependency(dependency)) + # if event_dependencies: + # events_file.write('\n') + # event_exports, event_code = generate_events(self.domain, domain_events) + # events_file.write(event_code) + # + # commands_path = module_path / 'commands.py' + # with commands_path.open('w') as commands_file: + # commands_file.write(module_header.format(module_name, self.experimental)) + # commands_file.write('from .types import *\n') + # for dependency in sorted(command_dependencies): + # commands_file.write(import_dependency(dependency)) + # if command_dependencies: + # commands_file.write('\n') + # command_exports, command_code = generate_commands(self.domain, domain_commands) + # commands_file.write(command_code) + + # return module_name, type_exports, event_exports, command_exports def parse(json_path, output_path): @@ -913,8 +916,11 @@ def main(): for json_path in json_paths: logger.info('Parsing JSON file %s', json_path) domains.extend(parse(json_path, output_path)) + domains.sort(key=operator.attrgetter('domain')) for domain in domains: + logger.info('Generating module: %s → %s.py', domain.domain, + domain.module) module_path = output_path / f'{domain.module}.py' with module_path.open('w') as module_file: module_file.write(domain.generate_code()) From 9f1f84a5df77d2404b0b9b79383423ff0d80bd48 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Tue, 27 Aug 2019 15:11:25 -0400 Subject: [PATCH 008/128] Implement CDP commands I left a few parts of this incomplete, but the basic structure for generating code for CDP commands is in place and covered by a test. --- build/generate.py | 142 +++++++++++++++++++++++++++++++++-------- build/test_generate.py | 84 +++++++++++++++++++++++- 2 files changed, 197 insertions(+), 29 deletions(-) diff --git a/build/generate.py b/build/generate.py index 0fca0e7..43f365c 100644 --- a/build/generate.py +++ b/build/generate.py @@ -185,23 +185,25 @@ def generate_decl(self) -> str: code += ' = None' return code - def generate_to_json(self) -> str: - ''' Generate the code that exports this property to a JSON dict named - ``json``. ''' + def generate_to_json(self, dict_: str, use_self: bool=True) -> str: + ''' Generate the code that exports this property to the specified JSON + dict. ''' + self_ref = 'self.' if use_self else '' if self.items: if self.items.ref: - assign = f"json['{self.name}'] = " \ - f"[i.to_json() for i in self.{self.py_name}]" + assign = f"{dict_}['{self.name}'] = " \ + f"[i.to_json() for i in {self_ref}{self.py_name}]" else: raise NotImplementedError() else: if self.ref: - assign = f"json['{self.name}'] = self.{self.py_name}.to_json()" + assign = f"{dict_}['{self.name}'] = " \ + f"{self_ref}{self.py_name}.to_json()" else: - assign = f"json['{self.name}'] = self.{self.py_name}" + assign = f"{dict_}['{self.name}'] = {self_ref}{self.py_name}" if self.optional: code = dedent(f'''\ - if self.{self.py_name} is not None: + if {self_ref}{self.py_name} is not None: {assign}''') else: code = assign @@ -227,7 +229,7 @@ def generate_from_json(self) -> str: expr = f"json['{self.name}']" if self.optional: expr = f"{expr} if '{self.name}' in json else None" - return f'{self.name}={expr},' + return expr @dataclass @@ -351,7 +353,8 @@ class {self.id}:\n''') def to_json(self) -> T_JSON_DICT: json: T_JSON_DICT = dict() ''') - def_to_json += indent('\n'.join(p.generate_to_json() for p in props), 4) + assigns = (p.generate_to_json(dict_='json') for p in props) + def_to_json += indent('\n'.join(assigns), 4) def_to_json += '\n' def_to_json += indent('return json', 4) code += indent(def_to_json, 4) + '\n\n' @@ -363,13 +366,13 @@ def to_json(self) -> T_JSON_DICT: def from_json(cls, json: T_JSON_DICT) -> '{self.id}': return cls( ''') - def_from_json += indent( - '\n'.join(p.generate_from_json() for p in props), 8) + def_from_json += indent('\n'.join(f'{p.name}={p.generate_from_json()},' + for p in self.properties), 8) def_from_json += '\n' def_from_json += indent(')', 4) code += indent(def_from_json, 4) - # todo we used to return a dict but i'm not sure if that's sitll needed? + # todo we used to return a dict but i'm not sure if that's still needed? # return { # 'name': self.id, # 'code': code, @@ -407,23 +410,48 @@ def from_json(cls, json: T_JSON_DICT) -> '{self.id}': class CdpParameter(CdpProperty): - ''' - A parameter to a CDP command. + ''' A parameter to a CDP command. ''' + def generate_code(self) -> str: + ''' Generate the code for a parameter in a function call. ''' + if self.ref: + py_type = "'{}'".format(ref_to_python(self.ref)) + else: + py_type = CdpPrimitiveType[self.type].value + if self.optional: + py_type = f'typing.Optional[{py_type}]' + code = f"{self.py_name}: {py_type}" + if self.optional: + code += ' = None' + return code - This is an empty subclass of CdpProperty because they seem to share the same - behavior, but I want to allow the flexibility to change the behavior later - on. - ''' + def generate_doc(self) -> str: + ''' Generate the docstring for this parameter. ''' + desc = self.description.replace('`', '``') + return f':param {self.py_name}: {desc}' class CdpReturn(CdpProperty): - ''' - A return value from a CDP command. + ''' A return value from a CDP command. ''' + @property + def py_annotation(self): + if self.items: + if self.items.ref: + py_ref = ref_to_python(self.items.ref) + ann = f"typing.List['{py_ref}']" + else: + raise NotImplementedError() + else: + if self.ref: + raise NotImplementedError() + else: + raise NotImplementedError() - This is an empty subclass of CdpProperty because they seem to share the same - behavior, but I want to allow the flexibility to change the behavior later - on. - ''' + return ann + + def generate_doc(self): + ''' Generate the docstring for this return. ''' + desc = self.description.replace('`', '``') + return f':returns: {desc}' @dataclass @@ -434,9 +462,15 @@ class CdpCommand: experimental: bool parameters: typing.List[CdpParameter] returns: typing.List[CdpReturn] + domain: str + + @property + def py_name(self): + ''' Get a Python name for this command. ''' + return inflection.underscore(self.name) @classmethod - def from_json(cls, command) -> 'CdpCommand': + def from_json(cls, command, domain) -> 'CdpCommand': ''' Instantiate a CDP command from a JSON object. ''' parameters = command.get('parameters', list()) returns = command.get('returns', list()) @@ -447,11 +481,62 @@ def from_json(cls, command) -> 'CdpCommand': command.get('experimental', False), [CdpParameter.from_json(p) for p in parameters], [CdpReturn.from_json(r) for r in returns], + domain, ) def generate_code(self) -> str: ''' Generate code for a CDP command. ''' - return 'TODO' + # Generate the function header + if len(self.returns) == 0: + raise NotImplementedError() + elif len(self.returns) == 1: + ret_type = self.returns[0].py_annotation + else: + raise NotImplementedError() + ret_type = f"typing.Generator[T_JSON_DICT,T_JSON_DICT,{ret_type}]" + code = f'def {self.py_name}(\n' + code += indent( + ',\n'.join(p.generate_code() for p in self.parameters), 8) + code += '\n' + code += indent(f') -> {ret_type}:\n', 4) + + # Generate the docstring + if self.description: + doc = self.description + '\n\n' + else: + doc = '' + doc += '\n'.join(p.generate_doc() for p in self.parameters) + if len(self.returns) == 1: + doc += '\n' + doc += self.returns[0].generate_doc() + elif len(self.returns) > 1: + doc += '\n' + raise NotImplementedError() + if doc: + code += indent(docstring(doc), 4) + code += '\n' + + # Generate the function body + code += indent('params: T_JSON_DICT = dict()', 4) + code += '\n' + assigns = (p.generate_to_json(dict_='params', use_self=False) + for p in self.parameters) + code += indent('\n'.join(assigns), 4) + code += '\n' + yield_code = dedent(f'''\ + cmd_dict: T_JSON_DICT = {{ + 'method': '{self.domain}.{self.name}', + 'params': params, + }} + json = yield cmd_dict''') + code += indent(yield_code, 4) + code += '\n' + if len(self.returns) == 0: + raise NotImplementedError() + else: + expr = ', '.join(r.generate_from_json() for r in self.returns) + code += indent(f'return {expr}', 4) + return code @dataclass @@ -493,7 +578,8 @@ def from_json(cls, domain): domain.get('experimental', False), domain.get('dependencies', list()), [CdpType.from_json(type) for type in types], - [CdpCommand.from_json(command) for command in commands], + [CdpCommand.from_json(command, domain['domain']) + for command in commands], list(), ) diff --git a/build/test_generate.py b/build/test_generate.py index 6340a38..70ba509 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -12,7 +12,7 @@ from textwrap import dedent -from generate import CdpType, docstring +from generate import CdpCommand, CdpType, docstring def test_docstring(): @@ -187,3 +187,85 @@ def from_json(cls, json: T_JSON_DICT) -> 'AXValue': print('EXPECTED:', expected) print('ACTUAL:', actual) assert expected == actual + + +def test_cdp_command(): + json_cmd = { + "name": "getPartialAXTree", + "description": "Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists.", + "experimental": True, + "parameters": [ + { + "name": "nodeId", + "description": "Identifier of the node to get the partial accessibility tree for.", + "optional": True, + "$ref": "DOM.NodeId" + }, + { + "name": "backendNodeId", + "description": "Identifier of the backend node to get the partial accessibility tree for.", + "optional": True, + "$ref": "DOM.BackendNodeId" + }, + { + "name": "objectId", + "description": "JavaScript object id of the node wrapper to get the partial accessibility tree for.", + "optional": True, + "$ref": "Runtime.RemoteObjectId" + }, + { + "name": "fetchRelatives", + "description": "Whether to fetch this nodes ancestors, siblings and children. Defaults to true.", + "optional": True, + "type": "boolean" + } + ], + "returns": [ + { + "name": "nodes", + "description": "The `Accessibility.AXNode` for this DOM node, if it exists, plus its ancestors, siblings and\nchildren, if requested.", + "type": "array", + "items": { + "$ref": "AXNode" + } + } + ] + } + expected = dedent("""\ + def get_partial_ax_tree( + node_id: typing.Optional['dom.NodeId'] = None, + backend_node_id: typing.Optional['dom.BackendNodeId'] = None, + object_id: typing.Optional['runtime.RemoteObjectId'] = None, + fetch_relatives: typing.Optional[bool] = None + ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.List['AXNode']]: + ''' + Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. + + :param node_id: Identifier of the node to get the partial accessibility tree for. + :param backend_node_id: Identifier of the backend node to get the partial accessibility tree for. + :param object_id: JavaScript object id of the node wrapper to get the partial accessibility tree for. + :param fetch_relatives: Whether to fetch this nodes ancestors, siblings and children. Defaults to true. + :returns: The ``Accessibility.AXNode`` for this DOM node, if it exists, plus its ancestors, siblings and + children, if requested. + ''' + params: T_JSON_DICT = dict() + if node_id is not None: + params['nodeId'] = node_id.to_json() + if backend_node_id is not None: + params['backendNodeId'] = backend_node_id.to_json() + if object_id is not None: + params['objectId'] = object_id.to_json() + if fetch_relatives is not None: + params['fetchRelatives'] = fetch_relatives + cmd_dict: T_JSON_DICT = { + 'method': 'Accessibility.getPartialAXTree', + 'params': params, + } + json = yield cmd_dict + return [AXNode.from_json(i) for i in json['nodes']]""") + + cmd = CdpCommand.from_json(json_cmd, 'Accessibility') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual From 35f623e1a740dc465d1ed8d3ee81b765cfecfe1c Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Wed, 28 Aug 2019 08:54:46 -0400 Subject: [PATCH 009/128] Implement CDP events As with the earlier commits, events are not 100% implemented but the majority of the code is finished here and covered by a new test. --- build/generate.py | 82 ++++++++++++++++++++++++++++++++++++------ build/test_generate.py | 44 ++++++++++++++++++++++- 2 files changed, 115 insertions(+), 11 deletions(-) diff --git a/build/generate.py b/build/generate.py index 43f365c..7696cab 100644 --- a/build/generate.py +++ b/build/generate.py @@ -209,7 +209,7 @@ def generate_to_json(self, dict_: str, use_self: bool=True) -> str: code = assign return code - def generate_from_json(self) -> str: + def generate_from_json(self, dict_='json') -> str: ''' Generate the code that creates an instance from a JSON dict named ``json``. ''' # todo this is one of the few places where a real dependency is created @@ -218,17 +218,17 @@ def generate_from_json(self) -> str: if self.items: if self.items.ref: py_ref = ref_to_python(self.items.ref) - expr = f"[{py_ref}.from_json(i) for i in json['{self.name}']]" + expr = f"[{py_ref}.from_json(i) for i in {dict_}['{self.name}']]" else: raise NotImplemented() else: if self.ref: py_ref = ref_to_python(self.ref) - expr = f"{py_ref}.from_json(json['{self.name}'])" + expr = f"{py_ref}.from_json({dict_}['{self.name}'])" else: - expr = f"json['{self.name}']" + expr = f"{dict_}['{self.name}']" if self.optional: - expr = f"{expr} if '{self.name}' in json else None" + expr = f"{expr} if '{self.name}' in {dict_} else None" return expr @@ -424,11 +424,32 @@ def generate_code(self) -> str: code += ' = None' return code + def generate_decl(self) -> str: + ''' Generate the declaration for this parameter. ''' + if self.description: + code = inline_doc(self.description) + code += '\n' + else: + code = '' + code += f'{self.py_name}: {self.py_annotation}' + return code + def generate_doc(self) -> str: ''' Generate the docstring for this parameter. ''' desc = self.description.replace('`', '``') return f':param {self.py_name}: {desc}' + def generate_from_json(self, dict_) -> str: + ''' + Generate the code to instantiate this parameter from a JSON dict. + ''' + code = super().generate_from_json(dict_) + try: + prim = CdpPrimitiveType[self.type].value + code = f'{prim}({code})' + except KeyError: + pass + return f'{self.py_name}={code}' class CdpReturn(CdpProperty): ''' A return value from a CDP command. ''' @@ -545,10 +566,50 @@ class CdpEvent: name: str description: str parameters: typing.List[CdpParameter] + domain: str + + @property + def py_name(self): + ''' Return the Python class name for this event. ''' + return inflection.camelize(self.name, uppercase_first_letter=True) + + @classmethod + def from_json(cls, json: dict, domain: str): + ''' Create a new CDP event instance from a JSON dict. ''' + return cls(json['name'], json.get('description'), + [CdpParameter.from_json(p) for p in json['parameters']], domain) def generate_code(self) -> str: ''' Generate code for a CDP event. ''' - return 'TODO' + code = dedent(f'''\ + @dataclass + class {self.py_name}:''') + code += '\n' + if self.description: + code += indent(docstring(self.description), 4) + code += '\n' + code += indent( + '\n'.join(p.generate_decl() for p in self.parameters), 4) + code += '\n\n' + internal = dedent(f'''\ + # These fields are used for internal purposes and are not part of CDP + _domain = '{self.domain}' + _method = '{self.name}' + ''') + code += indent(internal, 4) + code += '\n' + def_from_json = dedent(f'''\ + @classmethod + def from_json(cls, json: T_JSON_DICT) -> '{self.py_name}': + return cls( + ''') + code += indent(def_from_json, 4) + from_json = ',\n'.join(p.generate_from_json(dict_='json') + for p in self.parameters) + code += indent(from_json, 12) + code += '\n' + code += indent(')', 8) + return code @dataclass @@ -567,20 +628,21 @@ def module(self): return inflection.underscore(self.domain) @classmethod - def from_json(cls, domain): + def from_json(cls, domain: dict): ''' Instantiate a CDP domain from a JSON object. ''' types = domain.get('types', list()) commands = domain.get('commands', list()) events = domain.get('events', list()) + domain_name = domain['domain'] return cls( - domain['domain'], + domain_name, domain.get('experimental', False), domain.get('dependencies', list()), [CdpType.from_json(type) for type in types], - [CdpCommand.from_json(command, domain['domain']) + [CdpCommand.from_json(command, domain_name) for command in commands], - list(), + [CdpEvent.from_json(event, domain_name) for event in events] ) def generate_code(self) -> str: diff --git a/build/test_generate.py b/build/test_generate.py index 70ba509..17856ab 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -12,7 +12,7 @@ from textwrap import dedent -from generate import CdpCommand, CdpType, docstring +from generate import CdpCommand, CdpEvent, CdpType, docstring def test_docstring(): @@ -269,3 +269,45 @@ def get_partial_ax_tree( print('EXPECTED:', expected) print('ACTUAL:', actual) assert expected == actual + + +def test_cdp_event(): + json_cmd = { + "name": "recordingStateChanged", + "description": "Called when the recording state for the service has been updated.", + "parameters": [ + { + "name": "isRecording", + "type": "boolean" + }, + { + "name": "service", + "$ref": "ServiceName" + } + ] + } + expected = dedent("""\ + @dataclass + class RecordingStateChanged: + ''' + Called when the recording state for the service has been updated. + ''' + is_recording: bool + service: 'ServiceName' + + # These fields are used for internal purposes and are not part of CDP + _domain = 'BackgroundService' + _method = 'recordingStateChanged' + + @classmethod + def from_json(cls, json: T_JSON_DICT) -> 'RecordingStateChanged': + return cls( + is_recording=bool(json['isRecording']), + service=ServiceName.from_json(json['service']) + )""") + + cmd = CdpEvent.from_json(json_cmd, 'BackgroundService') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual From d1a5639c1e35471b1673fbccfb6a59a92bfca334 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Wed, 28 Aug 2019 12:03:49 -0400 Subject: [PATCH 010/128] Filled in some edge cases I'm finding unimplemented edge cases by raising NotImplementedErrors at certain branches and then running the generate.py script and seeing where it breaks. I've implemented 5 new edge cases here along with a test for each one. --- build/generate.py | 152 +++++++++++++++---------- build/test_generate.py | 247 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 339 insertions(+), 60 deletions(-) diff --git a/build/generate.py b/build/generate.py index 7696cab..fe183a6 100644 --- a/build/generate.py +++ b/build/generate.py @@ -97,9 +97,7 @@ def ref_to_python(ref: str) -> str: class CdpPrimitiveType(Enum): - ''' All of the CDP types that map directly to a Python type annotation. ''' - any = 'typing.Any' - array = 'typing.List' + ''' All of the CDP types that map directly to a Python type. ''' boolean = 'bool' integer = 'int' number = 'float' @@ -113,16 +111,6 @@ class CdpItemType: type: str ref: str - @property - def py_annotation(self) -> str: - if self.type: - annotation = CdpPrimitiveType[self.type].value - else: - py_ref = ref_to_python(self.ref) - annotation = f"'{py_ref}'" - - return annotation - @classmethod def from_json(cls, type) -> 'CdpItemType': return cls(type.get('type'), type.get('$ref')) @@ -147,13 +135,21 @@ def py_name(self) -> str: @property def py_annotation(self) -> str: ''' This property's Python type annotation. ''' - if self.type == 'array': - ann = f'typing.List[{self.items.py_annotation}]' - elif self.ref: - py_ref = ref_to_python(self.ref) - ann = f"'{py_ref}'" + if self.items: + if self.items.ref: + py_ref = ref_to_python(self.items.ref) + ann = "typing.List['{}']".format(py_ref) + else: + ann = 'typing.List[{}]'.format( + CdpPrimitiveType[self.type].value) else: - ann = CdpPrimitiveType[self.type].value + if self.ref: + py_ref = ref_to_python(self.ref) + ann = f"'{py_ref}'" + elif self.type == 'any': + ann = 'typing.Any' + else: + ann = CdpPrimitiveType[self.type].value if self.optional: ann = f'typing.Optional[{ann}]' return ann @@ -189,18 +185,17 @@ def generate_to_json(self, dict_: str, use_self: bool=True) -> str: ''' Generate the code that exports this property to the specified JSON dict. ''' self_ref = 'self.' if use_self else '' + assign = f"{dict_}['{self.name}'] = " if self.items: if self.items.ref: - assign = f"{dict_}['{self.name}'] = " \ - f"[i.to_json() for i in {self_ref}{self.py_name}]" + assign += f"[i.to_json() for i in {self_ref}{self.py_name}]" else: - raise NotImplementedError() + assign += f"[i for i in {self_ref}{self.py_name}]" else: if self.ref: - assign = f"{dict_}['{self.name}'] = " \ - f"{self_ref}{self.py_name}.to_json()" + assign += f"{self_ref}{self.py_name}.to_json()" else: - assign = f"{dict_}['{self.name}'] = {self_ref}{self.py_name}" + assign += f"{self_ref}{self.py_name}" if self.optional: code = dedent(f'''\ if {self_ref}{self.py_name} is not None: @@ -413,10 +408,17 @@ class CdpParameter(CdpProperty): ''' A parameter to a CDP command. ''' def generate_code(self) -> str: ''' Generate the code for a parameter in a function call. ''' - if self.ref: - py_type = "'{}'".format(ref_to_python(self.ref)) + if self.items: + if self.ref: + raise NotImplementedError(self) + else: + nested_type = CdpPrimitiveType[self.items.type].value + py_type = f'typing.List[{nested_type}]' else: - py_type = CdpPrimitiveType[self.type].value + if self.ref: + py_type = "'{}'".format(ref_to_python(self.ref)) + else: + py_type = CdpPrimitiveType[self.type].value if self.optional: py_type = f'typing.Optional[{py_type}]' code = f"{self.py_name}: {py_type}" @@ -451,6 +453,7 @@ def generate_from_json(self, dict_) -> str: pass return f'{self.py_name}={code}' + class CdpReturn(CdpProperty): ''' A return value from a CDP command. ''' @property @@ -460,19 +463,35 @@ def py_annotation(self): py_ref = ref_to_python(self.items.ref) ann = f"typing.List['{py_ref}']" else: - raise NotImplementedError() + raise NotImplementedError(self) else: if self.ref: - raise NotImplementedError() + py_ref = ref_to_python(self.ref) + ann = f"'{py_ref}'" else: - raise NotImplementedError() + ann = CdpPrimitiveType[self.type].value return ann def generate_doc(self): ''' Generate the docstring for this return. ''' - desc = self.description.replace('`', '``') - return f':returns: {desc}' + if self.description: + doc = self.description.replace('`', '``') + if self.optional: + doc = f'(Optional) {doc}' + else: + doc = '' + return doc + + def generate_return(self, dict_): + ''' Generate code for returning this value. ''' + code = super().generate_from_json() + try: + type_ = CdpPrimitiveType[self.type].value + code = f'{type_}({code})' + except: + pass + return code @dataclass @@ -509,53 +528,65 @@ def generate_code(self) -> str: ''' Generate code for a CDP command. ''' # Generate the function header if len(self.returns) == 0: - raise NotImplementedError() + ret_type = 'None' elif len(self.returns) == 1: ret_type = self.returns[0].py_annotation else: - raise NotImplementedError() + nested_types = ', '.join(r.py_annotation for r in self.returns) + ret_type = f'typing.Tuple[{nested_types}]' ret_type = f"typing.Generator[T_JSON_DICT,T_JSON_DICT,{ret_type}]" - code = f'def {self.py_name}(\n' - code += indent( - ',\n'.join(p.generate_code() for p in self.parameters), 8) - code += '\n' - code += indent(f') -> {ret_type}:\n', 4) + code = f'def {self.py_name}(' + ret = f') -> {ret_type}:\n' + if self.parameters: + code += '\n' + code += indent( + ',\n'.join(p.generate_code() for p in self.parameters), 8) + code += '\n' + code += indent(ret, 4) + else: + code += ret # Generate the docstring if self.description: - doc = self.description + '\n\n' + doc = self.description else: doc = '' + if self.parameters and doc: + doc += '\n\n' doc += '\n'.join(p.generate_doc() for p in self.parameters) if len(self.returns) == 1: doc += '\n' - doc += self.returns[0].generate_doc() + ret_doc = self.returns[0].generate_doc() + doc += f':returns: {ret_doc}' elif len(self.returns) > 1: doc += '\n' - raise NotImplementedError() + doc += ':returns: a tuple with the following items:\n' + ret_docs = '\n'.join(f'{i}. {r.name}: {r.generate_doc()}' for i, r + in enumerate(self.returns)) + doc += indent(ret_docs, 4) if doc: code += indent(docstring(doc), 4) - code += '\n' # Generate the function body - code += indent('params: T_JSON_DICT = dict()', 4) - code += '\n' + if self.parameters: + code += '\n' + code += indent('params: T_JSON_DICT = dict()', 4) + code += '\n' assigns = (p.generate_to_json(dict_='params', use_self=False) for p in self.parameters) code += indent('\n'.join(assigns), 4) code += '\n' - yield_code = dedent(f'''\ - cmd_dict: T_JSON_DICT = {{ - 'method': '{self.domain}.{self.name}', - 'params': params, - }} - json = yield cmd_dict''') - code += indent(yield_code, 4) - code += '\n' + code += indent('cmd_dict: T_JSON_DICT = {\n', 4) + code += indent(f"'method': '{self.domain}.{self.name}',\n", 8) + if self.parameters: + code += indent("'params': params,\n", 8) + code += indent('}\n', 4) + code += indent('json = yield cmd_dict', 4) if len(self.returns) == 0: - raise NotImplementedError() + pass else: - expr = ', '.join(r.generate_from_json() for r in self.returns) + code += '\n' + expr = ', '.join(r.generate_return(dict_='json') for r in self.returns) code += indent(f'return {expr}', 4) return code @@ -576,8 +607,12 @@ def py_name(self): @classmethod def from_json(cls, json: dict, domain: str): ''' Create a new CDP event instance from a JSON dict. ''' - return cls(json['name'], json.get('description'), - [CdpParameter.from_json(p) for p in json['parameters']], domain) + return cls( + json['name'], + json.get('description'), + [CdpParameter.from_json(p) for p in json.get('parameters', list())], + domain + ) def generate_code(self) -> str: ''' Generate code for a CDP event. ''' @@ -654,6 +689,7 @@ def generate_code(self) -> str: iter(self.events), ) code += '\n\n\n'.join(item.generate_code() for item in item_iter) + code += '\n' return code # todo update dependencies diff --git a/build/test_generate.py b/build/test_generate.py index 17856ab..1500dc1 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -271,8 +271,251 @@ def get_partial_ax_tree( assert expected == actual -def test_cdp_event(): +def test_cdp_command_no_params_or_returns(): + json_cmd = { + "name": "disable", + "description": "Disables the accessibility domain." + } + expected = dedent("""\ + def disable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: + ''' + Disables the accessibility domain. + ''' + cmd_dict: T_JSON_DICT = { + 'method': 'Accessibility.disable', + } + json = yield cmd_dict""") + + cmd = CdpCommand.from_json(json_cmd, 'Accessibility') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + +def test_cdp_command_return_primitive(): + json_cmd = { + "name": "getCurrentTime", + "description": "Returns the current time of the an animation.", + "parameters": [ + { + "name": "id", + "description": "Id of animation.", + "type": "string" + } + ], + "returns": [ + { + "name": "currentTime", + "description": "Current time of the page.", + "type": "number" + } + ] + } + expected = dedent("""\ + def get_current_time( + id: str + ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,float]: + ''' + Returns the current time of the an animation. + + :param id: Id of animation. + :returns: Current time of the page. + ''' + params: T_JSON_DICT = dict() + params['id'] = id + cmd_dict: T_JSON_DICT = { + 'method': 'Animation.getCurrentTime', + 'params': params, + } + json = yield cmd_dict + return float(json['currentTime'])""") + + cmd = CdpCommand.from_json(json_cmd, 'Animation') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_command_array_parameter(): + json_cmd = { + "name": "releaseAnimations", + "description": "Releases a set of animations to no longer be manipulated.", + "parameters": [ + { + "name": "animations", + "description": "List of animation ids to seek.", + "type": "array", + "items": { + "type": "string" + } + } + ] + } + expected = dedent("""\ + def release_animations( + animations: typing.List[str] + ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: + ''' + Releases a set of animations to no longer be manipulated. + + :param animations: List of animation ids to seek. + ''' + params: T_JSON_DICT = dict() + params['animations'] = [i for i in animations] + cmd_dict: T_JSON_DICT = { + 'method': 'Animation.releaseAnimations', + 'params': params, + } + json = yield cmd_dict""") + + cmd = CdpCommand.from_json(json_cmd, 'Animation') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_command_ref_parameter(): json_cmd = { + "name": "resolveAnimation", + "description": "Gets the remote object of the Animation.", + "parameters": [ + { + "name": "animationId", + "description": "Animation id.", + "type": "string" + } + ], + "returns": [ + { + "name": "remoteObject", + "description": "Corresponding remote object.", + "$ref": "Runtime.RemoteObject" + } + ] + } + expected = dedent("""\ + def resolve_animation( + animation_id: str + ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,'runtime.RemoteObject']: + ''' + Gets the remote object of the Animation. + + :param animation_id: Animation id. + :returns: Corresponding remote object. + ''' + params: T_JSON_DICT = dict() + params['animationId'] = animation_id + cmd_dict: T_JSON_DICT = { + 'method': 'Animation.resolveAnimation', + 'params': params, + } + json = yield cmd_dict + return runtime.RemoteObject.from_json(json['remoteObject'])""") + + cmd = CdpCommand.from_json(json_cmd, 'Animation') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_command_multiple_return(): + json_cmd = { + "name": "getEncodedResponse", + "description": "Returns the response body and size if it were re-encoded with the specified settings. Only\napplies to images.", + "parameters": [ + { + "name": "requestId", + "description": "Identifier of the network request to get content for.", + "$ref": "Network.RequestId" + }, + { + "name": "encoding", + "description": "The encoding to use.", + "type": "string", + "enum": [ + "webp", + "jpeg", + "png" + ] + }, + { + "name": "quality", + "description": "The quality of the encoding (0-1). (defaults to 1)", + "optional": True, + "type": "number" + }, + { + "name": "sizeOnly", + "description": "Whether to only return the size information (defaults to false).", + "optional": True, + "type": "boolean" + } + ], + "returns": [ + { + "name": "body", + "description": "The encoded body as a base64 string. Omitted if sizeOnly is true.", + "optional": True, + "type": "string" + }, + { + "name": "originalSize", + "description": "Size before re-encoding.", + "type": "integer" + }, + { + "name": "encodedSize", + "description": "Size after re-encoding.", + "type": "integer" + } + ] + } + expected = dedent("""\ + def get_encoded_response( + request_id: 'network.RequestId', + encoding: str, + quality: typing.Optional[float] = None, + size_only: typing.Optional[bool] = None + ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.Tuple[str, int, int]]: + ''' + Returns the response body and size if it were re-encoded with the specified settings. Only + applies to images. + + :param request_id: Identifier of the network request to get content for. + :param encoding: The encoding to use. + :param quality: The quality of the encoding (0-1). (defaults to 1) + :param size_only: Whether to only return the size information (defaults to false). + :returns: a tuple with the following items: + 0. body: (Optional) The encoded body as a base64 string. Omitted if sizeOnly is true. + 1. originalSize: Size before re-encoding. + 2. encodedSize: Size after re-encoding. + ''' + params: T_JSON_DICT = dict() + params['requestId'] = request_id.to_json() + params['encoding'] = encoding + if quality is not None: + params['quality'] = quality + if size_only is not None: + params['sizeOnly'] = size_only + cmd_dict: T_JSON_DICT = { + 'method': 'Audits.getEncodedResponse', + 'params': params, + } + json = yield cmd_dict + return str(json['body'] if 'body' in json else None), int(json['originalSize']), int(json['encodedSize'])""") + + cmd = CdpCommand.from_json(json_cmd, 'Audits') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_event(): + json_event = { "name": "recordingStateChanged", "description": "Called when the recording state for the service has been updated.", "parameters": [ @@ -306,7 +549,7 @@ def from_json(cls, json: T_JSON_DICT) -> 'RecordingStateChanged': service=ServiceName.from_json(json['service']) )""") - cmd = CdpEvent.from_json(json_cmd, 'BackgroundService') + cmd = CdpEvent.from_json(json_event, 'BackgroundService') actual = cmd.generate_code() print('EXPECTED:', expected) print('ACTUAL:', actual) From 8390b894d02d8c5df878a31fe2206a6351644e84 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Wed, 28 Aug 2019 14:25:11 -0400 Subject: [PATCH 011/128] Finished checking edge cases Implemented 3 more edge cases along with tests. At this point, the build script runs successfully to completion, but I haven't checked if the modules it produces are valid or not. --- build/generate.py | 60 ++++++++++++------- build/test_generate.py | 127 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 165 insertions(+), 22 deletions(-) diff --git a/build/generate.py b/build/generate.py index fe183a6..10c4a35 100644 --- a/build/generate.py +++ b/build/generate.py @@ -98,6 +98,7 @@ def ref_to_python(ref: str) -> str: class CdpPrimitiveType(Enum): ''' All of the CDP types that map directly to a Python type. ''' + any = 'typing.Any' boolean = 'bool' integer = 'int' number = 'float' @@ -106,13 +107,13 @@ class CdpPrimitiveType(Enum): @dataclass -class CdpItemType: - ''' The type of a repeated item. ''' +class CdpItems: + ''' Represents the type of a repeated item. ''' type: str ref: str @classmethod - def from_json(cls, type) -> 'CdpItemType': + def from_json(cls, type) -> 'CdpItems': return cls(type.get('type'), type.get('$ref')) @@ -124,7 +125,7 @@ class CdpProperty: type: str ref: str enum: typing.List[str] - items: CdpItemType + items: CdpItems optional: bool @property @@ -141,13 +142,11 @@ def py_annotation(self) -> str: ann = "typing.List['{}']".format(py_ref) else: ann = 'typing.List[{}]'.format( - CdpPrimitiveType[self.type].value) + CdpPrimitiveType[self.items.type].value) else: if self.ref: py_ref = ref_to_python(self.ref) ann = f"'{py_ref}'" - elif self.type == 'any': - ann = 'typing.Any' else: ann = CdpPrimitiveType[self.type].value if self.optional: @@ -163,7 +162,7 @@ def from_json(cls, property) -> 'CdpProperty': property.get('type'), property.get('$ref'), property.get('enum'), - CdpItemType.from_json(property['items']) if 'items' in property else None, + CdpItems.from_json(property['items']) if 'items' in property else None, property.get('optional', False), ) @@ -215,7 +214,8 @@ def generate_from_json(self, dict_='json') -> str: py_ref = ref_to_python(self.items.ref) expr = f"[{py_ref}.from_json(i) for i in {dict_}['{self.name}']]" else: - raise NotImplemented() + py_type = CdpPrimitiveType[self.items.type].value + expr = f"[{py_type}(i) for i in {dict_}['{self.name}']]" else: if self.ref: py_ref = ref_to_python(self.ref) @@ -233,18 +233,20 @@ class CdpType: id: str description: str type: str + items: CdpItems enum: typing.List[str] properties: typing.List[CdpProperty] @classmethod - def from_json(cls, type) -> 'CdpType': + def from_json(cls, type_) -> 'CdpType': ''' Instantiate a CDP type from a JSON object. ''' return cls( - type['id'], - type.get('description'), - type['type'], - type.get('enum'), - [CdpProperty.from_json(p) for p in type.get('properties', list())], + type_['id'], + type_.get('description'), + type_['type'], + CdpItems.from_json(type_['items']) if 'items' in type_ else None, + type_.get('enum'), + [CdpProperty.from_json(p) for p in type_.get('properties', list())], ) def generate_code(self) -> str: @@ -263,7 +265,16 @@ def generate_code(self) -> str: def generate_primitive_code(self) -> str: ''' Generate code for a primitive type. ''' - py_type = CdpPrimitiveType[self.type].value + if self.items: + if self.items.ref: + nested_type = ref_to_python(self.items.ref) + py_type = f"typing.List['{nested_type}']" + else: + nested_type = CdpPrimitiveType[self.items.type].value + py_type = f'typing.List[{nested_type}]' + else: + # A primitive type cannot have a ref, so there is no branch here. + py_type = CdpPrimitiveType[self.type].value def_to_json = dedent(f'''\ def to_json(self) -> {py_type}: @@ -409,8 +420,9 @@ class CdpParameter(CdpProperty): def generate_code(self) -> str: ''' Generate the code for a parameter in a function call. ''' if self.items: - if self.ref: - raise NotImplementedError(self) + if self.items.ref: + nested_type = ref_to_python(self.items.ref) + py_type = f"typing.List['{nested_type}']" else: nested_type = CdpPrimitiveType[self.items.type].value py_type = f'typing.List[{nested_type}]' @@ -438,8 +450,11 @@ def generate_decl(self) -> str: def generate_doc(self) -> str: ''' Generate the docstring for this parameter. ''' - desc = self.description.replace('`', '``') - return f':param {self.py_name}: {desc}' + doc = f':param {self.py_name}:' + if self.description: + desc = self.description.replace('`', '``') + doc += f' {desc}' + return doc def generate_from_json(self, dict_) -> str: ''' @@ -463,7 +478,8 @@ def py_annotation(self): py_ref = ref_to_python(self.items.ref) ann = f"typing.List['{py_ref}']" else: - raise NotImplementedError(self) + py_type = CdpPrimitiveType[self.items.type].value + ann = f'typing.List[{py_type}]' else: if self.ref: py_ref = ref_to_python(self.ref) @@ -553,6 +569,8 @@ def generate_code(self) -> str: doc = '' if self.parameters and doc: doc += '\n\n' + elif not self.parameters and self.returns: + doc += '\n' doc += '\n'.join(p.generate_doc() for p in self.parameters) if len(self.returns) == 1: doc += '\n' diff --git a/build/test_generate.py b/build/test_generate.py index 1500dc1..dc0b932 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -67,6 +67,37 @@ def __repr__(self): assert expected == actual +def test_cdp_array_of_primitive_type(): + json_type = { + "id": "ArrayOfStrings", + "description": "Index of the string in the strings table.", + "type": "array", + "items": { + "$ref": "StringIndex" + } + } + expected = dedent("""\ + class ArrayOfStrings(typing.List['StringIndex']): + ''' + Index of the string in the strings table. + ''' + def to_json(self) -> typing.List['StringIndex']: + return self + + @classmethod + def from_json(cls, json: typing.List['StringIndex']) -> 'ArrayOfStrings': + return cls(json) + + def __repr__(self): + return 'ArrayOfStrings({})'.format(super().__repr__())""") + + type = CdpType.from_json(json_type) + actual = type.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + def test_cdp_enum_type(): json_type = { "id": "AXValueSourceType", @@ -292,6 +323,7 @@ def disable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: print('ACTUAL:', actual) assert expected == actual + def test_cdp_command_return_primitive(): json_cmd = { "name": "getCurrentTime", @@ -337,7 +369,44 @@ def get_current_time( assert expected == actual -def test_cdp_command_array_parameter(): +def test_cdp_command_return_array_of_primitive(): + json_cmd = { + "name": "getBrowserCommandLine", + "description": "Returns the command line switches for the browser process if, and only if\n--enable-automation is on the commandline.", + "experimental": True, + "returns": [ + { + "name": "arguments", + "description": "Commandline parameters", + "type": "array", + "items": { + "type": "string" + } + } + ] + } + expected = dedent("""\ + def get_browser_command_line() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.List[str]]: + ''' + Returns the command line switches for the browser process if, and only if + --enable-automation is on the commandline. + + :returns: Commandline parameters + ''' + cmd_dict: T_JSON_DICT = { + 'method': 'Browser.getBrowserCommandLine', + } + json = yield cmd_dict + return [str(i) for i in json['arguments']]""") + + cmd = CdpCommand.from_json(json_cmd, 'Browser') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + +def test_cdp_command_array_of_primitive_parameter(): json_cmd = { "name": "releaseAnimations", "description": "Releases a set of animations to no longer be manipulated.", @@ -514,6 +583,62 @@ def get_encoded_response( assert expected == actual +def test_cdp_command_array_of_ref_parameter(): + json_cmd = { + "name": "grantPermissions", + "description": "Grant specific permissions to the given origin and reject all others.", + "experimental": True, + "parameters": [ + { + "name": "origin", + "type": "string" + }, + { + "name": "permissions", + "type": "array", + "items": { + "$ref": "PermissionType" + } + }, + { + "name": "browserContextId", + "description": "BrowserContext to override permissions. When omitted, default browser context is used.", + "optional": True, + "$ref": "Target.BrowserContextID" + } + ] + } + expected = dedent("""\ + def grant_permissions( + origin: str, + permissions: typing.List['PermissionType'], + browser_context_id: typing.Optional['target.BrowserContextID'] = None + ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: + ''' + Grant specific permissions to the given origin and reject all others. + + :param origin: + :param permissions: + :param browser_context_id: BrowserContext to override permissions. When omitted, default browser context is used. + ''' + params: T_JSON_DICT = dict() + params['origin'] = origin + params['permissions'] = [i.to_json() for i in permissions] + if browser_context_id is not None: + params['browserContextId'] = browser_context_id.to_json() + cmd_dict: T_JSON_DICT = { + 'method': 'Browser.grantPermissions', + 'params': params, + } + json = yield cmd_dict""") + + cmd = CdpCommand.from_json(json_cmd, 'Browser') + actual = cmd.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual + + def test_cdp_event(): json_event = { "name": "recordingStateChanged", From d80bfa90420149c250a1cfa50783c59998e30b43 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Wed, 28 Aug 2019 14:31:26 -0400 Subject: [PATCH 012/128] Fix a bug in primitive array types This is a bug that was introduced in our prototype and I noticed it while peforming this refactoring: the super class was set to the type annotation, not the name of a class. The implementation and test are both updated here. --- build/generate.py | 16 +++++++++------- build/test_generate.py | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/build/generate.py b/build/generate.py index 10c4a35..bb24e65 100644 --- a/build/generate.py +++ b/build/generate.py @@ -272,29 +272,31 @@ def generate_primitive_code(self) -> str: else: nested_type = CdpPrimitiveType[self.items.type].value py_type = f'typing.List[{nested_type}]' + superclass = 'list' else: # A primitive type cannot have a ref, so there is no branch here. py_type = CdpPrimitiveType[self.type].value + superclass = py_type + + code = f'class {self.id}({superclass}):\n' + doc = docstring(self.description) + if doc: + code += indent(doc, 4) + '\n' def_to_json = dedent(f'''\ def to_json(self) -> {py_type}: return self''') + code += indent(def_to_json, 4) def_from_json = dedent(f'''\ @classmethod def from_json(cls, json: {py_type}) -> '{self.id}': return cls(json)''') + code += '\n\n' + indent(def_from_json, 4) def_repr = dedent(f'''\ def __repr__(self): return '{self.id}({{}})'.format(super().__repr__())''') - - code = f'class {self.id}({py_type}):\n' - doc = docstring(self.description) - if doc: - code += indent(doc, 4) + '\n' - code += indent(def_to_json, 4) - code += '\n\n' + indent(def_from_json, 4) code += '\n\n' + indent(def_repr, 4) return code diff --git a/build/test_generate.py b/build/test_generate.py index dc0b932..ad47dde 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -77,7 +77,7 @@ def test_cdp_array_of_primitive_type(): } } expected = dedent("""\ - class ArrayOfStrings(typing.List['StringIndex']): + class ArrayOfStrings(list): ''' Index of the string in the strings table. ''' From f655ee9560fca61d25e6769080be12fe29714606 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Wed, 28 Aug 2019 15:49:23 -0400 Subject: [PATCH 013/128] Lots of cleanup as I wrap up refactoring: * Generate new init file * Make sure the cdp module can be imported - Dependencies aren't handled correctly yet, though * Remove dead code * Modify event dispatch so that we don't need to use inflection * Remove inflection as an install dependency! * Add some tests for the generated CDP code * Add a makefile that runs the various tests and build scripts --- .gitignore | 1 + Makefile | 13 ++ build/generate.py | 306 ++--------------------------------------- build/test_generate.py | 5 +- cdp/util.py | 15 +- requirements.txt | 4 +- setup.py | 6 +- test/test_cdp.py | 60 ++++++++ 8 files changed, 98 insertions(+), 312 deletions(-) create mode 100644 Makefile create mode 100644 test/test_cdp.py diff --git a/.gitignore b/.gitignore index 2815ae6..cd5d4e1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *.egg-info .mypy_cache +.pytest_cache __pycache__ venv diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..bfce4c9 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +all: test-generate generate test-import test-cdp + +generate: + python build/generate.py + +test-cdp: + pytest test/ + +test-generate: + pytest build/ + +test-import: + python -c 'import cdp; print(cdp.accessibility)' diff --git a/build/generate.py b/build/generate.py index bb24e65..2dacf0d 100644 --- a/build/generate.py +++ b/build/generate.py @@ -34,7 +34,7 @@ Experimental: {{}} \'\'\' -from cdp.util import T_JSON_DICT +from cdp.util import event_class, T_JSON_DICT from dataclasses import dataclass import enum import typing @@ -637,6 +637,7 @@ def from_json(cls, json: dict, domain: str): def generate_code(self) -> str: ''' Generate code for a CDP event. ''' code = dedent(f'''\ + @event_class('{self.domain}.{self.name}') @dataclass class {self.py_name}:''') code += '\n' @@ -646,13 +647,6 @@ class {self.py_name}:''') code += indent( '\n'.join(p.generate_decl() for p in self.parameters), 4) code += '\n\n' - internal = dedent(f'''\ - # These fields are used for internal purposes and are not part of CDP - _domain = '{self.domain}' - _method = '{self.name}' - ''') - code += indent(internal, 4) - code += '\n' def_from_json = dedent(f'''\ @classmethod def from_json(cls, json: T_JSON_DICT) -> '{self.py_name}': @@ -805,288 +799,8 @@ def parse(json_path, output_path): domains.append(CdpDomain.from_json(domain)) return domains -###################################################### -## All refactored code is above. Old code is below. ## -###################################################### - -def get_dependency(cdp_meta): - if 'type' in cdp_meta and cdp_meta['type'] != 'array': - return None - - if 'items' in cdp_meta and 'type' in cdp_meta['items']: - return None - - if '$ref' in cdp_meta: - type_ = cdp_meta['$ref'] - elif 'items' in cdp_meta and '$ref' in cdp_meta['items']: - type_ = cdp_meta['items']['$ref'] - else: - raise Exception('Cannot get dependency: {!r}'.format(cdp_meta)) - - try: - dependency, _ = type_.split('.') - return dependency - except ValueError: - # Not a dependency on another module. - return None - - -def import_dependency(dependency): - module_name = inflection.underscore(dependency) - return 'from ..{} import types as {}\n'.format(module_name, module_name) - - -def get_python_type(cdp_type): - ''' - Generate a name for the Python type that corresponds to the the given CDP - type. - - :param dict cdp_meta: CDP metadata for a type or property - :returns: Python type as a string - ''' - if 'type' in cdp_meta: - cdp_type = cdp_meta['type'] - if cdp_type == 'array': - py_type = 'typing.List' - try: - cdp_nested_type = get_python_type(cdp_meta['items']) - if '.' in cdp_nested_type: - domain, subtype = cdp_nested_type.split('.') - cdp_nested_type = '{}.{}'.format( - inflection.underscore(domain), subtype) - py_type += "['{}']".format(cdp_nested_type) - except KeyError: - # No nested type: ignore. - pass - else: - py_type = { - 'any': 'typing.Any', - 'boolean': 'bool', - 'integer': 'int', - 'object': 'dict', - 'number': 'float', - 'string': 'str', - }[cdp_type] - return py_type - - if '$ref' in cdp_meta: - prop_type = cdp_meta['$ref'] - if '.' in prop_type: - # If the type lives in another module, then we need to - # snake_case the module name and it should *not* be added to the - # list of child classes that is used for dependency resolution. - other_module, other_type = prop_type.split('.') - prop_type = '{}.{}'.format(inflection.underscore(other_module), - other_type) - return prop_type - - raise Exception('Cannot get python type from CDP metadata: {!r}'.format( - cdp_meta)) - - -def is_builtin_type(python_type): - return python_type in ('bool', 'int', 'dict', 'float', 'str') - - -def generate_events(domain, events): - exports = list() - code = '\n' - for event in events: - event_name = inflection.camelize(event['name'], - uppercase_first_letter=True) - parameters = event.get('parameters', list()) - code += '\n@dataclass\n' - code += 'class {}:\n'.format(event_name) - description = event.get('description') - code += docstring(description) - from_json = list() - for parameter in parameters: - name = parameter['name'] - snake_name = inflection.underscore(name) - param_description = parameter.get('description') - code += inline_doc(description, indent=4) - if 'type' in parameter: - param_decl = get_python_type(parameter) - elif '$ref' in parameter: - param_decl = parameter['$ref'] - if '.' in param_decl: - # If the type lives in another module, then we need to - # snake_case the module name and it should *not* be - # added to the list of child classes that is used for - # dependency resolution. - other_module, other_type = param_decl.split('.') - param_decl = '{}.{}'.format( - inflection.underscore(other_module), other_type) - else: - raise Exception('Cannot determing event parameter type:' - ' {!r}'.format(parameter)) - optional = parameter.get('optional', False) - if optional: - param_decl = 'typing.Optional[{}] = None'.format(param_decl) - code += ' {}: {}\n\n'.format(snake_name, param_decl) - from_json.append((name, snake_name, optional, make_return_code(parameter))) - code += ' # These fields are used for internal purposes and are not part of CDP\n' - code += " _domain = '{}'\n".format(domain) - code += " _method = '{}'\n".format(event['name']) - code += '\n' - code += ' @classmethod\n' - code += " def from_json(cls, json: dict) -> '{}':\n".format(event_name) - for name, snake_name, optional, snippet in from_json: - if not optional: - continue - code += " {} = {} if '{}' in json else None\n".format( - snake_name, snippet, name) - code += ' return cls(\n' - for name, snake_name, optional, snippet in from_json: - if optional: - code += ' {}={},\n'.format(snake_name, snake_name) - else: - code += ' {}={},\n'.format(snake_name, snippet) - code += ' )\n\n' - exports.append(event_name) - return exports, code - - -def generate_commands(domain_name, commands): - ''' - Generate command definitions as Python code. - - :param str domain_name: the CDP domain name - :param list commands: a list of CDP command definitions - :returns: a tuple (list of exported types, code as string) - ''' - code = '\n\n' - for command in commands: - command_name = command['name'] - method_name = inflection.underscore(command_name) - description = command.get('description', '') - arg_list = list() - to_json = list() - params = command.get('parameters', list()) - if params: - description += '\n' - for param in params: - param_name = param['name'] - snake_name = inflection.underscore(param_name) - param_type = get_python_type(param) - param_decl = param_type - if param.get('optional', False): - param_decl = 'typing.Optional[{}] = None'.format(param_decl) - arg_list.append('{}: {}'.format(snake_name, param_decl)) - description += '\n:param {}: {}'.format(snake_name, - param.get('description', '')) - if 'type' in param: - if param['type'] != 'array': - json_code = '{}'.format(snake_name) - elif '$ref' in param['items']: - subtype = get_python_type(param['items']) - json_code = '[i.to_json() for i in {}]'.format(snake_name) - elif 'type' in param['items']: - subtype = get_python_type(param['items']) - json_code = '[i for i in {}]'.format(snake_name) - else: - json_code = '{}.to_json()'.format(snake_name) - # convert = '' if is_builtin_type(param_type) else '.to_json()' - to_json.append((param_name, snake_name, json_code, - param.get('optional', False))) - returns = command.get('returns', list()) - if len(returns) == 0: - return_type = 'None' - elif len(returns) == 1: - return_type = get_python_type(returns[0]) - description += '\n:returns: {}'.format( - returns[0].get('description', '')) - else: - return_type = 'dict' - description += '\n:returns: a dict with the following keys:' - for return_ in returns: - optstr = '(Optional) ' if return_.get('optional', False) else '' - description += '\n * {}: {}{}'.format(return_['name'], - optstr, return_.get('description', '')) - code += 'def {}('.format(method_name) - if arg_list: - code += '\n' - for arg in arg_list: - code += ' {},\n'.format(arg) - code += ' ' - code += ') -> typing.Generator[T_JSON_DICT,T_JSON_DICT,{}]:\n'.format(return_type) - code += docstring(description, indent=4) - if to_json: - code += ' params: T_JSON_DICT = {\n' - for param_name, snake_name, json_code, optional in to_json: - if optional: - continue - code += " '{}': {},\n".format(param_name, json_code) - code += ' }\n' - for param_name, snake_name, json_code, optional in to_json: - if not optional: - continue - code += ' if {} is not None:\n'.format(snake_name) - code += " params['{}'] = {}\n".format(param_name, - json_code) - code += ' cmd_dict: T_JSON_DICT = {\n' - code += " 'method': '{}.{}',\n".format(domain_name, - command_name) - if to_json: - code += " 'params': params,\n" - code += ' }\n' - code += ' json = yield cmd_dict\n' - if len(returns) == 1: - return_ = returns[0] - return_type = get_python_type(return_) - code += ' return {}\n'.format(make_return_code(return_)) - elif len(returns) > 1: - # we should be able to refactor the first part of this if block to have something - # reusable, then we call that new thing inside of a loop in this elif block - # the only difference here is printing key names and dict syntax - code += ' result: T_JSON_DICT = {\n' - # code += ' return {\n' - for return_ in returns: - if return_.get('optional', False): - continue - return_type = get_python_type(return_) - code += " '{}': {},\n".format(return_['name'], - make_return_code(return_)) - code += ' }\n' - for return_ in returns: - if not return_.get('optional', False): - continue - code += " if '{}' in json:\n".format(return_['name']) - code += " result['{}'] = {}\n".format(return_['name'], - make_return_code(return_)) - code += ' return result\n' - code += '\n\n' - return [domain_name], code - - -def make_return_code(return_): - ''' - Make a snippet of code that retuns a value inside of a ``from_json()`` - method. - - :param dict return_: the CDP metadata for the item to return - :returns: a string - ''' - return_name = return_['name'] - return_type = get_python_type(return_) - if 'typing.List' in return_type: - subtype = get_python_type(return_['items']) - if subtype.startswith('typing.Any'): - code = "[i for i in json['{}']]".format(return_name) - elif 'type' in return_['items'] or is_builtin_type(subtype): - code = "[{}(i) for i in json['{}']]".format(subtype, return_name) - else: - code = "[{}.from_json(i) for i in json['{}']]".format(subtype, return_name) - elif is_builtin_type(return_type): - code = "{}(json['{}'])".format(return_type, return_name) - elif return_type.startswith('typing.Any'): - code = "json['{}']".format(return_name) - else: - code = "{}.from_json(json['{}'])".format(return_type, return_name) - return code - -def generate_init(init_path, modules): +def generate_init(init_path, domains): ''' Generate an ``__init__.py`` that exports the specified modules. @@ -1094,15 +808,11 @@ def generate_init(init_path, modules): :param list[tuple] modules: a list of modules each represented as tuples of (name, list_of_exported_symbols) ''' - modules = [module[0] for module in modules] - modules.sort() with init_path.open('w') as init_file: - init_file.write(init_header) - for submodule in ('types', 'events', 'commands'): - for module in modules: - init_file.write('import cdp.{}.{}\n'.format(module, submodule)) - init_file.write('\n') - init_file.write('import cdp.util\n') + init_file.write(INIT_HEADER) + init_file.write('import cdp.util\n\n') + for domain in domains: + init_file.write('import cdp.{}\n'.format(domain.module)) def main(): @@ -1130,7 +840,7 @@ def main(): module_file.write(domain.generate_code()) init_path = output_path / '__init__.py' - # generate_init(init_path, domains) + generate_init(init_path, domains) py_typed_path = output_path / 'py.typed' py_typed_path.touch() diff --git a/build/test_generate.py b/build/test_generate.py index ad47dde..ba29a6c 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -655,6 +655,7 @@ def test_cdp_event(): ] } expected = dedent("""\ + @event_class('BackgroundService.recordingStateChanged') @dataclass class RecordingStateChanged: ''' @@ -663,10 +664,6 @@ class RecordingStateChanged: is_recording: bool service: 'ServiceName' - # These fields are used for internal purposes and are not part of CDP - _domain = 'BackgroundService' - _method = 'recordingStateChanged' - @classmethod def from_json(cls, json: T_JSON_DICT) -> 'RecordingStateChanged': return cls( diff --git a/cdp/util.py b/cdp/util.py index b527a01..513b7fd 100644 --- a/cdp/util.py +++ b/cdp/util.py @@ -4,12 +4,17 @@ T_JSON_DICT = typing.Dict[str, typing.Any] +_event_parsers = dict() + + +def event_class(method): + ''' A decorator that registers a class as an event class. ''' + def decorate(cls): + _event_parsers[method] = cls + return cls + return decorate def parse_json_event(json: dict) -> typing.Tuple[str, str, typing.Any]: ''' Parse a JSON dictionary into a CDP event. ''' - domain, event_name = json['method'].split('.') - module = getattr(getattr(cdp, inflection.underscore(domain)), 'events') - cls_name = inflection.camelize(event_name, uppercase_first_letter=True) - cls = getattr(module, cls_name) - return cls._domain, cls._method, cls.from_json(json['params']) + return _event_parsers[json['method']].from_json(json['params']) diff --git a/requirements.txt b/requirements.txt index a9c687b..df1a82e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,4 @@ +# These packages are required for generating the CDP sources. They are not +# needed if you only want to install this library. inflection - +mypy diff --git a/setup.py b/setup.py index 2a1d406..871292d 100644 --- a/setup.py +++ b/setup.py @@ -23,8 +23,6 @@ python_requires='>=3.7', keywords='chrome devtools protocol cdp', package_data={'cdp': ['py.typed']}, - packages=find_packages(exclude=['build', 'docs', 'examples', 'tests']), - install_requires=[ - 'inflection', - ] + packages=find_packages(exclude=['build', 'docs', 'examples', 'test']), + install_requires=[] ) diff --git a/test/test_cdp.py b/test/test_cdp.py new file mode 100644 index 0000000..d7696b1 --- /dev/null +++ b/test/test_cdp.py @@ -0,0 +1,60 @@ +''' +Some basic tests for the generated CDP modules. +''' +from cdp import dom, page, util + + +def test_primitive_type(): + frame_id = page.FrameId('foo') + assert repr(frame_id) == "FrameId('foo')" + assert frame_id.to_json() == 'foo' + assert page.FrameId.from_json('foo') == frame_id + + +def test_enum_type(): + tran_type = page.TransitionType.ADDRESS_BAR + assert tran_type.name == 'ADDRESS_BAR' + assert tran_type.value == 'address_bar' + assert tran_type.to_json() == 'address_bar' + assert page.TransitionType.from_json('address_bar') == tran_type + + +def test_class_type(): + blue = dom.RGBA(51, 153, 255) + assert blue.a is None + assert blue.to_json() == {'r': 51, 'g': 153, 'b': 255} + assert dom.RGBA.from_json({'r': 51, 'g': 153, 'b': 255}) == blue + + trans_violet = dom.RGBA(51, 153, 255, 0.8) + assert trans_violet.a == 0.8 + assert trans_violet.to_json() == {'r': 51, 'g': 153, 'b': 255, 'a': 0.8} + assert dom.RGBA.from_json({'r': 51, 'g': 153, 'b': 255, 'a':0.8}) == trans_violet + + +def test_event_type(): + event = page.WindowOpen.from_json({ + 'url': 'https://foo.com', + 'windowName': 'Window 1', + 'windowFeatures': ['feature1', 'feature2'], + 'userGesture': False + }) + assert event.url == 'https://foo.com' + assert event.window_name == 'Window 1' + assert event.window_features == ['feature1', 'feature2'] + assert not event.user_gesture + + +def test_event_dispatch(): + event = util.parse_json_event({ + 'method': 'Page.windowOpen', + 'params': { + 'url': 'https://foo.com', + 'windowName': 'Window 1', + 'windowFeatures': ['feature1', 'feature2'], + 'userGesture': False + } + }) + assert event.url == 'https://foo.com' + assert event.window_name == 'Window 1' + assert event.window_features == ['feature1', 'feature2'] + assert not event.user_gesture From da97bd86385899b26aecfec069971fda2c731586 Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Thu, 29 Aug 2019 08:38:10 -0400 Subject: [PATCH 014/128] Remove dead code and add basic support for importing dependencies --- build/generate.py | 152 ++++++++--------------------------------- build/test_generate.py | 94 ++++++++++++++++++++++++- cdp/util.py | 1 - test/test_cdp.py | 14 +++- 4 files changed, 136 insertions(+), 125 deletions(-) diff --git a/build/generate.py b/build/generate.py index 2dacf0d..f08a061 100644 --- a/build/generate.py +++ b/build/generate.py @@ -39,7 +39,6 @@ import enum import typing - '''.format(SHARED_HEADER) @@ -169,12 +168,6 @@ def from_json(cls, property) -> 'CdpProperty': def generate_decl(self) -> str: ''' Generate the code that declares this property. ''' code = inline_doc(self.description) - # todo handle dependencies later - # elif '$ref' in prop and '.' not in prop_ann: - # # If the type lives in this module and is not a type that refers - # # to itself, then add it to the set of children so that - # # inter-class dependencies can be resolved later on. - # children.add(prop_ann) code += f'{self.py_name}: {self.py_annotation}' if self.optional: code += ' = None' @@ -206,9 +199,6 @@ def generate_to_json(self, dict_: str, use_self: bool=True) -> str: def generate_from_json(self, dict_='json') -> str: ''' Generate the code that creates an instance from a JSON dict named ``json``. ''' - # todo this is one of the few places where a real dependency is created - # (most of the deps are type annotations and can be avoided by quoting - # the annotation) if self.items: if self.items.ref: py_ref = ref_to_python(self.items.ref) @@ -251,10 +241,6 @@ def from_json(cls, type_) -> 'CdpType': def generate_code(self) -> str: ''' Generate Python code for this type. ''' - # todo handle exports and emitted types somewhere else? - # exports = list() - # exports.append(type_name) - # emitted_types = set() logger.debug('Generating type %s: %s', self.id, self.type) if self.enum: return self.generate_enum_code() @@ -380,42 +366,8 @@ def from_json(cls, json: T_JSON_DICT) -> '{self.id}': def_from_json += indent(')', 4) code += indent(def_from_json, 4) - # todo we used to return a dict but i'm not sure if that's still needed? - # return { - # 'name': self.id, - # 'code': code, - # Don't emit children that live in a different module. We assume that - # modules do not have cyclical dependencies on each other. - # 'children': [c for c in children if '.' not in c], - # } return code - # Todo how to resolve dependencies? - # The classes have dependencies on each other, so we have to emit them in - # a specific order. If we can't resolve these dependencies after a certain - # number of iterations, it suggests a cyclical dependency that this code - # cannot handle. - # tries_remaining = 1000 - # while classes: - # class_ = classes.pop(0) - # if not class_['children']: - # code += class_['code'] - # emitted_types.add(class_['name']) - # continue - # if all(child in emitted_types for child in class_['children']): - # code += class_['code'] - # emitted_types.add(class_['name']) - # continue - # classes.append(class_) - # tries_remaining -= 1 - # if not tries_remaining: - # logger.error('Class resolution failed. Emitted these types: %s', - # emitted_types) - # logger.error('Class resolution failed. Cannot emit these types: %s', - # json.dumps(classes, indent=2)) - # raise Exception('Failed to resolve class dependencies.' - # ' See output above.') - class CdpParameter(CdpProperty): ''' A parameter to a CDP command. ''' @@ -697,6 +649,13 @@ def from_json(cls, domain: dict): def generate_code(self) -> str: ''' Generate the Python module code for a given CDP domain. ''' code = MODULE_HEADER.format(self.domain, self.experimental) + imports = list() + for d in self.dependencies: + module = inflection.underscore(d) + imports.append(f'from . import {module}') + if imports: + code += '\n'.join(imports) + code += '\n\n\n' item_iter = itertools.chain( iter(self.types), iter(self.commands), @@ -706,80 +665,29 @@ def generate_code(self) -> str: code += '\n' return code - # todo update dependencies - # The dependencies listed in the JSON don't match the actual dependencies - # encountered when building the types. So we ignore the declared - # dependencies and compute it ourself. - # type_dependencies = set() - # domain_types = domain.get('types', list()) - # for type_ in domain_types: - # for prop in type_.get('properties', list()): - # dependency = get_dependency(prop) - # if dependency: - # type_dependencies.add(dependency) - # if type_dependencies: - # logger.debug('Computed type_dependencies: %s', ','.join( - # type_dependencies)) - # - # event_dependencies = set() - # domain_events = domain.get('events', list()) - # for event in domain_events: - # for param in event.get('parameters', list()): - # dependency = get_dependency(param) - # if dependency: - # event_dependencies.add(dependency) - # if event_dependencies: - # logger.debug('Computed event_dependencies: %s', ','.join( - # event_dependencies)) - # - # command_dependencies = set() - # domain_commands = domain.get('commands', list()) - # for command in domain_commands: - # for param in command.get('parameters', list()): - # dependency = get_dependency(param) - # if dependency: - # command_dependencies.add(dependency) - # for return_ in command.get('returns', list()): - # dependency = get_dependency(return_) - # if dependency: - # command_dependencies.add(dependency) - # if command_dependencies: - # logger.debug('Computed command_dependencies: %s', ','.join( - # command_dependencies)) - - # types_path = module_path / 'types.py' - # with types_path.open('w') as types_file: - # types_file.write(module_header.format(module_name, self.experimental)) - # for dependency in sorted(type_dependencies): - # types_file.write(import_dependency(dependency)) - # if type_dependencies: - # types_file.write('\n') - # type_exports, type_code = generate_types(domain_types) - # types_file.write(type_code) - # - # events_path = module_path / 'events.py' - # with events_path.open('w') as events_file: - # events_file.write(module_header.format(module_name, self.experimental)) - # events_file.write('from .types import *\n') - # for dependency in sorted(event_dependencies): - # events_file.write(import_dependency(dependency)) - # if event_dependencies: - # events_file.write('\n') - # event_exports, event_code = generate_events(self.domain, domain_events) - # events_file.write(event_code) - # - # commands_path = module_path / 'commands.py' - # with commands_path.open('w') as commands_file: - # commands_file.write(module_header.format(module_name, self.experimental)) - # commands_file.write('from .types import *\n') - # for dependency in sorted(command_dependencies): - # commands_file.write(import_dependency(dependency)) - # if command_dependencies: - # commands_file.write('\n') - # command_exports, command_code = generate_commands(self.domain, domain_commands) - # commands_file.write(command_code) - - # return module_name, type_exports, event_exports, command_exports + # def generate_imports(self): + # ''' Determine which modules this module depends on and emit the code to + # import those modules. ''' + # refs = set() + # for type_ in self.types: + # # Remember: types never have a ref, but they can have an items with + # # a ref. + # if type_.items: + # refs.add(type_.items.ref) + # for command in self.commands: + # pass + # # If a type doesn't have a ref, then ref is None, so we should remove + # # that here: + # ref.remove(None) + # dependencies = set() + # for ref in refs: + # try: + # domain, _ = ref.split('.') + # except ValueError: + # continue + # if domain != self.domain: + # dependencies.add(inflection.underscore(domain)) + # return '\n'.join(f'import {d}' for d in dependencies) def parse(json_path, output_path): diff --git a/build/test_generate.py b/build/test_generate.py index ba29a6c..5eb6d27 100644 --- a/build/test_generate.py +++ b/build/test_generate.py @@ -12,7 +12,7 @@ from textwrap import dedent -from generate import CdpCommand, CdpEvent, CdpType, docstring +from generate import CdpCommand, CdpDomain, CdpEvent, CdpType, docstring def test_docstring(): @@ -676,3 +676,95 @@ def from_json(cls, json: T_JSON_DICT) -> 'RecordingStateChanged': print('EXPECTED:', expected) print('ACTUAL:', actual) assert expected == actual + + +def test_cdp_domain(): + ''' This is a made-up domain in order to keep the test short. ''' + json_domain = { + "domain": "Car", + "dependencies": [ + "WindTunnel", + ], + "types": [ + { + "id": "Wheels", + "type": "array", + "items": {"$ref": "Vehicle.Wheel"}, + }, + { + "id": "Engine", + "type": "object", + "properties": [ + { + "name": "block", + "$ref": "Parts.EngineBlock" + }, + { + "name": "pistons", + "type": "array", + "items": {"$ref": "Parts.Piston"}, + }, + ] + } + ], + "commands": [ + ], + "events": [ + ] + } + expected = dedent("""\ + ''' + DO NOT EDIT THIS FILE + + This file is generated from the CDP specification. If you need to make changes, + edit the generator and regenerate all of the modules. + + Domain: Car + Experimental: False + ''' + + from cdp.util import event_class, T_JSON_DICT + from dataclasses import dataclass + import enum + import typing + + from . import wind_tunnel + + + class Wheels(list): + def to_json(self) -> typing.List['vehicle.Wheel']: + return self + + @classmethod + def from_json(cls, json: typing.List['vehicle.Wheel']) -> 'Wheels': + return cls(json) + + def __repr__(self): + return 'Wheels({})'.format(super().__repr__()) + + + @dataclass + class Engine: + block: 'parts.EngineBlock' + + pistons: typing.List['parts.Piston'] + + def to_json(self) -> T_JSON_DICT: + json: T_JSON_DICT = dict() + json['block'] = self.block.to_json() + json['pistons'] = [i.to_json() for i in self.pistons] + return json + + @classmethod + def from_json(cls, json: T_JSON_DICT) -> 'Engine': + return cls( + block=parts.EngineBlock.from_json(json['block']), + pistons=[parts.Piston.from_json(i) for i in json['pistons']], + ) + """) # A domain should have a new line at the end. + + domain = CdpDomain.from_json(json_domain) + actual = domain.generate_code() + print('EXPECTED:', expected) + print('ACTUAL:', actual) + assert expected == actual diff --git a/cdp/util.py b/cdp/util.py index 513b7fd..054b2d5 100644 --- a/cdp/util.py +++ b/cdp/util.py @@ -1,5 +1,4 @@ import cdp -import inflection import typing diff --git a/test/test_cdp.py b/test/test_cdp.py index d7696b1..8330805 100644 --- a/test/test_cdp.py +++ b/test/test_cdp.py @@ -1,7 +1,7 @@ ''' Some basic tests for the generated CDP modules. ''' -from cdp import dom, page, util +from cdp import dom, io, page, tracing, util def test_primitive_type(): @@ -44,6 +44,18 @@ def test_event_type(): assert not event.user_gesture +def test_event_type_with_dependency(): + ''' This tracing event has a dependency on the io module. ''' + event = tracing.TracingComplete.from_json({ + 'stream': 'Foo Stream', + 'traceFormat': tracing.StreamFormat.JSON, + }) + assert isinstance(event.stream, io.StreamHandle) + assert repr(event.stream) == "StreamHandle('Foo Stream')" + assert event.trace_format.value == 'json' + assert event.stream_compression is None + + def test_event_dispatch(): event = util.parse_json_event({ 'method': 'Page.windowOpen', From e1ee5477c2deb6015c73f2a5644d5157e27eefdd Mon Sep 17 00:00:00 2001 From: "Mark E. Haase" Date: Thu, 29 Aug 2019 08:39:28 -0400 Subject: [PATCH 015/128] Delete old generated code This is causing a lot of noise in my git status, and it's easier just to remove it until I'm ready to check in the regenerated code. --- cdp/accessibility/__init__.py | 0 cdp/accessibility/commands.py | 88 -- cdp/accessibility/events.py | 17 - cdp/accessibility/types.py | 411 -------- cdp/animation/__init__.py | 0 cdp/animation/commands.py | 194 ---- cdp/animation/events.py | 74 -- cdp/animation/types.py | 209 ---- cdp/application_cache/__init__.py | 0 cdp/application_cache/commands.py | 84 -- cdp/application_cache/events.py | 55 - cdp/application_cache/types.py | 118 --- cdp/audits/__init__.py | 0 cdp/audits/commands.py | 61 -- cdp/audits/events.py | 17 - cdp/audits/types.py | 16 - cdp/background_service/__init__.py | 0 cdp/background_service/commands.py | 93 -- cdp/background_service/events.py | 61 -- cdp/background_service/types.py | 108 -- cdp/browser/__init__.py | 0 cdp/browser/commands.py | 276 ----- cdp/browser/events.py | 17 - cdp/browser/types.py | 188 ---- cdp/cache_storage/__init__.py | 0 cdp/cache_storage/commands.py | 140 --- cdp/cache_storage/events.py | 17 - cdp/cache_storage/types.py | 175 ---- cdp/cast/__init__.py | 0 cdp/cast/commands.py | 106 -- cdp/cast/events.py | 59 -- cdp/cast/types.py | 44 - cdp/console/__init__.py | 0 cdp/console/commands.py | 49 - cdp/console/events.py | 36 - cdp/console/types.py | 67 -- cdp/css/__init__.py | 0 cdp/css/commands.py | 491 --------- cdp/css/events.py | 112 -- cdp/css/types.py | 852 ---------------- cdp/database/__init__.py | 0 cdp/database/commands.py | 92 -- cdp/database/events.py | 32 - cdp/database/types.py | 91 -- cdp/debugger/__init__.py | 0 cdp/debugger/commands.py | 702 ------------- cdp/debugger/events.py | 280 ----- cdp/debugger/types.py | 269 ----- cdp/device_orientation/__init__.py | 0 cdp/device_orientation/commands.py | 52 - cdp/device_orientation/events.py | 17 - cdp/device_orientation/types.py | 16 - cdp/dom/__init__.py | 0 cdp/dom/commands.py | 964 ------------------ cdp/dom/events.py | 338 ------ cdp/dom/types.py | 493 --------- cdp/dom_debugger/__init__.py | 0 cdp/dom_debugger/commands.py | 210 ---- cdp/dom_debugger/events.py | 17 - cdp/dom_debugger/types.py | 106 -- cdp/dom_snapshot/__init__.py | 0 cdp/dom_snapshot/commands.py | 110 -- cdp/dom_snapshot/events.py | 17 - cdp/dom_snapshot/types.py | 748 -------------- cdp/dom_storage/__init__.py | 0 cdp/dom_storage/commands.py | 121 --- cdp/dom_storage/events.py | 95 -- cdp/dom_storage/types.py | 56 - cdp/emulation/__init__.py | 0 cdp/emulation/commands.py | 472 --------- cdp/emulation/events.py | 32 - cdp/emulation/types.py | 60 -- cdp/fetch/__init__.py | 0 cdp/fetch/commands.py | 227 ----- cdp/fetch/events.py | 157 --- cdp/fetch/types.py | 182 ---- cdp/headless_experimental/__init__.py | 0 cdp/headless_experimental/commands.py | 88 -- cdp/headless_experimental/events.py | 36 - cdp/headless_experimental/types.py | 45 - cdp/heap_profiler/__init__.py | 0 cdp/heap_profiler/commands.py | 206 ---- cdp/heap_profiler/events.py | 114 --- cdp/heap_profiler/types.py | 122 --- cdp/indexed_db/__init__.py | 0 cdp/indexed_db/commands.py | 232 ----- cdp/indexed_db/events.py | 17 - cdp/indexed_db/types.py | 270 ----- cdp/input/__init__.py | 0 cdp/input/commands.py | 401 -------- cdp/input/events.py | 17 - cdp/input/types.py | 102 -- cdp/inspector/__init__.py | 0 cdp/inspector/commands.py | 38 - cdp/inspector/events.py | 66 -- cdp/inspector/types.py | 16 - cdp/io/__init__.py | 0 cdp/io/commands.py | 96 -- cdp/io/events.py | 17 - cdp/io/types.py | 32 - cdp/layer_tree/__init__.py | 0 cdp/layer_tree/commands.py | 202 ---- cdp/layer_tree/events.py | 53 - cdp/layer_tree/types.py | 271 ----- cdp/log/__init__.py | 0 cdp/log/commands.py | 77 -- cdp/log/events.py | 36 - cdp/log/types.py | 121 --- cdp/memory/__init__.py | 0 cdp/memory/commands.py | 163 --- cdp/memory/events.py | 17 - cdp/memory/types.py | 120 --- cdp/network/__init__.py | 0 cdp/network/commands.py | 640 ------------ cdp/network/events.py | 603 ----------- cdp/network/types.py | 1356 ------------------------- cdp/overlay/__init__.py | 0 cdp/overlay/commands.py | 367 ------- cdp/overlay/events.py | 94 -- cdp/overlay/types.py | 132 --- cdp/page/__init__.py | 0 cdp/page/commands.py | 1112 -------------------- cdp/page/events.py | 530 ---------- cdp/page/types.py | 638 ------------ cdp/performance/__init__.py | 0 cdp/performance/commands.py | 70 -- cdp/performance/events.py | 40 - cdp/performance/types.py | 41 - cdp/profiler/__init__.py | 0 cdp/profiler/commands.py | 163 --- cdp/profiler/events.py | 72 -- cdp/profiler/types.py | 307 ------ cdp/runtime/__init__.py | 0 cdp/runtime/commands.py | 606 ----------- cdp/runtime/events.py | 210 ---- cdp/runtime/types.py | 732 ------------- cdp/schema/__init__.py | 0 cdp/schema/commands.py | 30 - cdp/schema/events.py | 17 - cdp/schema/types.py | 41 - cdp/security/__init__.py | 0 cdp/security/commands.py | 96 -- cdp/security/events.py | 92 -- cdp/security/types.py | 184 ---- cdp/service_worker/__init__.py | 0 cdp/service_worker/commands.py | 216 ---- cdp/service_worker/events.py | 62 -- cdp/service_worker/types.py | 188 ---- cdp/storage/__init__.py | 0 cdp/storage/commands.py | 139 --- cdp/storage/events.py | 105 -- cdp/storage/types.py | 65 -- cdp/system_info/__init__.py | 0 cdp/system_info/commands.py | 55 - cdp/system_info/events.py | 17 - cdp/system_info/types.py | 131 --- cdp/target/__init__.py | 0 cdp/target/commands.py | 359 ------- cdp/target/events.py | 189 ---- cdp/target/types.py | 121 --- cdp/tethering/__init__.py | 0 cdp/tethering/commands.py | 54 - cdp/tethering/events.py | 40 - cdp/tethering/types.py | 16 - cdp/tracing/__init__.py | 0 cdp/tracing/commands.py | 122 --- cdp/tracing/events.py | 98 -- cdp/tracing/types.py | 130 --- cdp/web_audio/__init__.py | 0 cdp/web_audio/commands.py | 58 -- cdp/web_audio/events.py | 74 -- cdp/web_audio/types.py | 142 --- cdp/web_authn/__init__.py | 0 cdp/web_authn/commands.py | 39 - cdp/web_authn/events.py | 17 - cdp/web_authn/types.py | 16 - 176 files changed, 23792 deletions(-) delete mode 100644 cdp/accessibility/__init__.py delete mode 100644 cdp/accessibility/commands.py delete mode 100644 cdp/accessibility/events.py delete mode 100644 cdp/accessibility/types.py delete mode 100644 cdp/animation/__init__.py delete mode 100644 cdp/animation/commands.py delete mode 100644 cdp/animation/events.py delete mode 100644 cdp/animation/types.py delete mode 100644 cdp/application_cache/__init__.py delete mode 100644 cdp/application_cache/commands.py delete mode 100644 cdp/application_cache/events.py delete mode 100644 cdp/application_cache/types.py delete mode 100644 cdp/audits/__init__.py delete mode 100644 cdp/audits/commands.py delete mode 100644 cdp/audits/events.py delete mode 100644 cdp/audits/types.py delete mode 100644 cdp/background_service/__init__.py delete mode 100644 cdp/background_service/commands.py delete mode 100644 cdp/background_service/events.py delete mode 100644 cdp/background_service/types.py delete mode 100644 cdp/browser/__init__.py delete mode 100644 cdp/browser/commands.py delete mode 100644 cdp/browser/events.py delete mode 100644 cdp/browser/types.py delete mode 100644 cdp/cache_storage/__init__.py delete mode 100644 cdp/cache_storage/commands.py delete mode 100644 cdp/cache_storage/events.py delete mode 100644 cdp/cache_storage/types.py delete mode 100644 cdp/cast/__init__.py delete mode 100644 cdp/cast/commands.py delete mode 100644 cdp/cast/events.py delete mode 100644 cdp/cast/types.py delete mode 100644 cdp/console/__init__.py delete mode 100644 cdp/console/commands.py delete mode 100644 cdp/console/events.py delete mode 100644 cdp/console/types.py delete mode 100644 cdp/css/__init__.py delete mode 100644 cdp/css/commands.py delete mode 100644 cdp/css/events.py delete mode 100644 cdp/css/types.py delete mode 100644 cdp/database/__init__.py delete mode 100644 cdp/database/commands.py delete mode 100644 cdp/database/events.py delete mode 100644 cdp/database/types.py delete mode 100644 cdp/debugger/__init__.py delete mode 100644 cdp/debugger/commands.py delete mode 100644 cdp/debugger/events.py delete mode 100644 cdp/debugger/types.py delete mode 100644 cdp/device_orientation/__init__.py delete mode 100644 cdp/device_orientation/commands.py delete mode 100644 cdp/device_orientation/events.py delete mode 100644 cdp/device_orientation/types.py delete mode 100644 cdp/dom/__init__.py delete mode 100644 cdp/dom/commands.py delete mode 100644 cdp/dom/events.py delete mode 100644 cdp/dom/types.py delete mode 100644 cdp/dom_debugger/__init__.py delete mode 100644 cdp/dom_debugger/commands.py delete mode 100644 cdp/dom_debugger/events.py delete mode 100644 cdp/dom_debugger/types.py delete mode 100644 cdp/dom_snapshot/__init__.py delete mode 100644 cdp/dom_snapshot/commands.py delete mode 100644 cdp/dom_snapshot/events.py delete mode 100644 cdp/dom_snapshot/types.py delete mode 100644 cdp/dom_storage/__init__.py delete mode 100644 cdp/dom_storage/commands.py delete mode 100644 cdp/dom_storage/events.py delete mode 100644 cdp/dom_storage/types.py delete mode 100644 cdp/emulation/__init__.py delete mode 100644 cdp/emulation/commands.py delete mode 100644 cdp/emulation/events.py delete mode 100644 cdp/emulation/types.py delete mode 100644 cdp/fetch/__init__.py delete mode 100644 cdp/fetch/commands.py delete mode 100644 cdp/fetch/events.py delete mode 100644 cdp/fetch/types.py delete mode 100644 cdp/headless_experimental/__init__.py delete mode 100644 cdp/headless_experimental/commands.py delete mode 100644 cdp/headless_experimental/events.py delete mode 100644 cdp/headless_experimental/types.py delete mode 100644 cdp/heap_profiler/__init__.py delete mode 100644 cdp/heap_profiler/commands.py delete mode 100644 cdp/heap_profiler/events.py delete mode 100644 cdp/heap_profiler/types.py delete mode 100644 cdp/indexed_db/__init__.py delete mode 100644 cdp/indexed_db/commands.py delete mode 100644 cdp/indexed_db/events.py delete mode 100644 cdp/indexed_db/types.py delete mode 100644 cdp/input/__init__.py delete mode 100644 cdp/input/commands.py delete mode 100644 cdp/input/events.py delete mode 100644 cdp/input/types.py delete mode 100644 cdp/inspector/__init__.py delete mode 100644 cdp/inspector/commands.py delete mode 100644 cdp/inspector/events.py delete mode 100644 cdp/inspector/types.py delete mode 100644 cdp/io/__init__.py delete mode 100644 cdp/io/commands.py delete mode 100644 cdp/io/events.py delete mode 100644 cdp/io/types.py delete mode 100644 cdp/layer_tree/__init__.py delete mode 100644 cdp/layer_tree/commands.py delete mode 100644 cdp/layer_tree/events.py delete mode 100644 cdp/layer_tree/types.py delete mode 100644 cdp/log/__init__.py delete mode 100644 cdp/log/commands.py delete mode 100644 cdp/log/events.py delete mode 100644 cdp/log/types.py delete mode 100644 cdp/memory/__init__.py delete mode 100644 cdp/memory/commands.py delete mode 100644 cdp/memory/events.py delete mode 100644 cdp/memory/types.py delete mode 100644 cdp/network/__init__.py delete mode 100644 cdp/network/commands.py delete mode 100644 cdp/network/events.py delete mode 100644 cdp/network/types.py delete mode 100644 cdp/overlay/__init__.py delete mode 100644 cdp/overlay/commands.py delete mode 100644 cdp/overlay/events.py delete mode 100644 cdp/overlay/types.py delete mode 100644 cdp/page/__init__.py delete mode 100644 cdp/page/commands.py delete mode 100644 cdp/page/events.py delete mode 100644 cdp/page/types.py delete mode 100644 cdp/performance/__init__.py delete mode 100644 cdp/performance/commands.py delete mode 100644 cdp/performance/events.py delete mode 100644 cdp/performance/types.py delete mode 100644 cdp/profiler/__init__.py delete mode 100644 cdp/profiler/commands.py delete mode 100644 cdp/profiler/events.py delete mode 100644 cdp/profiler/types.py delete mode 100644 cdp/runtime/__init__.py delete mode 100644 cdp/runtime/commands.py delete mode 100644 cdp/runtime/events.py delete mode 100644 cdp/runtime/types.py delete mode 100644 cdp/schema/__init__.py delete mode 100644 cdp/schema/commands.py delete mode 100644 cdp/schema/events.py delete mode 100644 cdp/schema/types.py delete mode 100644 cdp/security/__init__.py delete mode 100644 cdp/security/commands.py delete mode 100644 cdp/security/events.py delete mode 100644 cdp/security/types.py delete mode 100644 cdp/service_worker/__init__.py delete mode 100644 cdp/service_worker/commands.py delete mode 100644 cdp/service_worker/events.py delete mode 100644 cdp/service_worker/types.py delete mode 100644 cdp/storage/__init__.py delete mode 100644 cdp/storage/commands.py delete mode 100644 cdp/storage/events.py delete mode 100644 cdp/storage/types.py delete mode 100644 cdp/system_info/__init__.py delete mode 100644 cdp/system_info/commands.py delete mode 100644 cdp/system_info/events.py delete mode 100644 cdp/system_info/types.py delete mode 100644 cdp/target/__init__.py delete mode 100644 cdp/target/commands.py delete mode 100644 cdp/target/events.py delete mode 100644 cdp/target/types.py delete mode 100644 cdp/tethering/__init__.py delete mode 100644 cdp/tethering/commands.py delete mode 100644 cdp/tethering/events.py delete mode 100644 cdp/tethering/types.py delete mode 100644 cdp/tracing/__init__.py delete mode 100644 cdp/tracing/commands.py delete mode 100644 cdp/tracing/events.py delete mode 100644 cdp/tracing/types.py delete mode 100644 cdp/web_audio/__init__.py delete mode 100644 cdp/web_audio/commands.py delete mode 100644 cdp/web_audio/events.py delete mode 100644 cdp/web_audio/types.py delete mode 100644 cdp/web_authn/__init__.py delete mode 100644 cdp/web_authn/commands.py delete mode 100644 cdp/web_authn/events.py delete mode 100644 cdp/web_authn/types.py diff --git a/cdp/accessibility/__init__.py b/cdp/accessibility/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/cdp/accessibility/commands.py b/cdp/accessibility/commands.py deleted file mode 100644 index 49ce42d..0000000 --- a/cdp/accessibility/commands.py +++ /dev/null @@ -1,88 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: accessibility -Experimental: True -''' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -from .types import * -from ..dom import types as dom -from ..runtime import types as runtime - - - -def disable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: - ''' - Disables the accessibility domain. - ''' - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.disable', - } - json = yield cmd_dict - - -def enable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: - ''' - Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls. - This turns on accessibility for the page, which can impact performance until accessibility is disabled. - ''' - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.enable', - } - json = yield cmd_dict - - -def get_partial_ax_tree( - node_id: typing.Optional[dom.NodeId] = None, - backend_node_id: typing.Optional[dom.BackendNodeId] = None, - object_id: typing.Optional[runtime.RemoteObjectId] = None, - fetch_relatives: typing.Optional[bool] = None, - ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.List['AXNode']]: - ''' - Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. - - :param node_id: Identifier of the node to get the partial accessibility tree for. - :param backend_node_id: Identifier of the backend node to get the partial accessibility tree for. - :param object_id: JavaScript object id of the node wrapper to get the partial accessibility tree for. - :param fetch_relatives: Whether to fetch this nodes ancestors, siblings and children. Defaults to true. - :returns: The `Accessibility.AXNode` for this DOM node, if it exists, plus its ancestors, siblings and - children, if requested. - ''' - params: T_JSON_DICT = { - } - if node_id is not None: - params['nodeId'] = node_id.to_json() - if backend_node_id is not None: - params['backendNodeId'] = backend_node_id.to_json() - if object_id is not None: - params['objectId'] = object_id.to_json() - if fetch_relatives is not None: - params['fetchRelatives'] = fetch_relatives - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.getPartialAXTree', - 'params': params, - } - json = yield cmd_dict - return [AXNode.from_json(i) for i in json['nodes']] - - -def get_full_ax_tree() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.List['AXNode']]: - ''' - Fetches the entire accessibility tree - :returns: - ''' - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.getFullAXTree', - } - json = yield cmd_dict - return [AXNode.from_json(i) for i in json['nodes']] - - diff --git a/cdp/accessibility/events.py b/cdp/accessibility/events.py deleted file mode 100644 index ceb8207..0000000 --- a/cdp/accessibility/events.py +++ /dev/null @@ -1,17 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: accessibility -Experimental: True -''' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -from .types import * - diff --git a/cdp/accessibility/types.py b/cdp/accessibility/types.py deleted file mode 100644 index 60b56a1..0000000 --- a/cdp/accessibility/types.py +++ /dev/null @@ -1,411 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: accessibility -Experimental: True -''' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -from ..dom import types as dom - - -class AXNodeId(str): - ''' - Unique accessibility node identifier. - ''' - def to_json(self) -> str: - return self - - @classmethod - def from_json(cls, json: str) -> 'AXNodeId': - return cls(json) - - def __repr__(self): - return 'AXNodeId({})'.format(super().__repr__()) - - -class AXValueType(enum.Enum): - ''' - Enum of possible property types. - ''' - BOOLEAN = "boolean" - TRISTATE = "tristate" - BOOLEAN_OR_UNDEFINED = "booleanOrUndefined" - IDREF = "idref" - IDREF_LIST = "idrefList" - INTEGER = "integer" - NODE = "node" - NODE_LIST = "nodeList" - NUMBER = "number" - STRING = "string" - COMPUTED_STRING = "computedString" - TOKEN = "token" - TOKEN_LIST = "tokenList" - DOM_RELATION = "domRelation" - ROLE = "role" - INTERNAL_ROLE = "internalRole" - VALUE_UNDEFINED = "valueUndefined" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXValueType': - return cls(json) - - -class AXValueSourceType(enum.Enum): - ''' - Enum of possible property sources. - ''' - ATTRIBUTE = "attribute" - IMPLICIT = "implicit" - STYLE = "style" - CONTENTS = "contents" - PLACEHOLDER = "placeholder" - RELATED_ELEMENT = "relatedElement" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXValueSourceType': - return cls(json) - - -class AXValueNativeSourceType(enum.Enum): - ''' - Enum of possible native property sources (as a subtype of a particular AXValueSourceType). - ''' - FIGCAPTION = "figcaption" - LABEL = "label" - LABELFOR = "labelfor" - LABELWRAPPED = "labelwrapped" - LEGEND = "legend" - TABLECAPTION = "tablecaption" - TITLE = "title" - OTHER = "other" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXValueNativeSourceType': - return cls(json) - - -class AXPropertyName(enum.Enum): - ''' - Values of AXProperty name: - - from 'busy' to 'roledescription': states which apply to every AX node - - from 'live' to 'root': attributes which apply to nodes in live regions - - from 'autocomplete' to 'valuetext': attributes which apply to widgets - - from 'checked' to 'selected': states which apply to widgets - - from 'activedescendant' to 'owns' - relationships between elements other than parent/child/sibling. - ''' - BUSY = "busy" - DISABLED = "disabled" - EDITABLE = "editable" - FOCUSABLE = "focusable" - FOCUSED = "focused" - HIDDEN = "hidden" - HIDDEN_ROOT = "hiddenRoot" - INVALID = "invalid" - KEYSHORTCUTS = "keyshortcuts" - SETTABLE = "settable" - ROLEDESCRIPTION = "roledescription" - LIVE = "live" - ATOMIC = "atomic" - RELEVANT = "relevant" - ROOT = "root" - AUTOCOMPLETE = "autocomplete" - HAS_POPUP = "hasPopup" - LEVEL = "level" - MULTISELECTABLE = "multiselectable" - ORIENTATION = "orientation" - MULTILINE = "multiline" - READONLY = "readonly" - REQUIRED = "required" - VALUEMIN = "valuemin" - VALUEMAX = "valuemax" - VALUETEXT = "valuetext" - CHECKED = "checked" - EXPANDED = "expanded" - MODAL = "modal" - PRESSED = "pressed" - SELECTED = "selected" - ACTIVEDESCENDANT = "activedescendant" - CONTROLS = "controls" - DESCRIBEDBY = "describedby" - DETAILS = "details" - ERRORMESSAGE = "errormessage" - FLOWTO = "flowto" - LABELLEDBY = "labelledby" - OWNS = "owns" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXPropertyName': - return cls(json) - - -@dataclass -class AXRelatedNode: - #: The BackendNodeId of the related DOM node. - backend_dom_node_id: dom.BackendNodeId - - #: The IDRef value provided, if any. - idref: typing.Optional[str] = None - - #: The text alternative of this node in the current context. - text: typing.Optional[str] = None - - def to_json(self) -> T_JSON_DICT: - json: T_JSON_DICT = { - 'backendDOMNodeId': self.backend_dom_node_id.to_json(), - } - if self.idref is not None: - json['idref'] = self.idref - if self.text is not None: - json['text'] = self.text - return json - - @classmethod - def from_json(cls, json: T_JSON_DICT) -> 'AXRelatedNode': - idref = json['idref'] if 'idref' in json else None - text = json['text'] if 'text' in json else None - return cls( - backend_dom_node_id=dom.BackendNodeId.from_json(json['backendDOMNodeId']), - idref=idref, - text=text, - ) - -@dataclass -class AXValue: - ''' - A single computed AX property. - ''' - #: The type of this value. - type: AXValueType - - #: The computed value of this property. - value: typing.Optional[typing.Any] = None - - #: One or more related nodes, if applicable. - related_nodes: typing.Optional[typing.List['AXRelatedNode']] = None - - #: The sources which contributed to the computation of this property. - sources: typing.Optional[typing.List['AXValueSource']] = None - - def to_json(self) -> T_JSON_DICT: - json: T_JSON_DICT = { - 'type': self.type.to_json(), - } - if self.value is not None: - json['value'] = self.value - if self.related_nodes is not None: - json['relatedNodes'] = [i.to_json() for i in self.related_nodes] - if self.sources is not None: - json['sources'] = [i.to_json() for i in self.sources] - return json - - @classmethod - def from_json(cls, json: T_JSON_DICT) -> 'AXValue': - value = json['value'] if 'value' in json else None - related_nodes = [AXRelatedNode.from_json(i) for i in json['relatedNodes']] if 'relatedNodes' in json else None - sources = [AXValueSource.from_json(i) for i in json['sources']] if 'sources' in json else None - return cls( - type=AXValueType.from_json(json['type']), - value=value, - related_nodes=related_nodes, - sources=sources, - ) - -@dataclass -class AXNode: - ''' - A node in the accessibility tree. - ''' - #: Unique identifier for this node. - node_id: AXNodeId - - #: Whether this node is ignored for accessibility - ignored: bool - - #: Collection of reasons why this node is hidden. - ignored_reasons: typing.Optional[typing.List['AXProperty']] = None - - #: This `Node`'s role, whether explicit or implicit. - role: typing.Optional[AXValue] = None - - #: The accessible name for this `Node`. - name: typing.Optional[AXValue] = None - - #: The accessible description for this `Node`. - description: typing.Optional[AXValue] = None - - #: The value for this `Node`. - value: typing.Optional[AXValue] = None - - #: All other properties - properties: typing.Optional[typing.List['AXProperty']] = None - - #: IDs for each of this node's child nodes. - child_ids: typing.Optional[typing.List['AXNodeId']] = None - - #: The backend ID for the associated DOM node, if any. - backend_dom_node_id: typing.Optional[dom.BackendNodeId] = None - - def to_json(self) -> T_JSON_DICT: - json: T_JSON_DICT = { - 'nodeId': self.node_id.to_json(), - 'ignored': self.ignored, - } - if self.ignored_reasons is not None: - json['ignoredReasons'] = [i.to_json() for i in self.ignored_reasons] - if self.role is not None: - json['role'] = self.role.to_json() - if self.name is not None: - json['name'] = self.name.to_json() - if self.description is not None: - json['description'] = self.description.to_json() - if self.value is not None: - json['value'] = self.value.to_json() - if self.properties is not None: - json['properties'] = [i.to_json() for i in self.properties] - if self.child_ids is not None: - json['childIds'] = [i.to_json() for i in self.child_ids] - if self.backend_dom_node_id is not None: - json['backendDOMNodeId'] = self.backend_dom_node_id.to_json() - return json - - @classmethod - def from_json(cls, json: T_JSON_DICT) -> 'AXNode': - ignored_reasons = [AXProperty.from_json(i) for i in json['ignoredReasons']] if 'ignoredReasons' in json else None - role = AXValue.from_json(json['role']) if 'role' in json else None - name = AXValue.from_json(json['name']) if 'name' in json else None - description = AXValue.from_json(json['description']) if 'description' in json else None - value = AXValue.from_json(json['value']) if 'value' in json else None - properties = [AXProperty.from_json(i) for i in json['properties']] if 'properties' in json else None - child_ids = [AXNodeId.from_json(i) for i in json['childIds']] if 'childIds' in json else None - backend_dom_node_id = dom.BackendNodeId.from_json(json['backendDOMNodeId']) if 'backendDOMNodeId' in json else None - return cls( - node_id=AXNodeId.from_json(json['nodeId']), - ignored=json['ignored'], - ignored_reasons=ignored_reasons, - role=role, - name=name, - description=description, - value=value, - properties=properties, - child_ids=child_ids, - backend_dom_node_id=backend_dom_node_id, - ) - -@dataclass -class AXValueSource: - ''' - A single source for a computed AX property. - ''' - #: What type of source this is. - type: AXValueSourceType - - #: The value of this property source. - value: typing.Optional[AXValue] = None - - #: The name of the relevant attribute, if any. - attribute: typing.Optional[str] = None - - #: The value of the relevant attribute, if any. - attribute_value: typing.Optional[AXValue] = None - - #: Whether this source is superseded by a higher priority source. - superseded: typing.Optional[bool] = None - - #: The native markup source for this value, e.g. a