How to use predicate 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.

predicate_merger.py

Source: predicate_merger.py Github

copy
1# Copyright (C) 2018-2019 DLR
2#
3# All rights reserved. This program and the accompanying materials are made
4# available under the terms of the 3-Clause BSD License which accompanies this
5# distribution, and is available at
6# https://opensource.org/licenses/BSD-3-Clause
7#
8# Contributors:
9# Christoph Suerig <[email protected]>
10
11# Don't connect with the Copyright comment above!
12# Version: 07.06.2019
13from rafcon.utils import log
14
15logger = log.get_logger(__name__)
16
17
18class PredicateMerger:
19    """
20    This class merges predicates with the same identifier, but different types of the same branch together.
21    """
22
23    __name_index = 0
24
25    def __init__(self, datastore):
26        """
27        :param datastore: A datastore containing available types.
28        """
29        self.__datastore = datastore
30
31    def merge_predicates(self, predicates):
32        """
33        Merge predicates merges all predicates, sets all available predicates in datastore
34        and returns all merged predicates as strings.
35
36        :param predicates: A list [string] with predicates.
37        :return: ([String],[(String,[(String,int)])]): A tuple (list [string] with merged predicates, and a list [of format ('LOCATED',[(VEHICLE,1),(PHYSOBJ,3)])] all available predicates)
38        """
39        if predicates is None:
40            raise ValueError('predicates can not be None!')
41        preds_map = {}
42        available_predicates = []
43        merged_preds_as_string = []
44        for predicate in predicates:
45            parsed_pred = self.__parse_predicate(predicate)
46            if parsed_pred[0] in preds_map.keys():
47                preds_map[parsed_pred[0]].append(parsed_pred)
48            else:
49                preds_map[parsed_pred[0]] = [parsed_pred]
50        for key in preds_map.keys():
51            c_pred = self.__reduce_predicate_list(preds_map[key])
52            available_predicates.append(c_pred)
53            merged_preds_as_string.append(self.__tuple_to_predicate_string(c_pred))
54        return (merged_preds_as_string, available_predicates)
55
56    def __parse_predicate(self, predicate_string):
57        """
58        parse_predicate gets a predicate string and parses it into a useful tuple of (predicate_Name,[(type_name,occurance)]).
59
60        :param predicate_string: A predicate as string e.g (LOCATED ?VEH - VEHICLE ?OBJ ?sObj ?thirdObj - PHYSOBJ).
61        :return: (String,[(String,int)]): A parsed predicate as tuple e.g. ('LOCATED',[(VEHICLE,1),(PHYSOBJ,3)]).
62        """
63        pred_name = None
64        pred_types = []
65        pred = predicate_string
66        if '(' in predicate_string and '?' in predicate_string:
67            start = predicate_string.index('(')
68            end = predicate_string.index('?')
69            if start + 1 >= end - 1:
70                logger.error("Can't parse predicate: " + predicate_string)
71                raise ValueError("Can't parse predicate: " + predicate_string)
72            pred_name = predicate_string[start + 1:end - 1].replace(' ', '')
73            pred = predicate_string[end:]
74        else:
75            logger.error("Can't parse predicate: " + predicate_string)
76            raise ValueError("Can't parse predicate: " + predicate_string)
77
78        if not '-' in pred:
79            logger.error("Can't parse predicate: " + predicate_string)
80            raise ValueError("Can't parse predicate: " + predicate_string)
81        while '-' in pred:
82            c_type_s = pred.index('-') + 1
83            c_type_e = 0
84            if '?' in pred[c_type_s:]:
85                c_type_e += pred[c_type_s:].index('?') + c_type_s
86            elif ')' in pred:
87                c_type_e += pred.index(')')
88            else:
89                logger.error("Can't parse predicate: " + predicate_string)
90                raise ValueError("Can't parse predicate: " + predicate_string)
91            pred_types.append((pred[c_type_s:c_type_e].replace(' ', ''), pred[:c_type_e].count('?')))
92            pred = pred[c_type_e:]
93        return (pred_name, pred_types)
94
95    def __reduce_predicate_list(self, predicate_list):
96        """
97        reduce_predicate_list gets a list of predicates, with the same name but different types,
98        and reduces them to one predicate, with the most open types.
99
100        :param predicate_list: A list of predicates with the same name, format: ('LOCATED',[(VEHICLE,1),(PHYSOBJ,3)])
101        :return: (String,[(String,int)]): One predicate tuple, containing the most general types. of format ('LOCATED',[(VEHICLE,1),(PHYSOBJ,3)])
102        """
103        type_tree = self.__datastore.get_available_types()
104        # the resulting predicate
105        result_predicate = predicate_list[0]
106
107        for predicate in predicate_list:
108            err_str = "Can't merge predicates, they are Incompatible! (variable names where changed) first: " + \
109                      self.__tuple_to_predicate_string(result_predicate) + \
110                      " second: " + self.__tuple_to_predicate_string(predicate)
111            # cant merge, if they have different names, or different number of argument types.
112            if result_predicate[0] != predicate[0] or len(result_predicate[1]) != len(predicate[1]):
113                logger.error(err_str)
114                raise ValueError(err_str)
115            for index, type_tuple in enumerate(predicate[1]):
116                # cant merge, if they have different number of arguments per type.
117                if type_tuple[1] != result_predicate[1][index][1]:
118                    logger.error(err_str)
119                    raise ValueError(err_str)
120                # try to merge the types used in predicates e.g. Robot or Vehicle
121                if result_predicate[1][index][0] != type_tuple[0]:
122                    smallest_parent = type_tree.get_smallest_parent(type_tuple[0], result_predicate[1][index][0])
123                    if smallest_parent:
124                        # set smallest_parent type as predicate type
125                        result_predicate[1][index] = (smallest_parent, result_predicate[1][index][1])
126                        # just to warn the user, that a predicate is a root-type-predicate.
127                        if (type_tree.get_parent_of(smallest_parent) is None):
128                            logger.warn('Predicate merged to root Type predicate: ' + self.__tuple_to_predicate_string(
129                                result_predicate))
130                    else:
131                        logger.error(err_str)
132                        raise ValueError(err_str)
133        return result_predicate
134
135    def __tuple_to_predicate_string(self, predicate_tuple):
136        """
137        Receives a predicate tuple and returns it as predicate string.
138
139        :param predicate_tuple: A tuple in format (PREDICATE_NAME,[(TYPE,NUM_VARIABLES)])
140        :return: String: A predicate string e.g (PREDICATENAME ?0 ?1 - Type).
141        """
142        pred_string = '(' + predicate_tuple[0]
143        tuple_counter = 0  # need this counter do guarantee distinct variable names.
144        for type_tup in predicate_tuple[1]:
145            variable_counter = 0
146            tuple_counter += 1
147            while variable_counter < type_tup[
148                1]:  # NUM_VARIABLES: type_tup[1] contains the number of variables of one type.
149                pred_string += ' ?' + type_tup[0][:1] + str(tuple_counter) + str(variable_counter)
150                variable_counter += 1
151            pred_string += ' - ' + type_tup[0]
152        pred_string += ')'
153        return str(pred_string)
154
Full Screen

exclusions.py

Source: exclusions.py Github

copy
1# testing/exclusions.py
2# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
3#
4# This module is part of SQLAlchemy and is released under
5# the MIT License: http://www.opensource.org/licenses/mit-license.php
6
7
8import operator
9from .plugin.plugin_base import SkipTest
10from ..util import decorator
11from . import config
12from .. import util
13import contextlib
14import inspect
15
16class skip_if(object):
17    def __init__(self, predicate, reason=None):
18        self.predicate = _as_predicate(predicate)
19        self.reason = reason
20
21    _fails_on = None
22
23    def __add__(self, other):
24        def decorate(fn):
25            return other(self(fn))
26        return decorate
27
28    @property
29    def enabled(self):
30        return self.enabled_for_config(config._current)
31
32    def enabled_for_config(self, config):
33        return not self.predicate(config)
34
35    @contextlib.contextmanager
36    def fail_if(self, name='block'):
37        try:
38            yield
39        except Exception as ex:
40            if self.predicate(config._current):
41                print(("%s failed as expected (%s): %s " % (
42                    name, self.predicate, str(ex))))
43            else:
44                raise
45        else:
46            if self.predicate(config._current):
47                raise AssertionError(
48                    "Unexpected success for '%s' (%s)" %
49                    (name, self.predicate))
50
51    def __call__(self, fn):
52        @decorator
53        def decorate(fn, *args, **kw):
54            if self.predicate(config._current):
55                if self.reason:
56                    msg = "'%s' : %s" % (
57                            fn.__name__,
58                            self.reason
59                        )
60                else:
61                    msg = "'%s': %s" % (
62                            fn.__name__, self.predicate
63                        )
64                raise SkipTest(msg)
65            else:
66                if self._fails_on:
67                    with self._fails_on.fail_if(name=fn.__name__):
68                        return fn(*args, **kw)
69                else:
70                    return fn(*args, **kw)
71        return decorate(fn)
72
73    def fails_on(self, other, reason=None):
74        self._fails_on = skip_if(other, reason)
75        return self
76
77    def fails_on_everything_except(self, *dbs):
78        self._fails_on = skip_if(fails_on_everything_except(*dbs))
79        return self
80
81class fails_if(skip_if):
82    def __call__(self, fn):
83        @decorator
84        def decorate(fn, *args, **kw):
85            with self.fail_if(name=fn.__name__):
86                return fn(*args, **kw)
87        return decorate(fn)
88
89
90def only_if(predicate, reason=None):
91    predicate = _as_predicate(predicate)
92    return skip_if(NotPredicate(predicate), reason)
93
94
95def succeeds_if(predicate, reason=None):
96    predicate = _as_predicate(predicate)
97    return fails_if(NotPredicate(predicate), reason)
98
99
100class Predicate(object):
101    @classmethod
102    def as_predicate(cls, predicate):
103        if isinstance(predicate, skip_if):
104            return NotPredicate(predicate.predicate)
105        elif isinstance(predicate, Predicate):
106            return predicate
107        elif isinstance(predicate, list):
108            return OrPredicate([cls.as_predicate(pred) for pred in predicate])
109        elif isinstance(predicate, tuple):
110            return SpecPredicate(*predicate)
111        elif isinstance(predicate, util.string_types):
112            tokens = predicate.split(" ", 2)
113            op = spec = None
114            db = tokens.pop(0)
115            if tokens:
116                op = tokens.pop(0)
117            if tokens:
118                spec = tuple(int(d) for d in tokens.pop(0).split("."))
119            return SpecPredicate(db, op, spec)
120        elif util.callable(predicate):
121            return LambdaPredicate(predicate)
122        else:
123            assert False, "unknown predicate type: %s" % predicate
124
125
126class BooleanPredicate(Predicate):
127    def __init__(self, value, description=None):
128        self.value = value
129        self.description = description or "boolean %s" % value
130
131    def __call__(self, config):
132        return self.value
133
134    def _as_string(self, negate=False):
135        if negate:
136            return "not " + self.description
137        else:
138            return self.description
139
140    def __str__(self):
141        return self._as_string()
142
143
144class SpecPredicate(Predicate):
145    def __init__(self, db, op=None, spec=None, description=None):
146        self.db = db
147        self.op = op
148        self.spec = spec
149        self.description = description
150
151    _ops = {
152            '<': operator.lt,
153             '>': operator.gt,
154             '==': operator.eq,
155             '!=': operator.ne,
156             '<=': operator.le,
157             '>=': operator.ge,
158             'in': operator.contains,
159             'between': lambda val, pair: val >= pair[0] and val <= pair[1],
160             }
161
162    def __call__(self, config):
163        engine = config.db
164
165        if "+" in self.db:
166            dialect, driver = self.db.split('+')
167        else:
168            dialect, driver = self.db, None
169
170        if dialect and engine.name != dialect:
171            return False
172        if driver is not None and engine.driver != driver:
173            return False
174
175        if self.op is not None:
176            assert driver is None, "DBAPI version specs not supported yet"
177
178            version = _server_version(engine)
179            oper = hasattr(self.op, '__call__') and self.op \
180                        or self._ops[self.op]
181            return oper(version, self.spec)
182        else:
183            return True
184
185    def _as_string(self, negate=False):
186        if self.description is not None:
187            return self.description
188        elif self.op is None:
189            if negate:
190                return "not %s" % self.db
191            else:
192                return "%s" % self.db
193        else:
194            if negate:
195                return "not %s %s %s" % (
196                        self.db,
197                        self.op,
198                        self.spec
199                    )
200            else:
201                return "%s %s %s" % (
202                        self.db,
203                        self.op,
204                        self.spec
205                    )
206
207    def __str__(self):
208        return self._as_string()
209
210
211class LambdaPredicate(Predicate):
212    def __init__(self, lambda_, description=None, args=None, kw=None):
213        spec = inspect.getargspec(lambda_)
214        if not spec[0]:
215            self.lambda_ = lambda db: lambda_()
216        else:
217            self.lambda_ = lambda_
218        self.args = args or ()
219        self.kw = kw or {}
220        if description:
221            self.description = description
222        elif lambda_.__doc__:
223            self.description = lambda_.__doc__
224        else:
225            self.description = "custom function"
226
227    def __call__(self, config):
228        return self.lambda_(config)
229
230    def _as_string(self, negate=False):
231        if negate:
232            return "not " + self.description
233        else:
234            return self.description
235
236    def __str__(self):
237        return self._as_string()
238
239
240class NotPredicate(Predicate):
241    def __init__(self, predicate):
242        self.predicate = predicate
243
244    def __call__(self, config):
245        return not self.predicate(config)
246
247    def __str__(self):
248        return self.predicate._as_string(True)
249
250
251class OrPredicate(Predicate):
252    def __init__(self, predicates, description=None):
253        self.predicates = predicates
254        self.description = description
255
256    def __call__(self, config):
257        for pred in self.predicates:
258            if pred(config):
259                self._str = pred
260                return True
261        return False
262
263    _str = None
264
265    def _eval_str(self, negate=False):
266        if self._str is None:
267            if negate:
268                conjunction = " and "
269            else:
270                conjunction = " or "
271            return conjunction.join(p._as_string(negate=negate)
272                            for p in self.predicates)
273        else:
274            return self._str._as_string(negate=negate)
275
276    def _negation_str(self):
277        if self.description is not None:
278            return "Not " + (self.description % {"spec": self._str})
279        else:
280            return self._eval_str(negate=True)
281
282    def _as_string(self, negate=False):
283        if negate:
284            return self._negation_str()
285        else:
286            if self.description is not None:
287                return self.description % {"spec": self._str}
288            else:
289                return self._eval_str()
290
291    def __str__(self):
292        return self._as_string()
293
294_as_predicate = Predicate.as_predicate
295
296
297def _is_excluded(db, op, spec):
298    return SpecPredicate(db, op, spec)(config._current)
299
300
301def _server_version(engine):
302    """Return a server_version_info tuple."""
303
304    # force metadata to be retrieved
305    conn = engine.connect()
306    version = getattr(engine.dialect, 'server_version_info', ())
307    conn.close()
308    return version
309
310
311def db_spec(*dbs):
312    return OrPredicate(
313            [Predicate.as_predicate(db) for db in dbs]
314        )
315
316
317def open():
318    return skip_if(BooleanPredicate(False, "mark as execute"))
319
320
321def closed():
322    return skip_if(BooleanPredicate(True, "marked as skip"))
323
324def fails():
325    return fails_if(BooleanPredicate(True, "expected to fail"))
326
327@decorator
328def future(fn, *arg):
329    return fails_if(LambdaPredicate(fn), "Future feature")
330
331
332def fails_on(db, reason=None):
333    return fails_if(SpecPredicate(db), reason)
334
335
336def fails_on_everything_except(*dbs):
337    return succeeds_if(
338                OrPredicate([
339                    SpecPredicate(db) for db in dbs
340                    ])
341            )
342
343
344def skip(db, reason=None):
345    return skip_if(SpecPredicate(db), reason)
346
347
348def only_on(dbs, reason=None):
349    return only_if(
350            OrPredicate([SpecPredicate(db) for db in util.to_list(dbs)])
351    )
352
353
354def exclude(db, op, spec, reason=None):
355    return skip_if(SpecPredicate(db, op, spec), reason)
356
357
358def against(config, *queries):
359    assert queries, "no queries sent!"
360    return OrPredicate([
361                Predicate.as_predicate(query)
362                for query in queries
363            ])(config)
364
Full Screen

predicates.py

Source: predicates.py Github

copy
1"""
2 This module houses the GEOS ctypes prototype functions for the
3 unary and binary predicate operations on geometries.
4"""
5from ctypes import c_char, c_char_p, c_double
6
7from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
8from django.contrib.gis.geos.prototypes.errcheck import check_predicate
9
10
11# ## Binary & unary predicate factories ##
12class UnaryPredicate(GEOSFuncFactory):
13    "For GEOS unary predicate functions."
14    argtypes = [GEOM_PTR]
15    restype = c_char
16    errcheck = staticmethod(check_predicate)
17
18
19class BinaryPredicate(UnaryPredicate):
20    "For GEOS binary predicate functions."
21    argtypes = [GEOM_PTR, GEOM_PTR]
22
23
24# ## Unary Predicates ##
25geos_hasz = UnaryPredicate('GEOSHasZ')
26geos_isclosed = UnaryPredicate('GEOSisClosed')
27geos_isempty = UnaryPredicate('GEOSisEmpty')
28geos_isring = UnaryPredicate('GEOSisRing')
29geos_issimple = UnaryPredicate('GEOSisSimple')
30geos_isvalid = UnaryPredicate('GEOSisValid')
31
32# ## Binary Predicates ##
33geos_contains = BinaryPredicate('GEOSContains')
34geos_covers = BinaryPredicate('GEOSCovers')
35geos_crosses = BinaryPredicate('GEOSCrosses')
36geos_disjoint = BinaryPredicate('GEOSDisjoint')
37geos_equals = BinaryPredicate('GEOSEquals')
38geos_equalsexact = BinaryPredicate('GEOSEqualsExact', argtypes=[GEOM_PTR, GEOM_PTR, c_double])
39geos_intersects = BinaryPredicate('GEOSIntersects')
40geos_overlaps = BinaryPredicate('GEOSOverlaps')
41geos_relatepattern = BinaryPredicate('GEOSRelatePattern', argtypes=[GEOM_PTR, GEOM_PTR, c_char_p])
42geos_touches = BinaryPredicate('GEOSTouches')
43geos_within = BinaryPredicate('GEOSWithin')
44
Full Screen

ExtendMethod.js

Source: ExtendMethod.js Github

copy
1String.prototype.trim = function () {
2    return this.replace(/(^\s*)|(\s*$)/g, "");
3}
4
5Array.prototype.indexOf = function (valueOrPredicate) {
6    var predicate = getFunction(valueOrPredicate);
7    for (var i = 0; i < this.length; i++) {
8        var value = this[i];
9        if (predicate(value, i, this)) {
10            return i;
11        }
12    }
13    return -1;
14}
15
16Array.prototype.lastIndexOf = function (valueOrPredicate) {
17    var predicate = getFunction(valueOrPredicate);
18    for (var i = this.length - 1; i >= 0 ; i--) {
19        var value = this[i];
20        if (predicate(value, i, this)) {
21            return i;
22        }
23    }
24    return -1;
25}
26
27Array.prototype.all = function (predicate) {
28    isFunction(predicate);
29    for (var i = 0; i < this.length; i++) {
30        var value = this[i];
31        if (!predicate(value, i, this)) {
32            return false;
33        }
34    }
35    return true;
36}
37
38Array.prototype.any = function (predicate) {
39    isFunction(predicate);
40    for (var i = 0; i < this.length; i++) {
41        var value = this[i];
42        if (predicate(value, i, this)) {
43            return true;
44        }
45    }
46    return false;
47}
48
49Array.prototype.contains = function (valueOrPredicate) {
50    var predicate = getFunction(valueOrPredicate);
51    for (var i = 0; i < this.length; i++) {
52        var value = this[i];
53        if (predicate(value, i, this)) {
54            return true;
55        }
56    }
57    return false;
58}
59
60Array.prototype.count = function (predicate) {
61    if (typeof predicate != "function") {
62        return this.length;
63    }
64    var count = 0;
65    for (var i = 0; i < this.length; i++) {
66        var value = this[i];
67        if (predicate(value)) {
68            count++;
69        }
70    }
71    return count;
72}
73
74Array.prototype.distinct = function (predicate) {//有bug,对[1,"1",1]这类型数组(字符串和数字一样)处理会出错
75    var arr = [],
76        table = {},
77        i = 0,
78        len = this.length,
79        result;
80    if (typeof predicate == "undefined") {
81        for (; i < len; i++) {
82            result = this[i];
83            if (table[result] !== result) {
84                arr.push(result);
85                table[result] = result;
86            }
87        }
88    }
89    //else {
90    //    for (; i < len; i++) {
91    //        var value1 = this[i]
92    //        value2 = this[i + 1];
93    //        if (typeof value2 == "undefined") {
94    //            break;
95    //        }
96    //        if (!predicate(value1, value2)) {
97    //            arr.push(value1);
98    //            arr.push(value2);
99    //        }
100    //    }
101    //    if (arr.length == 0) {
102    //        arr.push(this[i]);
103    //    }
104    //}
105    return arr;
106}
107
108Array.prototype.first = function (predicate) {
109    if (typeof predicate == "undefined") {
110        return this[0];
111    }
112    else {
113        for (var i = 0; i < this.length; i++) {
114            var value = this[i];
115            if (predicate(value, i, this)) {
116                return value;
117            }
118        }
119    }
120}
121
122Array.prototype.select = function (predicate) {
123    if (typeof predicate == "undefined") {
124        return this;
125    }
126    else {
127        var newArray = [];
128        for (var i = 0; i < this.length; i++) {
129            var value = this[i];
130            newArray.push(predicate(value, i, this));
131        }
132        return newArray;
133    }
134}
135
136Array.prototype.skip = function (predicate) {
137    if (typeof predicate == "undefined") {
138        return this;
139    }
140    else if (typeof predicate == "number") {
141        return this.slice(predicate);
142    }
143    else {
144        var newArray = [];
145        for (var i = 0; i < this.length; i++) {
146            var value = this[i];
147            if (!predicate(value, i, this)) {
148                newArray.push(value);
149            }
150        }
151        return newArray;
152    }
153}
154
155Array.prototype.take = function (predicate) {
156    if (typeof predicate == "undefined") {
157        return this;
158    }
159    else if (typeof predicate == "number") {
160        return this.slice(0, predicate);
161    }
162    else {
163        var newArray = [];
164        for (var i = 0; i < this.length; i++) {
165            var value = this[i];
166            if (predicate(value, i, this)) {
167                newArray.push(value);
168            }
169        }
170        return newArray;
171    }
172}
173
174Array.prototype.where = function (predicate) {
175    isFunction(predicate);
176    var newArray = [];
177    for (var i = 0; i < this.length; i++) {
178        var value = this[i];
179        if (predicate(value, i, this)) {
180            newArray.push(value);
181        }
182    }
183    return newArray;
184}
185
186Array.prototype.remove = function (valueOrPredicate) {
187    var predicate = getFunction(valueOrPredicate);
188    for (var i = 0; i < this.length; i++) {
189        var value = this[i];
190        if (predicate(value, i, this)) {
191            this.splice(i, 1);
192            i--;
193        }
194    }
195    return this;
196}
197
198Array.prototype.removeFirst = function (valueOrPredicate) {
199    var predicate = getFunction(valueOrPredicate);
200    for (var i = 0; i < this.length; i++) {
201        var value = this[i];
202        if (predicate(value, i, this)) {
203            this.splice(i, 1);
204            i--;
205            break;
206        }
207    }
208    return this;
209}
210
211Array.prototype.removeAll = function () {
212    this.length = 0;
213    return this;
214}
215
216Array.prototype.insert = function (value, index) {
217    if (typeof index != "number") {
218        throw index + " is not a number";
219    }
220    this.splice(index, 0, value);
221    return this;
222}
223
224Array.prototype.forEach = function (predicate) {
225    var predicate = getFunction(predicate);
226    for (var i = 0; i < this.length; i++) {
227        var value = this[i];
228        predicate(value, i, this);
229    }
230    return this;
231}
232
233//=========辅助方法===========
234function isFunction(predicate) {
235    if (typeof predicate !== "function") {
236        throw predicate + " is not a function";
237    }
238}
239
240function getFunction(valueOrPredicate) {
241    return (typeof valueOrPredicate === "function")
242         ? valueOrPredicate
243         : function (value) { return value === valueOrPredicate; };
244}
245
246
Full Screen

automation_predicate.js

Source: automation_predicate.js Github

copy
1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * @fileoverview ChromeVox predicates for the automation extension API.
7 */
8
9goog.provide('AutomationPredicate');
10goog.provide('AutomationPredicate.Binary');
11goog.provide('AutomationPredicate.Unary');
12
13goog.scope(function() {
14var RoleType = chrome.automation.RoleType;
15
16/**
17 * @constructor
18 */
19AutomationPredicate = function() {};
20
21/**
22 * @typedef {function(chrome.automation.AutomationNode) : boolean}
23 */
24AutomationPredicate.Unary;
25
26/**
27 * @typedef {function(chrome.automation.AutomationNode,
28 *                    chrome.automation.AutomationNode) : boolean}
29 */
30AutomationPredicate.Binary;
31
32/**
33 * Constructs a predicate given a role.
34 * @param {RoleType} role
35 * @return {AutomationPredicate.Unary}
36 */
37AutomationPredicate.withRole = function(role) {
38  return function(node) {
39    return node.role == role;
40  };
41};
42
43/** @type {AutomationPredicate.Unary} */
44AutomationPredicate.checkBox = AutomationPredicate.withRole(RoleType.checkBox);
45/** @type {AutomationPredicate.Unary} */
46AutomationPredicate.comboBox = AutomationPredicate.withRole(RoleType.comboBox);
47/** @type {AutomationPredicate.Unary} */
48AutomationPredicate.editText = AutomationPredicate.withRole(RoleType.textField);
49/** @type {AutomationPredicate.Unary} */
50AutomationPredicate.heading = AutomationPredicate.withRole(RoleType.heading);
51/** @type {AutomationPredicate.Unary} */
52AutomationPredicate.inlineTextBox =
53    AutomationPredicate.withRole(RoleType.inlineTextBox);
54/** @type {AutomationPredicate.Unary} */
55AutomationPredicate.link = AutomationPredicate.withRole(RoleType.link);
56/** @type {AutomationPredicate.Unary} */
57AutomationPredicate.table = AutomationPredicate.withRole(RoleType.table);
58
59/**
60 * @param {chrome.automation.AutomationNode} node
61 * @return {boolean}
62 */
63AutomationPredicate.button = function(node) {
64  return /button/i.test(node.role);
65};
66
67/**
68 * @param {chrome.automation.AutomationNode} node
69 * @return {boolean}
70 */
71AutomationPredicate.formField = function(node) {
72  switch (node.role) {
73    case 'button':
74    case 'buttonDropDown':
75    case 'checkBox':
76    case 'comboBox':
77    case 'date':
78    case 'dateTime':
79    case 'details':
80    case 'disclosureTriangle':
81    case 'form':
82    case 'menuButton':
83    case 'menuListPopup':
84    case 'popUpButton':
85    case 'radioButton':
86    case 'searchBox':
87    case 'slider':
88    case 'spinButton':
89    case 'switch':
90    case 'tab':
91    case 'textField':
92    case 'time':
93    case 'toggleButton':
94    case 'tree':
95      return true;
96  }
97  return false;
98};
99
100/**
101 * @param {chrome.automation.AutomationNode} node
102 * @return {boolean}
103 */
104AutomationPredicate.landmark = function(node) {
105  switch (node.role) {
106    case 'application':
107    case 'banner':
108    case 'complementary':
109    case 'contentInfo':
110    case 'form':
111    case 'main':
112    case 'navigation':
113    case 'search':
114      return true;
115  }
116  return false;
117};
118
119/**
120 * @param {chrome.automation.AutomationNode} node
121 * @return {boolean}
122 */
123AutomationPredicate.visitedLink = function(node) {
124  return node.state.visited;
125};
126
127/**
128 * @param {chrome.automation.AutomationNode} node
129 * @return {boolean}
130 */
131AutomationPredicate.focused = function(node) {
132  return node.state.focused;
133};
134
135/**
136 * @param {chrome.automation.AutomationNode} node
137 * @return {boolean}
138 */
139AutomationPredicate.leaf = function(node) {
140  return !node.firstChild ||
141      node.role == RoleType.button ||
142      node.role == RoleType.buttonDropDown ||
143      node.role == RoleType.popUpButton ||
144      node.role == RoleType.slider ||
145      node.role == RoleType.textField ||
146      node.children.every(function(n) {
147        return n.state.invisible;
148      });
149};
150
151/**
152 * @param {chrome.automation.AutomationNode} node
153 * @return {boolean}
154 */
155AutomationPredicate.leafWithText = function(node) {
156  return AutomationPredicate.leaf(node) &&
157      !!(node.name || node.value);
158};
159
160/**
161 * @param {chrome.automation.AutomationNode} first
162 * @param {chrome.automation.AutomationNode} second
163 * @return {boolean}
164 */
165AutomationPredicate.linebreak = function(first, second) {
166  // TODO(dtseng): Use next/previousOnLin once available.
167  var fl = first.location;
168  var sl = second.location;
169  return fl.top != sl.top ||
170      (fl.top + fl.height != sl.top + sl.height);
171};
172
173/**
174 * Leaf nodes that should be ignored while traversing the automation tree. For
175 * example, apply this predicate when moving to the next element.
176 * @param {chrome.automation.AutomationNode} node
177 * @return {boolean}
178 */
179AutomationPredicate.shouldIgnoreLeaf = function(node) {
180  return AutomationPredicate.leaf(node) &&
181      (node.role == RoleType.client ||
182      node.role == RoleType.div ||
183      (node.role == 'image' && node.name == '') ||
184      (node.role == 'staticText' && node.value == ''));
185};
186
187});  // goog.scope
188
Full Screen

ProcessorView.js

Source: ProcessorView.js Github

copy
1import React, { Component, PropTypes } from "react";
2import Dropzone from "react-dropzone";
3import isEqual from "lodash/isEqual";
4import isEmpty from "lodash/isEmpty";
5import uuidv4 from "uuid/v4";
6import ProcessorListLabel from "./ProcessorListLabel";
7import ProcessorEdit from "./ProcessorEdit";
8import PropertyListItem from "./../PropertyListItem";
9import "./../../style/Processors.less";
10import * as R from "ramda";
11
12const format = new ol.format.GeoJSON();
13
14const processorStyle = new ol.style.Style({
15  fill: new ol.style.Fill({
16    color: "rgba(255, 0, 0, 0.1)"
17  }),
18  stroke: new ol.style.Stroke({
19    color: "#f00",
20    width: 1
21  })
22});
23
24const newPredicateStyle = new ol.style.Style({
25  fill: new ol.style.Fill({
26    color: "rgba(0, 0, 255, 0.1)"
27  }),
28  stroke: new ol.style.Stroke({
29    color: "#00f",
30    width: 1
31  })
32});
33
34class ProcessorView extends Component {
35  constructor(props) {
36    super(props);
37    this.state = {
38      addingPredicate: false,
39      editing: false,
40      editingPredicate: false,
41      editingProcessor: false,
42      creating: false,
43      drawing: false,
44      uploading: false,
45      fileUploaded: false,
46      uploadedFile: false,
47      uploadErr: false,
48      predicate_comparator: "geowithin",
49      activePredicates: {}
50    };
51    this.predicateLayers = {};
52    this.onSave = this.onSave.bind(this);
53    this.onCancel = this.onCancel.bind(this);
54    this.onDraw = this.onDraw.bind(this);
55    this.onUpload = this.onUpload.bind(this);
56    this.onDrop = this.onDrop.bind(this);
57    this.onDelete = this.onDelete.bind(this);
58    this.onAddPredicate = this.onAddPredicate.bind(this);
59    this.onPredicateComparatorChange = this.onPredicateComparatorChange.bind(
60      this
61    );
62    this.onEditProcessor = this.onEditProcessor.bind(this);
63    this.onCancelEditProcessor = this.onCancelEditProcessor.bind(this);
64    this.onEditProcessorSave = this.onEditProcessorSave.bind(this);
65    this.togglePredicate = this.togglePredicate.bind(this);
66    this.onEditPredicate = this.onEditPredicate.bind(this);
67    this.onDeletePredicate = this.onDeletePredicate.bind(this);
68  }
69
70  componentDidMount() {
71    this.createMap();
72    this.addPredicates(this.props.processor);
73    // window.addEventListeer("resize", () => {
74    //   this.createMap();
75    // });
76  }
77
78  componentWillReceiveProps(nextProps) {
79    if (
80      !isEqual(
81        nextProps.processor.definition.predicates,
82        this.props.processor.definition.predicates
83      )
84    ) {
85      this.addPredicates(nextProps.processor);
86    }
87    if (this.props.menu.open !== nextProps.menu.open) {
88      // wait for menu to transition
89      setTimeout(() => this.map.updateSize(), 200);
90    }
91  }
92
93  onCancel() {
94    this.map.removeInteraction(this.modify);
95    this.map.removeInteraction(this.create);
96    this.select.getFeatures().clear();
97    this.newPredicateSource.clear();
98    this.setState({
99      editing: false,
100      creating: false,
101      drawing: false,
102      uploading: false,
103      fileUploaded: false,
104      uploadErr: false,
105      uploadedFile: false,
106      editingPredicate: false,
107      editingProcessor: false
108    });
109  }
110
111  onSave() {
112    this.setState({
113      editing: false,
114      creating: false,
115      drawing: false,
116      uploading: false,
117      uploadedFile: false
118    });
119    this.map.removeInteraction(this.modify);
120    this.map.removeInteraction(this.create);
121    this.select.getFeatures().clear();
122    const fcId = `${this.props.processor.id}.${this.props.processor.definition
123      .predicates.length + 1}`;
124    const fs = this.newPredicateSource.getFeatures().map((f, i) => {
125      f.setId(`${fcId}.${i}`);
126      return f;
127    });
128    const gj = JSON.parse(
129      format.writeFeatures(fs, {
130        dataProjection: "EPSG:4326",
131        featureProjection: "EPSG:3857"
132      })
133    );
134    gj.id = fcId;
135    gj.features = gj.features.map(f => ({
136      ...f,
137      properties: {}
138    }));
139    const newPredicate = {
140      id: uuidv4(),
141      definition: gj,
142      type: this.state.predicate_comparator
143    };
144    const { processor } = this.props;
145    const newProcessor = R.assocPath(
146      ["definition", "predicates"],
147      R.concat(processor.definition.predicates, [newPredicate]),
148      this.props.processor
149    );
150    this.newPredicateSource.clear();
151    this.props.actions.updateProcessor(newProcessor);
152  }
153
154  onDraw() {
155    this.setState({ drawing: true });
156    this.map.addInteraction(this.create);
157  }
158
159  onUpload() {
160    this.setState({ uploading: true });
161  }
162
163  onDrop(acceptedFiles) {
164    if (acceptedFiles.length) {
165      const file = acceptedFiles[0];
166      const reader = new FileReader();
167      reader.onload = e => {
168        try {
169          const gj = JSON.parse(e.target.result);
170          this.setState({
171            uploadErr: false,
172            uploadedFile: file.name
173          });
174          const features = format.readFeatures(gj);
175          features.forEach(feature => {
176            feature.getGeometry().transform("EPSG:4326", "EPSG:3857");
177            this.newPredicateSource.addFeature(feature);
178          });
179          this.map
180            .getView()
181            .fit(this.newPredicateSource.getExtent(), this.map.getSize());
182        } catch (err) {
183          this.setState({ uploadErr: "Not valid GeoJSON" });
184        }
185      };
186      reader.readAsText(file);
187    }
188  }
189
190  onDelete() {
191    this.props.actions.deleteProcessor(this.props.processor);
192  }
193
194  onPredicateComparatorChange(e) {
195    this.setState({
196      predicate_comparator: e.target.value
197    });
198  }
199
200  onAddPredicate() {
201    this.setState({ creating: true });
202  }
203
204  onEditProcessor() {
205    this.setState({ editingProcessor: true });
206  }
207
208  onCancelEditProcessor() {
209    this.setState({ editingProcessor: false }, () => {
210      this.createMap();
211    });
212  }
213
214  onEditProcessorSave(processor) {
215    this.props.actions.updateProcessor(processor);
216    this.setState({ editingProcessor: false }, () => {
217      this.createMap();
218    });
219  }
220
221  onEditPredicate(predicate) {
222    const layer = this.predicateLayers[predicate.id];
223    const fs = layer
224      .getSource()
225      .getFeatures()
226      .map(f => f.clone());
227    this.setState({ editingPredicate: predicate.id });
228    this.select.getFeatures().clear();
229    this.newPredicateSource.clear();
230    this.map.getView().fit(layer.getSource().getExtent(), this.map.getSize());
231    this.map.removeLayer(layer);
232    this.newPredicateSource.addFeatures(fs);
233    this.modify = new ol.interaction.Modify({
234      features: new ol.Collection(this.newPredicateSource.getFeatures())
235    });
236    this.map.addInteraction(this.modify);
237  }
238
239  onSavePredicate(predicate) {
240    const fcId = `${this.props.processor.id}.${predicate.id}`;
241    const fs = this.newPredicateSource.getFeatures().map((f, i) => {
242      f.setId(`${fcId}.${i}`);
243      return f;
244    });
245    const gj = JSON.parse(
246      format.writeFeatures(fs, {
247        dataProjection: "EPSG:4326",
248        featureProjection: "EPSG:3857"
249      })
250    );
251    gj.id = fcId;
252    gj.features = gj.features.map(f => ({
253      ...f,
254      properties: {}
255    }));
256    const newPredicate = {
257      ...predicate,
258      rhs: gj
259    };
260    const newProcessor = {
261      ...this.props.processor,
262      predicates: this.props.processor.definition.predicates.map(r => {
263        if (r.id === newPredicate.id) {
264          return newPredicate;
265        }
266        return r;
267      })
268    };
269    this.setState({
270      editingPredicate: false
271    });
272    this.map.removeInteraction(this.modify);
273    this.newPredicateSource.clear();
274    this.props.actions.updateProcessor(newProcessor);
275  }
276
277  onDeletePredicate(predicate) {
278    const predicates = this.props.processor.definition.predicates.filter(
279      r => r.id !== predicate.id
280    );
281    const newProcessor = R.assocPath(
282      ["definition", "predicates"],
283      R.reject(
284        p => p.id === predicate.id,
285        this.props.processor.definition.predicates
286      ),
287      this.props.processor
288    );
289    this.select.getFeatures().clear();
290    this.props.actions.updateProcessor(newProcessor);
291  }
292
293  onCancelPredicate(predicate) {
294    const layer = this.predicateLayers[predicate.id];
295    this.map.removeInteraction(this.modify);
296    this.newPredicateSource.clear();
297    this.map.addLayer(layer);
298    this.setState({
299      editingPredicate: false
300    });
301  }
302
303  createMap() {
304    while (this.mapRef.firstChild) {
305      this.mapRef.removeChild(this.mapRef.firstChild);
306    }
307    this.allPredicateSource = new ol.source.Vector();
308    this.newPredicateSource = new ol.source.Vector();
309    const newPredicateLayer = new ol.layer.Vector({
310      source: this.newPredicateSource,
311      style: newPredicateStyle
312    });
313    this.select = new ol.interaction.Select({
314      wrapX: false,
315      style: newPredicateStyle
316    });
317    this.modify = new ol.interaction.Modify({
318      features: new ol.Collection(this.newPredicateSource.getFeatures())
319    });
320    this.create = new ol.interaction.Draw({
321      source: this.newPredicateSource,
322      type: "Polygon"
323    });
324    this.map = new ol.Map({
325      target: this.mapRef,
326      interactions: ol.interaction.defaults().extend([this.select]),
327      layers: [
328        new ol.layer.Tile({
329          source: new ol.source.OSM()
330        }),
331        newPredicateLayer
332      ],
333      view: new ol.View({
334        center: ol.proj.fromLonLat([-100, 30]),
335        zoom: 3
336      })
337    });
338
339    this.addPredicates(this.props.processor);
340  }
341
342  addPredicates(processor) {
343    const { predicates } = this.props.processor.definition;
344    Object.keys(this.predicateLayers).forEach(layerid =>
345      this.map.removeLayer(this.predicateLayers[layerid])
346    );
347    this.predicateLayers = {};
348    if (predicates && predicates.length) {
349      predicates.forEach(predicate => {
350        if (predicate.type === "geowithin") {
351          this.addPredicate(predicate);
352        }
353      });
354      this.map
355        .getView()
356        .fit(this.allPredicateSource.getExtent(), this.map.getSize());
357    }
358  }
359
360  addPredicate(predicate) {
361    if (isEmpty(predicate)) return;
362    const predicateSource = new ol.source.Vector();
363    const features = format.readFeatures(predicate.definition);
364    features.forEach(feature => {
365      feature.getGeometry().transform("EPSG:4326", "EPSG:3857");
366      predicateSource.addFeature(feature);
367      this.allPredicateSource.addFeature(feature);
368    });
369    const layer = new ol.layer.Vector({
370      source: predicateSource,
371      style: processorStyle
372    });
373    this.predicateLayers[predicate.id] = layer;
374    this.map.addLayer(layer);
375    this.setState(prevState => ({
376      activePredicates: {
377        ...prevState.activePredicates,
378        [predicate.id]: true
379      }
380    }));
381  }
382
383  togglePredicate(predicate) {
384    if (this.predicateLayers[predicate.id]) {
385      const layer = this.predicateLayers[predicate.id];
386      const active = this.state.activePredicates[predicate.id];
387      if (active) {
388        this.map.removeLayer(layer);
389      } else {
390        this.map.addLayer(layer);
391      }
392      this.setState(prevState => ({
393        activePredicates: {
394          ...prevState.activePredicates,
395          [predicate.id]: !active
396        }
397      }));
398    }
399  }
400
401  viewPredicate(predicate) {
402    if (this.predicateLayers[predicate.id]) {
403      const layer = this.predicateLayers[predicate.id];
404      const fs = layer.getSource().getFeatures();
405      this.map.getView().fit(layer.getSource().getExtent(), this.map.getSize());
406      this.select.getFeatures().clear();
407      fs.forEach(f => this.select.getFeatures().push(f));
408    }
409  }
410
411  renderPredicates() {
412    const predicateList =
413      this.props.processor.definition.predicates === undefined ||
414      this.props.processor.definition.predicates.length === 0 ? (
415        <span className="note">
416          No predicates have been added to this processor.
417        </span>
418      ) : (
419        this.props.processor.definition.predicates.map(p => (
420          <div className="form-item mini" key={p.id}>
421            <div className="properties">
422              <PropertyListItem name={"Type"} value={p.type} />
423            </div>
424            {this.state.editingPredicate === p.id ? (
425              <div className="btn-toolbar plain">
426                <span
427                  className="btn-plain"
428                  onClick={() => this.onSavePredicate(p)}
429                >
430                  Save
431                </span>
432                <span
433                  className="btn-plain"
434                  onClick={() => this.onCancelPredicate(p)}
435                >
436                  Cancel
437                </span>
438              </div>
439            ) : (
440              <div className="btn-toolbar plain">
441                <span
442                  className="btn-plain"
443                  onClick={() => this.viewPredicate(p)}
444                >
445                  View
446                </span>
447                <span
448                  className="btn-plain"
449                  onClick={() => this.onEditPredicate(p)}
450                >
451                  Edit
452                </span>
453                <span
454                  className="btn-plain"
455                  onClick={() => this.onDeletePredicate(p)}
456                >
457                  Delete
458                </span>
459              </div>
460            )}
461          </div>
462        ))
463      );
464    return (
465      <div>
466        <h4>Predicates</h4>
467        <div className="predicate-list">{predicateList}</div>
468        {!this.state.creating && (
469          <div className="btn-toolbar">
470            <button className="btn btn-sc" onClick={this.onAddPredicate}>
471              Add Predicate
472            </button>
473          </div>
474        )}
475      </div>
476    );
477  }
478
479  renderEditing() {
480    return (
481      <div>
482        <div className="btn-toolbar">
483          <button className="btn btn-sc" onClick={this.onEditProcessor}>
484            Edit Processor
485          </button>
486          <button className="btn btn-danger" onClick={this.onDelete}>
487            Delete
488          </button>
489        </div>
490      </div>
491    );
492  }
493
494  renderCreating() {
495    const uploading = this.state.uploadedFile ? (
496      <span>{this.state.uploadedFile}</span>
497    ) : (
498      <div>
499        <Dropzone
500          onDrop={this.onDrop}
501          multiple={false}
502          className="drop-zone"
503          activeClassName="drop-zone-active"
504        >
505          <div>
506            <span>Drop file here, or click to select file to upload.</span>
507            <br />
508            <br />
509            <span>GeoJSON files accepted.</span>
510          </div>
511        </Dropzone>
512        {!!this.state.uploadErr && <p>{this.state.uploadErr}</p>}
513      </div>
514    );
515    const done = (
516      <div className="btn-toolbar">
517        <button className="btn btn-sc" onClick={this.onSave}>
518          Save
519        </button>
520        <button className="btn btn-sc" onClick={this.onCancel}>
521          Cancel
522        </button>
523      </div>
524    );
525    if (this.state.creating) {
526      return (
527        <div className="add-predicate">
528          <h4>Add Predicate</h4>
529          <div className="form-group">
530            <label htmlFor="comparator">Predicate Type:</label>
531            <select
532              id="comparator"
533              className="form-control"
534              value={this.state.predicate_comparator}
535              onChange={this.onPredicateComparatorChange}
536            >
537              <option value="$geowithin">geowithin</option>
538            </select>
539          </div>
540          {this.state.drawing && done}
541          {this.state.uploading && (
542            <div>
543              {uploading}
544              {done}
545            </div>
546          )}
547          {!this.state.drawing &&
548            !this.state.uploading && (
549              <div>
550                <div className="btn-toolbar">
551                  <button className="btn btn-sc" onClick={this.onDraw}>
552                    Draw
553                  </button>
554                  <button className="btn btn-sc" onClick={this.onUpload}>
555                    Upload
556                  </button>
557                </div>
558                <div className="btn-toolbar">
559                  <button className="btn btn-default" onClick={this.onCancel}>
560                    Cancel
561                  </button>
562                </div>
563              </div>
564            )}
565        </div>
566      );
567    }
568    return null;
569  }
570
571  render() {
572    const { processor } = this.props;
573    if (this.state.editingProcessor) {
574      return (
575        <div className="wrapper">
576          <section className="main">
577            <ProcessorEdit
578              processor={processor}
579              cancel={this.onCancelEditProcessor}
580              onSave={this.onEditProcessorSave}
581              errors={this.props.errors}
582              actions={this.props.actions}
583              capabilities={this.props.capabilities}
584            />
585          </section>
586        </div>
587      );
588    }
589    return (
590      <div className="processor-details">
591        <div className="processor-props">
592          <ProcessorListLabel processor={processor} />
593          {this.renderEditing()}
594          {this.renderPredicates()}
595          {this.renderCreating()}
596        </div>
597        <div
598          className="processor-map"
599          ref={c => {
600            this.mapRef = c;
601          }}
602        />
603      </div>
604    );
605  }
606}
607
608ProcessorView.propTypes = {
609  processor: PropTypes.object.isRequired,
610  menu: PropTypes.object.isRequired,
611  actions: PropTypes.object.isRequired,
612  errors: PropTypes.object.isRequired
613};
614
615export default ProcessorView;
616
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)