Best Python code snippet using robotframework
corneil_perl_stewart.py
Source:corneil_perl_stewart.py  
1# pyright: strict2from __future__ import annotations3from typing import List, Set, Tuple, Optional, cast4from enum import Enum5import networkx as nx6from cographs.utilities import pick7from cographs.cotree_classes import TreeNode, InternalNode, LeafNode, VT8class MarkResult(Enum):9    ALL_MARKED = 010    NONE_MARKED = 111    SOME_MARKED = 212def mark(new_node: LeafNode[VT],13         cotree_leaves: List[LeafNode[VT]],14         graph: nx.Graph[VT],15         root: InternalNode[VT]) -> Tuple[MarkResult, Set[InternalNode[VT]]]:16    root.clear()17    to_unmark: List[TreeNode[VT]] = []18    marked: Set[TreeNode[VT]] = set()19    for node in cotree_leaves:20        if graph.has_edge(node.node, new_node.node):21            marked.add(node)22            to_unmark.append(node)23    if len(marked) == 0:24        return (MarkResult.NONE_MARKED,25                cast(Set[InternalNode[VT]], marked))26    while len(to_unmark) > 0:27        node = to_unmark.pop()28        marked.remove(node)29        parent = node.parent30        if isinstance(node, InternalNode):31            node.marked_degree = 032        if parent is not None:33            if parent not in marked:34                marked.add(parent)35            parent.marked_degree += 136            if parent.marked_degree == parent.degree():37                to_unmark.append(parent)38            parent.processed_children.add(node)39    if len(marked) > 0 and root.degree() == 1:40        marked.add(root)41    assert all([isinstance(vertex, InternalNode)42                for vertex in marked])43    return (MarkResult.SOME_MARKED if len(marked) > 044            else MarkResult.ALL_MARKED,45            cast(Set[InternalNode[VT]], marked))46def find_lowest(47        root: InternalNode[VT],48        marked: Set[InternalNode[VT]]) -> Optional[InternalNode[VT]]:49    invalid_node = None50    if root not in marked:51        return None52    if root.marked_degree != root.degree() - 1:53        invalid_node = root54    marked.remove(root)55    root.marked_degree = 056    path_start = path_end = root57    while len(marked) > 0:58        path_start = marked.pop()59        if invalid_node is not None:60            return None61        if not path_start.is_union:62            if path_start.marked_degree != path_start.degree() - 1:63                invalid_node = path_start64            if path_start.parent in marked:65                return None66            assert path_start.parent is not None67            current = path_start.parent.parent68        else:69            invalid_node = path_start70            current = path_start.parent71        path_start.marked_degree = 072        while current != path_end:73            assert current is not None74            if (current == root or75                    current not in marked or76                    current.marked_degree != current.degree() - 1 or77                    current.parent in marked):78                return None79            marked.remove(current)80            current.marked_degree = 081            assert current.parent is not None82            current = current.parent.parent83        path_end = path_start84    return path_start85def updated_cotree(86        leaf: LeafNode[VT],87        lowest_marked: InternalNode[VT],88        root: InternalNode[VT]) -> InternalNode[VT]:89    children = (lowest_marked.processed_children90                if lowest_marked.is_union91                else lowest_marked.children - lowest_marked.processed_children)92    if len(children) == 1:93        child = pick(children)94        if isinstance(child, LeafNode):95            lowest_marked.children.remove(child)96            lowest_marked.add_child(InternalNode(97                is_union=not lowest_marked.is_union,98                children=set([child, leaf])))99        elif isinstance(child, InternalNode):100            child.add_child(leaf)101    else:102        lowest_marked.children -= lowest_marked.processed_children103        new_node = InternalNode(is_union=lowest_marked.is_union, children=set(104            lowest_marked.processed_children))105        if lowest_marked.is_union:106            lowest_marked.add_child(InternalNode(107                is_union=not lowest_marked.is_union,108                children=set([new_node, leaf])))109        elif lowest_marked.parent is not None:110            lowest_marked.parent.children.remove(lowest_marked)111            lowest_marked.parent.add_child(new_node)112            new_node.add_child(InternalNode(113                is_union=True, children=set([lowest_marked, leaf])))114        else:115            root = new_node116            new_node.add_child(InternalNode(117                is_union=True, children=set([lowest_marked, leaf])))118    return root119def compute_cotree(graph: nx.Graph[VT]) -> Optional[TreeNode[VT]]:120    leaves = [LeafNode(x) for x in graph.nodes]121    if graph.number_of_nodes() == 0:122        return None123    if graph.number_of_nodes() == 1:124        return pick(leaves)125    root: InternalNode[VT] = InternalNode(is_union=False)126    if graph.has_edge(leaves[0].node, leaves[1].node):127        root.add_child(*leaves[:2])128    else:129        root.add_child(InternalNode(is_union=True, children=set(leaves[:2])))130    for index, leaf in enumerate(leaves[2:], 2):131        result, marked = mark(leaf, leaves[:index], graph, root)132        if result == MarkResult.ALL_MARKED:133            root.add_child(leaf)134        elif result == MarkResult.NONE_MARKED:135            if root.degree() == 1:136                root_child = pick(root.children)137                assert isinstance(root_child, InternalNode)138                root_child.add_child(leaf)139            else:140                root = InternalNode(is_union=False, children=set(141                    [InternalNode(is_union=True, children=set([root, leaf]))]))142        else:143            lowest_marked = find_lowest(root, marked)144            if lowest_marked is None:145                return None146            root = updated_cotree(leaf, lowest_marked, root)147    return root148def is_cograph(graph: nx.Graph[VT]) -> bool:...json_compiler_test.py
Source:json_compiler_test.py  
1#!/usr/bin/env/ python32import json3import os4import shutil5import subprocess6import sys7import tempfile8import textwrap9import unittest10def ascend_find_exe(path, target):11    if not os.path.isdir(path):12        path = os.path.dirname(path)13    while True:14        test = os.path.join(path, target)15        if os.access(test, os.X_OK):16            return test17        parent = os.path.dirname(path)18        if os.path.samefile(parent, path):19            return None20        path = parent21exe = os.path.join(os.getcwd(), sys.argv[0])22thrift = ascend_find_exe(exe, 'thrift')23def read_file(path):24    with open(path, 'r') as f:25        return f.read()26def write_file(path, content):27    with open(path, 'w') as f:28        f.write(content)29def check_run_thrift(*args):30    argsx = [thrift, "--gen", "json"] + list(args)31    pipe = subprocess.PIPE32    return subprocess.check_call(argsx, stdout=pipe, stderr=pipe)33def gen(path, content):34    base, ext = os.path.splitext(path)35    if ext != ".thrift":36        raise Exception("bad path: {}".format(path))37    write_file(path, content)38    check_run_thrift("foo.thrift")39    return json.loads(read_file(os.path.join("gen-json", base + ".json")))40class JsonCompilerTest(unittest.TestCase):41    def setUp(self):42        tmp = tempfile.mkdtemp()43        self.addCleanup(shutil.rmtree, tmp, True)44        self.tmp = tmp45        self.addCleanup(os.chdir, os.getcwd())46        os.chdir(self.tmp)47        self.maxDiff = None48    def test_empty(self):49        obj = gen("foo.thrift", textwrap.dedent("""\50        """))51        self.assertEqual(obj, {52            "thrift_module": "foo",53        })54    def test_one_struct_empty(self):55        obj = gen("foo.thrift", textwrap.dedent("""\56            struct DataHolder {57            }58        """))59        self.assertEqual(obj, {60            "thrift_module": "foo",61            "structs": {62                "DataHolder": {63                    "fields": {64                    },65                    "is_exception": False,66                    "is_union": False,67                    "lineno": 1,68                },69            },70        })71    def test_one_struct_one_field_dep_struct(self):72        obj = gen("foo.thrift", textwrap.dedent("""\73            struct DataItem {74            }75            struct DataHolder {76                1: DataItem item,77            }78        """))79        self.assertEqual(obj, {80            "thrift_module": "foo",81            "structs": {82                "DataItem": {83                    "fields": {84                    },85                    "is_exception": False,86                    "is_union": False,87                    "lineno": 1,88                },89                "DataHolder": {90                    "fields": {91                        "item": {92                            "required": True,93                            "type_enum": "STRUCT",94                            "spec_args": "DataItem",95                        },96                    },97                    "is_exception": False,98                    "is_union": False,99                    "lineno": 3,100                },101            },102        })103    def test_one_struct_one_field_dep_coll_struct(self):104        obj = gen("foo.thrift", textwrap.dedent("""\105            struct DataItem {106            }107            struct DataHolder {108                1: map<string, DataItem> item,109            }110        """))111        self.assertEqual(obj, {112            "thrift_module": "foo",113            "structs": {114                "DataItem": {115                    "fields": {116                    },117                    "is_exception": False,118                    "is_union": False,119                    "lineno": 1,120                },121                "DataHolder": {122                    "fields": {123                        "item": {124                            "required": True,125                            "type_enum": "MAP",126                            "spec_args": {127                                "key_type": {128                                    "type_enum": "STRING",129                                    "spec_args": None,130                                },131                                "val_type": {132                                    "type_enum": "STRUCT",133                                    "spec_args": "DataItem",134                                },135                            },136                        },137                    },138                    "is_exception": False,139                    "is_union": False,140                    "lineno": 3,141                },142            },143        })144    def test_one_struct_one_field_dep_struct_bug_out_of_order(self):145        # when a field appeared with an unknown type, it is listed as typedef146        # in spec_args, even if later that type was defined as struct147        obj = gen("foo.thrift", textwrap.dedent("""\148            struct DataHolder {149                1: DataItem item,150            }151            struct DataItem {152            }153        """))154        self.assertEqual(obj, {155            "thrift_module": "foo",156            "structs": {157                "DataItem": {158                    "fields": {159                    },160                    "is_exception": False,161                    "is_union": False,162                    "lineno": 4,163                },164                "DataHolder": {165                    "fields": {166                        "item": {167                            "required": True,168                            "type_enum": "STRUCT",169                            "spec_args": "DataItem",170                        },171                    },172                    "is_exception": False,173                    "is_union": False,174                    "lineno": 1,175                },176            },...test_type_checks.py
Source:test_type_checks.py  
...28    assert deserialize.is_typing_type(Union[str, None])29    assert deserialize.is_typing_type(Union[str, int])30    assert deserialize.is_typing_type(Callable)31    assert deserialize.is_typing_type(Pattern)32def test_is_union():33    """Test is_union."""34    assert deserialize.is_union(Union[int, None])35    assert deserialize.is_union(Union[Dict[str, str], None])36    assert deserialize.is_union(Union[int, str])37    assert deserialize.is_union(Union[str, int])38    assert deserialize.is_union(Union[int, Union[int, str]])39    assert deserialize.is_union(Union[Union[str, int], int])40    assert not deserialize.is_union(int)41    assert not deserialize.is_union(List[int])42    assert not deserialize.is_union(Dict[str, str])43    assert not deserialize.is_union(Tuple[Optional[int], int])44    # The typing module doesn't let you create either of these.45    assert not deserialize.is_union(Union[None])46    assert not deserialize.is_union(Union[None, None])47def test_union_types():48    """Test union_types."""49    assert deserialize.union_types(Union[str, int], "") == {str, int}50    assert deserialize.union_types(Union[Dict[str, str], int], "") == {Dict[str, str], int}51    assert deserialize.union_types(Union[int, None], "") == {int, type(None)}52    assert deserialize.union_types(Union[None, int], "") == {type(None), int}53    # Optional[Optional[X]] == Optional[X]54    assert deserialize.union_types(Union[Union[int, None], None], "") == {int, type(None)}55    assert deserialize.union_types(Union[None, Optional[str]], "") == {type(None), str}56    with pytest.raises(deserialize.DeserializeException):57        _ = deserialize.union_types(int, "")58    with pytest.raises(deserialize.DeserializeException):59        _ = deserialize.union_types(Tuple[Optional[int], int], "")60def test_is_list():...cdeclarations.py
Source:cdeclarations.py  
1#!/usr/bin/env python2'''3This file contains classes that represent C declarations. cparser produces4declarations in this format, and ctypesparser reformats them into a format that5is not C-specific. The other modules don't need to touch these.6'''7__docformat__ = 'restructuredtext'8# --------------------------------------------------------------------------9# C Object Model10# --------------------------------------------------------------------------11class Declaration(object):12    def __init__(self):13        self.declarator = None14        self.type = Type()15        self.storage = None16    def __repr__(self):17        d = {18            'declarator': self.declarator,19            'type': self.type,20        }21        if self.storage:22            d['storage'] = self.storage23        l = ['%s=%r' % (k, v) for k, v in d.items()]24        return 'Declaration(%s)' % ', '.join(l)25class Declarator(object):26    pointer = None27    def __init__(self):28        self.identifier = None29        self.initializer = None30        self.array = None31        self.parameters = None32        self.bitfield = None33    # make pointer read-only to catch mistakes early34    pointer = property(lambda self: None)35    def __repr__(self):36        s = self.identifier or ''37        if self.bitfield:38            s += ":%d" % self.bitfield39        if self.array:40            s += repr(self.array)41        if self.initializer:42            s += ' = %r' % self.initializer43        if self.parameters is not None:44            s += '(' + ', '.join([repr(p) for p in self.parameters]) + ')'45        return s46class Pointer(Declarator):47    pointer = None48    def __init__(self):49        super(Pointer, self).__init__()50        self.qualifiers = []51    def __repr__(self):52        q = ''53        if self.qualifiers:54            q = '<%s>' % ' '.join(self.qualifiers)55        return 'POINTER%s(%r)' % (q, self.pointer) + \56            super(Pointer, self).__repr__()57class Array(object):58    def __init__(self):59        self.size = None60        self.array = None61    def __repr__(self):62        if self.size:63            a =  '[%r]' % self.size64        else:65            a = '[]'66        if self.array:67            return repr(self.array) + a68        else:69            return a70class Parameter(object):71    def __init__(self):72        self.type = Type()73        self.storage = None74        self.declarator = None75    def __repr__(self):76        d = {77            'type': self.type,78        }79        if self.declarator:80            d['declarator'] = self.declarator81        if self.storage:82            d['storage'] = self.storage83        l = ['%s=%r' % (k, v) for k, v in d.items()]84        return 'Parameter(%s)' % ', '.join(l)85class Type(object):86    def __init__(self):87        self.qualifiers = []88        self.specifiers = []89    def __repr__(self):90        return ' '.join(self.qualifiers + [str(s) for s in self.specifiers])91# These are used only internally.92class StorageClassSpecifier(str):93    pass94class TypeSpecifier(str):95    pass96class StructTypeSpecifier(object):97    def __init__(self, is_union, tag, declarations):98        self.is_union = is_union99        self.tag = tag100        self.declarations = declarations101    def __repr__(self):102        if self.is_union:103            s = 'union'104        else:105            s = 'struct'106        if self.tag:107            s += ' %s' % self.tag108        if self.declarations:109            s += ' {%s}' % '; '.join([repr(d) for d in self.declarations])110        return s111class EnumSpecifier(object):112    def __init__(self, tag, enumerators, src=None):113        self.tag = tag114        self.enumerators = enumerators115        self.src=src116    def __repr__(self):117        s = 'enum'118        if self.tag:119            s += ' %s' % self.tag120        if self.enumerators:121            s += ' {%s}' % ', '.join([repr(e) for e in self.enumerators])122        return s123class Enumerator(object):124    def __init__(self, name, expression):125        self.name = name126        self.expression = expression127    def __repr__(self):128        s = self.name129        if self.expression:130            s += ' = %r' % self.expression131        return s132class TypeQualifier(str):133    pass134def apply_specifiers(specifiers, declaration):135    '''Apply specifiers to the declaration (declaration may be136    a Parameter instead).'''137    for s in specifiers:138        if type(s) == StorageClassSpecifier:139            if declaration.storage:140                # Multiple storage classes, technically an error... ignore it141                pass142            declaration.storage = s143        elif type(s) in (TypeSpecifier, StructTypeSpecifier, EnumSpecifier):144            declaration.type.specifiers.append(s)145        elif type(s) == TypeQualifier:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
