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

diffutils.py

Source: diffutils.py Github

copy
1import re
2
3from pyrevit.coreutils.logger import get_logger
4from pyrevit.coreutils import reverse_dict, get_str_hash
5from pyrevit import DB
6
7
8logger = get_logger(__name__)
9
10
11type_param_exclude_list = ['Type', 'Type Name', 'Type Id', 'Family',
12                           'Family Name', 'Family and Type']
13
14domain_param_exclude_list = ['Workset', 'Edited by', 'Design Option',
15                             'Drawn By', 'Level', 'Comments',
16                             'Copyright', 'Image']
17
18custom_attrs = {DB.TextNote: ['LeaderCount', 'LeaderLeftAttachment',
19                              'LeaderRightAttachment', 'Text'],
20                DB.Dimension: ['Above', 'Below', 'Prefix', 'Suffix',
21                               'ValueOverride', 'AreSegmentsEqual',
22                               'NumberOfSegments']}
23
24
25class DiffResults:
26    def __init__(self):
27        self.processed_params = set()
28        self.rvt_element_types = set()
29        self.diff_elements = list()
30
31
32def cleanup_repr_str(repr_str):
33    repr_str = repr_str.strip('\n,\r')
34    return re.sub(' +', ' ', repr_str)
35
36
37def element_hash(rvt_element, include_type=False, diff_results=None):
38
39    def param_hash(param):
40        repr_str = '{} {}'.format(unicode(param.Definition.Name).ljust(30),
41                                  param.AsValueString())
42        if diff_results:
43            diff_results.processed_params.add(param.Definition.Name)
44        return get_str_hash(cleanup_repr_str(repr_str))
45
46    def attribute_hash(el, attribute):
47        try:
48            repr_str = unicode(getattr(el, attribute))
49        except Exception as hash_err:
50            logger.debug('Error reading attribute: '
51                         '{} form element {} with id: {} | {}'
52                         .format(attribute, el, el.Id, hash_err))
53            return ''
54
55        if diff_results:
56            diff_results.processed_params.add(attribute)
57
58        return get_str_hash(cleanup_repr_str(repr_str))
59
60    sorted_params = sorted(rvt_element.Parameters,
61                           key=lambda x: x.Definition.Name)
62    if diff_results:
63        diff_results.rvt_element_types.add(type(rvt_element))
64
65    hash_value = ''
66    for parameter in sorted_params:
67        if parameter.Definition.Name not in domain_param_exclude_list:
68            if include_type:
69                hash_value += param_hash(parameter)
70            elif parameter.Definition.Name not in type_param_exclude_list:
71                hash_value += param_hash(parameter)
72
73    if type(rvt_element) in custom_attrs:
74        for el_attr in custom_attrs[type(rvt_element)]:
75            hash_value += attribute_hash(rvt_element, el_attr)
76
77    return get_str_hash(hash_value)
78
79
80def element_hash_dict(element_list, include_type=False, diff_results=None):
81    return {el.Id.IntegerValue: element_hash(el, include_type, diff_results)
82            for el in element_list}
83
84
85def compare(element_a, element_b, compare_types=False, diff_results=None):
86    return element_hash(element_a,
87                        compare_types,
88                        diff_results) == element_hash(element_b,
89                                                      compare_types,
90                                                      diff_results)
91
92
93def compare_elmnt_sets(elementset_a, elementset_b,
94                       compare_types=False, diff_results=None):
95    dict_a = element_hash_dict(elementset_a, compare_types, diff_results)
96    hash_list_a = sorted(dict_a.values())
97
98    dict_b = element_hash_dict(elementset_b, compare_types, diff_results)
99    hash_list_b = sorted(dict_b.values())
100
101    if hash_list_a == hash_list_b:
102        return True
103
104    elif diff_results:
105        rdict_a = reverse_dict(dict_a)
106        rdict_b = reverse_dict(dict_b)
107        for el_hash in set(hash_list_a) ^ set(hash_list_b):
108            if el_hash in rdict_a:
109                for el_id in rdict_a[el_hash]:
110                    diff_results.diff_elements.append(DB.ElementId(el_id))
111
112            if el_hash in rdict_b:
113                for el_id in rdict_b[el_hash]:
114                    diff_results.diff_elements.append(DB.ElementId(el_id))
115
116    return False
117
118
119def compare_views(doc, view_a, view_b, compare_types=False, diff_results=None):
120    view_a_elmts = DB.FilteredElementCollector(doc)\
121                     .OwnedByView(view_a.Id)\
122                     .WhereElementIsNotElementType()\
123                     .ToElements()
124    view_b_elmts = DB.FilteredElementCollector(doc)\
125                     .OwnedByView(view_b.Id)\
126                     .WhereElementIsNotElementType()\
127                     .ToElements()
128
129    # pick the detail elements only
130    det_elmts_a = [el for el in view_a_elmts if el.ViewSpecific]
131    det_elmts_b = [el for el in view_b_elmts if el.ViewSpecific]
132
133    # compare and return result
134    return compare_elmnt_sets(det_elmts_a,
135                              det_elmts_b,
136                              compare_types,
137                              diff_results)
138
Full Screen

type.py

Source: type.py Github

copy
1# http://wiki.python.org/moin/PythonDecoratorLibrary#Type_Enforcement_.28accepts.2Freturns.29
2'''
3One of three degrees of enforcement may be specified by passing
4the 'debug' keyword argument to the decorator:
5    0 -- NONE:   No type-checking. Decorators disabled.
6    1 -- MEDIUM: Print warning message to stderr. (Default)
7    2 -- STRONG: Raise TypeError with message.
8If 'debug' is not passed to the decorator, the default level is used.
9
10Example usage:
11    >>> NONE, MEDIUM, STRONG = 0, 1, 2
12    >>>
13    >>> @accepts(int, int, int)
14    ... @returns(float)
15    ... def average(x, y, z):
16    ...     return (x + y + z) / 2
17    ...
18    >>> average(5.5, 10, 15.0)
19    TypeWarning:  'average' method accepts (int, int, int), but was given
20    (float, int, float)
21    15.25
22    >>> average(5, 10, 15)
23    TypeWarning:  'average' method returns (float), but result is (int)
24    15
25
26Needed to cast params as floats in function def (or simply divide by 2.0).
27
28    >>> TYPE_CHECK = STRONG
29    >>> @accepts(int, debug=TYPE_CHECK)
30    ... @returns(int, debug=TYPE_CHECK)
31    ... def fib(n):
32    ...     if n in (0, 1): return n
33    ...     return fib(n-1) + fib(n-2)
34    ...
35    >>> fib(5.3)
36    Traceback (most recent call last):
37      ...
38    TypeError: 'fib' method accepts (int), but was given (float)
39
40'''
41import sys
42#from itertools import izip
43from itertools import zip_longest as izip
44
45def accepts(*types, **kw):
46    '''Function decorator. Checks decorated function's arguments are
47    of the expected types.
48
49    Parameters:
50    types -- The expected types of the inputs to the decorated function.
51             Must specify type for each parameter.
52    kw    -- Optional specification of 'debug' level (this is the only valid
53             keyword argument, no other should be given).
54             debug = ( 0 | 1 | 2 )
55
56    '''
57    if not kw:
58        # default level: MEDIUM
59        debug = 2
60    else:
61        debug = kw['debug']
62    try:
63        def decorator(f):
64            # XXX Missing full support of kwargs
65            def newf(*args, **kwargs):
66                if debug is 0:
67                    return f(*args, **kwargs)
68                assert len(args) == len(types)
69                argtypes = tuple(map(type, args))
70                if not compare_types(types, argtypes):
71                # if argtypes != types:
72                    msg = info(f.__name__, types, argtypes, 0)
73                    if debug is 1:
74                        print >> sys.stderr, 'TypeWarning: ', msg
75                    elif debug is 2:
76                        raise TypeError(msg)
77                return f(*args, **kwargs)
78            newf.__name__ = f.__name__
79            return newf
80        return decorator
81    except KeyError as key:
82        raise KeyError(key + "is not a valid keyword argument")
83    except TypeError as msg:
84        raise TypeError(msg)
85
86def compare_types(expected, actual):
87    if isinstance(expected, tuple):
88        if isinstance(actual, tuple):
89            for x, y in izip(expected, actual):
90                if not compare_types(x ,y):
91                    return False
92            return True
93        else:
94            return actual == type(None) or actual in expected
95    else:
96        return actual == type(None) or actual == expected or isinstance(actual, expected) # issubclass(actual, expected)
97
98def returns(ret_type, **kw):
99    '''Function decorator. Checks decorated function's return value
100    is of the expected type.
101
102    Parameters:
103    ret_type -- The expected type of the decorated function's return value.
104                Must specify type for each parameter.
105    kw       -- Optional specification of 'debug' level (this is the only valid
106                keyword argument, no other should be given).
107                debug=(0 | 1 | 2)
108    '''
109    try:
110        if not kw:
111            # default level: MEDIUM
112            debug = 1
113        else:
114            debug = kw['debug']
115        def decorator(f):
116            def newf(*args):
117                result = f(*args)
118                if debug is 0:
119                    return result
120                res_type = type(result)
121                if not compare_types(ret_type, res_type): 
122                # if res_type != ret_type: # JORDAN: fix to allow for # StringTypes = (str, unicode)
123                # XXX note that this check should be recursive
124                    msg = info(f.__name__, (ret_type,), (res_type,), 1)
125                    if debug is 1:
126                        print >> sys.stderr, 'TypeWarning: ', msg
127                    elif debug is 2:
128                        raise TypeError (msg)
129                return result
130            newf.__name__ = f.__name__
131            return newf
132        return decorator
133    except KeyError as key:
134        raise KeyError( key + "is not a valid keyword argument")
135    except TypeError as msg:
136        raise TypeError(msg)
137
138def info(fname, expected, actual, flag):
139    '''Convenience function returns nicely formatted error/warning msg.'''
140    format = lambda types: ', '.join([str(t).split("'")[1] for t in types])
141    msg = "'{}' method ".format( fname )\
142          + ("accepts", "returns")[flag] + " ({}), but ".format(expected)\
143          + ("was given", "result is")[flag] + " ({})".format(actual)
144    return msg
145
146
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)