How to use serialize_argument method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

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

test_decorator.py

Source: test_decorator.py Github

copy
1import re
2
3from argo_dsl.decorator import *
4from argo_dsl.template import new_parameters
5
6
7def test_script_decorator():
8    @script_template(image="ubuntu", command="cat", pre_run="echo start", post_run="echo done")
9    def script(a: str, b: int = 2):
10        """
11        hello world
12        """
13
14    class Parameters:
15        a: str
16        b: int = 2
17
18    assert issubclass(script, ScriptTemplate)
19    assert script.image == "ubuntu"
20    assert script.name == "script"
21    assert new_parameters(script.Parameters) == new_parameters(Parameters)
22    assert (
23        script().manifest.source
24        == """\
25cat > /tmp/script << EOL
26hello world
27EOL
28
29set -e
30
31echo start
32cat /tmp/script
33echo done"""
34    )
35
36    assert script().serialize_argument(1) == "1"
37
38
39def test_bash_decorator():
40    @bash_template(image="ubuntu")
41    def echo(a: str, b: int = 2):
42        """
43        echo $a, $b
44        """
45
46    assert (
47        echo().manifest.source
48        == """\
49cat > /tmp/script << EOL
50a="{{inputs.parameters.a}}"
51b="{{inputs.parameters.b}}"
52echo $a, $b
53EOL
54
55set -e
56
57
58bash /tmp/script"""
59    )
60
61
62def test_python_decorator_with_parameters():
63    @python_template(image="python")
64    def print_result(
65        a: str,
66        b: int = 2,
67        c: float = 3.3,
68        d: bool = False,
69        e: complex = 2j,
70        f: re.Pattern = re.compile("abc"),
71        g: v1alpha1.ValueFrom = v1alpha1.ValueFrom(default="4"),
72    ):
73        print(a * b)
74
75    assert (
76        print_result().manifest.source
77        == """\
78cat > /tmp/script << EOL
79import pickle
80a = "{{inputs.parameters.a}}"
81b = {{inputs.parameters.b}}
82c = {{inputs.parameters.c}}
83d = {{inputs.parameters.d}}
84e = {{inputs.parameters.e}}
85f = pickle.loads(bytearray.fromhex("{{inputs.parameters.f}}"), protocol=None)
86g = "{{inputs.parameters.g}}"
87
88print(a * b)
89EOL
90
91set -e
92
93
94python /tmp/script"""
95    )
96
97    assert print_result().serialize_argument("a") == "a"
98    assert print_result().serialize_argument(1) == "1"
99    assert print_result().serialize_argument(1.1) == "1.1"
100    assert print_result().serialize_argument(2j) == "2j"
101    assert print_result().serialize_argument(True) == "True"
102    assert print_result().serialize_argument(re.compile("abc")) == str(pickle.dumps(re.compile("abc")).hex())
103
104    assert new_parameters(print_result.Parameters) == [
105        v1alpha1.Parameter(name="a"),
106        v1alpha1.Parameter(name="b", default="2"),
107        v1alpha1.Parameter(name="c", default="3.3"),
108        v1alpha1.Parameter(name="d", default="False"),
109        v1alpha1.Parameter(name="e", default="2j"),
110        v1alpha1.Parameter(name="f", default=str(pickle.dumps(re.compile("abc")).hex())),
111        v1alpha1.Parameter(name="g", valueFrom=v1alpha1.ValueFrom(default="4")),
112    ]
113
114
115def test_python_decorator_with_builtin_parameters():
116    @python_template(image="python")
117    def print_result(
118        a: str,
119        b: int = 2,
120    ):
121        print(a * b)
122
123    assert (
124        print_result().manifest.source
125        == """\
126cat > /tmp/script << EOL
127a = "{{inputs.parameters.a}}"
128b = {{inputs.parameters.b}}
129
130print(a * b)
131EOL
132
133set -e
134
135
136python /tmp/script"""
137    )
138
139
140def test_python_decorator_without_parameters():
141    @python_template(image="python")
142    def print_str():
143        print("Hello World")
144
145    assert (
146        print_str().manifest.source
147        == """\
148cat > /tmp/script << EOL
149print("Hello World")
150EOL
151
152set -e
153
154
155python /tmp/script"""
156    )
157
158
159def test_resource_decorator_with_parameters():
160    @resource_template(action="get")
161    def get_pod(name):
162        """
163        apiVersion: v1
164        kind: Pod
165        metadata:
166          name: {{inputs.parameters.name}}
167        """
168
169    assert (
170        get_pod().resource_manifest
171        == """\
172apiVersion: v1
173kind: Pod
174metadata:
175  name: {{inputs.parameters.name}}"""
176    )
177    assert get_pod().name == "get_pod"
178    assert new_parameters(get_pod.Parameters) == [
179        v1alpha1.Parameter(name="name"),
180    ]
181
182
183def test_resource_decorator_without_parameters():
184    @resource_template(action="get")
185    def get_pod():
186        """
187        apiVersion: v1
188        kind: Pod
189        metadata:
190          name: demo
191        """
192
193    assert (
194        get_pod().resource_manifest
195        == """\
196apiVersion: v1
197kind: Pod
198metadata:
199  name: demo"""
200    )
201
202
203def test_hook():
204    class image(Hook):
205        image: str
206
207        def hook(self) -> Callable[[v1alpha1.Template], v1alpha1.Template]:
208            def add_image(template: v1alpha1.Template) -> v1alpha1.Template:
209                template.script.image = "test"
210                return template
211
212            return add_image
213
214    @image(image="test")
215    @script_template(image="ubuntu")
216    def script():
217        ...
218
219    assert script().template.script.image == "test"
220
Full Screen

base_analyses.py

Source: base_analyses.py Github

copy
1from functools import lru_cache
2from typing import NamedTuple, Dict, Tuple
3
4
5class Polymer:
6    pass
7
8# domain, chain, subsets of polymers
9
10class Ligand:
11    pass
12# get_atoms
13
14
15# class AnalysisArgs:
16#     # bud RAII nebo metoda run
17#     def __init__(self, *args, **kwargs):
18#         pass
19#
20#     def serialize(self):
21#         """ Returns analysis name and serialized arguments """
22#         pass
23#
24#
25# class AnalysisResult:
26#     # tohle spis bude metoda na Analyzer -> serializeResult
27#     # protoze nechci vzdycky delat Analyzer()(args).value ...
28#
29#     def serialize(self):
30#         pass
31#     #
32#     # def value(self):
33#     #     pass
34
35
36class Analyzer:
37    """ Instance behaves like a function.
38
39    Use analyzer_instance(arg1, arg2) to get the result. """
40    dependencies: Tuple['Analyzer', ...]
41
42    def __init__(self, dependencies: Tuple['Analyzer', ...] = ()):
43        self.dependencies = dependencies
44
45    def __call__(self, *args, **kwargs):
46        """ Use this """
47        return self.run(*args, *self.dependencies, **kwargs)
48
49    def run(self, *args, **kwargs):
50        """ Provide your own method. """
51        raise NotImplementedError
52
53    def get_name(self):
54        return type(self).__name__
55
56
57class CachedAnalyzer(Analyzer):
58    """ Holds instances of analyses and their results. Analyses are run though this object. But then -- parallelization? Serialization?"""
59
60    def __call__(self, *args, **kwargs):
61        return self.analysis_cached_run(*args, **kwargs)
62
63    # @lru_cache(maxsize=None)
64    def analysis_cached_run(self, *args, **kwargs):
65        return super().__call__(*args, **kwargs)
66
67
68class SerializableAnalyzer(Analyzer):
69    def serialize(self, result, *args, **kwargs):
70        """ default implementation assumes result, args and kwargs are primitive types, therefore know how to serialize to a string value.
71
72        :param result: result of __call__/run
73        :param args: for now: arbitrary args, serve as identifier for an analysis result in the serialized data. (Don't need to be actual args to __call__/run)
74        :param kwargs: similar as args
75        :return: a potentially nested dict/list of primitive types
76        """
77
78        def serialize_argument(a):
79            try:
80                return a.serialize()  # třeba takhle přidat custom argumenty, ktery se budou umet serializovat? Mozna to jeste muzu ujasnit pomoci typing?
81            except AttributeError:
82                return a
83
84        serialized_args = [serialize_argument(a) for a in args]
85        serialized_kwargs = {k: serialize_argument(v) for k, v in kwargs.items()}
86
87        return {'analysis_name': self.get_name(), 'args': serialized_args, 'kwargs': serialized_kwargs, 'result': result}  # jeste serialize result?
88
89
90
91class SerializableCachedAnalyzer(CachedAnalyzer, SerializableAnalyzer):
92    pass
93
94
95
96# do budoucna -- mohu udělat dekorátor, který z funkce udělá  Analyzer classu, (dobrý nápad??), dependencies a base classa jako parametry decorátoru, funkce pak bude brát ty dependecies
97# spíš než dekorátor možná
98
99# serializace - non-output mohou mít i třeba pickle?
100#      - volá se při prvním výsledku analýzy (v třídě Analyzer). Serializace teoreticky může být do různých formátů, mám ale json (a možná pickle)
101# jednoznačná identifikace argumentů??
102    # is - equality? (nebude fungovat po un-picklování file-cached dat)
103# Jednotlivé analyzery -- depedency injection?
104# definovat - instance do proměnných a proměnné do dependencies i celkového seznamu analyzátorů (projde se a vykoná analýzy)
105# zatim cached podle __hash__ argumentů, tzn. povětšinou in-memory identity objektu (do budoucna lze předefinovat __hash__ na contents AnalysisResult
106#
107#
108# @wrap_in_analyzer(CachedAnalyzer)
109# def get_ligands(struct):
110#     return itertools.chain(get_hetero_atom_residues(struct), get_short_peptide_ligands(struct, 15))
111#
112
Full Screen

decorator.py

Source: decorator.py Github

copy
1import pickle
2
3from typing import Any
4from typing import Callable
5from typing import ClassVar
6from typing import Dict
7from typing import Generic
8from typing import List
9from typing import Optional
10from typing import Type
11from typing import TypeVar
12
13from pydantic import BaseModel
14from pydantic import PrivateAttr
15from pydantic.generics import GenericModel
16from typing_extensions import Literal
17
18from .api.io.argoproj.workflow import v1alpha1
19from .template import ResourceTemplate
20from .template import ScriptTemplate
21from .template import Template
22from .utils import Function
23
24
25_T = TypeVar("_T", bound=Template)
26
27
28class TemplateDecorator(BaseModel, Generic[_T]):
29    _func: Function = PrivateAttr()
30
31    @property
32    def func(self) -> Function:
33        return self._func
34
35    def __call__(
36        self,
37        func: Callable[..., Optional[str]],
38    ) -> Type[_T]:
39        self._func = Function(func)
40        return self.generate_template()
41
42    def generate_template(self) -> Type[_T]:
43        raise NotImplementedError
44
45    def generate_parameter_class(self) -> type:
46        return self.func.parameter_class
47
48
49class ScriptDecorator(TemplateDecorator[ScriptTemplate]):
50    image: str
51    command: str = ""
52    pre_run: str = ""
53    post_run: str = ""
54
55    def generate_template(self) -> Type[ScriptTemplate]:
56        source = self.generate_source()
57        source = f"""\
58cat > /tmp/script << EOL
59{source}
60EOL
61
62set -e
63
64{self.pre_run}
65{self.command} /tmp/script
66{self.post_run}
67""".strip()
68        decorator = self
69
70        class Script(ScriptTemplate):
71            image = decorator.image
72            name: ClassVar[str] = decorator.func.name
73            Parameters = decorator.generate_parameter_class()
74
75            def specify_manifest(self) -> v1alpha1.ScriptTemplate:
76                return v1alpha1.ScriptTemplate(image=self.image, source=source, command=["bash"])
77
78            def serialize_argument(self, argument: Any) -> str:
79                return decorator.serialize_argument(argument)
80
81        return Script
82
83    def generate_source(self) -> str:
84        return self.func.docstring or self.func.return_value or ""
85
86    def serialize_argument(self, argument: Any) -> str:
87        return str(argument)
88
89
90script_template = ScriptDecorator
91
92
93class BashDecorator(ScriptDecorator):
94    command: str = "bash"
95
96    def generate_source(self) -> str:
97        source = super().generate_source()
98        parameters = ['%s="{{inputs.parameters.%s}}"' % (parameter, parameter) for parameter in self.func.parameters]
99        source = "\n".join(parameters) + "\n" + source
100
101        return source
102
103
104bash_template = BashDecorator
105
106
107class PythonDecorator(ScriptDecorator):
108    command: str = "python"
109    pickle_protocol: Optional[int] = None
110
111    def generate_source(self) -> str:
112        source = self.func.body.strip()
113        parameter_class = self.func.parameter_class
114
115        is_value_from_param = lambda name, annotation: annotation == v1alpha1.ValueFrom or isinstance(
116            getattr(parameter_class, name, None), v1alpha1.ValueFrom
117        )
118
119        codes = []
120        for param_name, param_annotation in parameter_class.__annotations__.items():
121            if is_value_from_param(param_name, param_annotation) or param_annotation == str:
122                codes.append('%s = "{{inputs.parameters.%s}}"' % (param_name, param_name))
123            elif param_annotation in [int, float, bool, complex]:
124                codes.append("%s = {{inputs.parameters.%s}}" % (param_name, param_name))
125            else:
126                if codes[0] != "import pickle":
127                    codes = ["import pickle"] + codes
128                codes.append(
129                    '%s = pickle.loads(bytearray.fromhex("{{inputs.parameters.%s}}"), protocol=%s)'
130                    % (param_name, param_name, self.pickle_protocol)
131                )
132
133        if self.func.parameters:
134            source = "\n".join(codes) + f"\n\n{source}"
135
136        return source
137
138    def generate_parameter_class(self) -> Type:
139        parameter_class = self.func.parameter_class
140        if not self.func.parameters:
141            return parameter_class
142
143        annotations = dict(parameter_class.__annotations__)
144
145        def serialize_default_value(v: Any):
146            if isinstance(v, v1alpha1.ValueFrom):
147                return v
148            else:
149                return self.serialize_argument(v)
150
151        default_fields: Dict[str, Any] = {
152            k: serialize_default_value(v) for k, v in parameter_class.__dict__.items() if not k.startswith("_")
153        }
154        return type("Parameters", (), {"__annotations__": annotations, **default_fields})
155
156    def serialize_argument(self, argument: Any) -> str:
157        if isinstance(argument, (str, int, float, bool, complex)):
158            return str(argument)
159        else:
160            return str(pickle.dumps(argument, protocol=self.pickle_protocol).hex())
161
162
163python_template = PythonDecorator
164
165
166class ResourceDecorator(TemplateDecorator[ResourceTemplate]):
167    action: Literal["get", "create", "apply", "delete", "replace", "patch"]
168    resource_manifest: Optional[str] = None
169    failureCondition: Optional[str] = None
170    flags: Optional[List[str]] = None
171    mergeStrategy: Optional[Literal["strategic", "merge", "json"]] = None
172    setOwnerReference: Optional[bool] = None
173    successCondition: Optional[str] = None
174
175    def generate_template(self) -> Type[ResourceTemplate]:
176        manifest = self.generate_manifest()
177
178        class Resource(ResourceTemplate):
179            name = self.func.name
180            Parameters = self.generate_parameter_class()
181            action = self.action
182            resource_manifest = manifest
183            failureCondition = self.failureCondition
184            flags = self.flags
185            mergeStrategy = self.mergeStrategy
186            setOwnerReference = self.setOwnerReference
187            successCondition = self.successCondition
188
189        return Resource
190
191    def generate_manifest(self) -> str:
192        return self.func.docstring or self.func.return_value or ""
193
194
195resource_template = ResourceDecorator
196
197
198class Hook(GenericModel, Generic[_T]):
199    def __call__(self, t: Type[_T]) -> Type[_T]:
200        class T(t):  # type: ignore
201            __hooks__ = t.__hooks__ + [self.hook()]
202
203        return T
204
205    def hook(self) -> Callable[[v1alpha1.Template], v1alpha1.Template]:
206        raise NotImplementedError
207
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)