Best Python code snippet using radish
trino.py
Source:trino.py  
...25    from sqlalchemy.engine import reflection26    from sqlalchemy.sql import sqltypes27    from sqlalchemy_trino import datatype, error28    from sqlalchemy_trino.dialect import TrinoDialect29    register_custom_type(datatype.ROW, RecordTypeClass)30    register_custom_type(datatype.MAP, MapTypeClass)31    register_custom_type(datatype.DOUBLE, NumberTypeClass)32    # Read only table names and skip view names, as view names will also be returned33    # from get_view_names34    @reflection.cache  # type: ignore35    def get_table_names(self, connection, schema: str = None, **kw):  # type: ignore36        schema = schema or self._get_default_schema_name(connection)37        if schema is None:38            raise exc.NoSuchTableError("schema is required")39        query = dedent(40            """41            SELECT "table_name"42            FROM "information_schema"."tables"43            WHERE "table_schema" = :schema and "table_type" != 'VIEW'44        """45        ).strip()...test_serializers.py
Source:test_serializers.py  
...85@pytest.mark.parametrize('serializer_type', ['cbor', 'msgpack', 'json'])86class TestCustomTypes:87    @pytest.mark.parametrize('cls', [SimpleType, SlottedSimpleType], ids=['normal', 'slotted'])88    def test_marshal_unmarshal(self, serializer, cls):89        serializer.register_custom_type(cls)90        testval = cls(1, {'a': 1})91        testval2 = cls(2, testval)92        output = serializer.serialize(testval2)93        outval = serializer.deserialize(output)94        assert outval == testval295    def test_custom_state(self, serializer):96        """Test that marshallers and umarshallers can be embedded into the relevant class."""97        serializer.register_custom_type(CustomStateSimpleType, CustomStateSimpleType.marshal,98                                        CustomStateSimpleType.unmarshal)99        testval = CustomStateSimpleType('a', 1)100        output = serializer.serialize(testval)101        outval = serializer.deserialize(output)102        assert outval == testval103    def test_marshal_builtin(self, serializer):104        """Test that a single-argument unmarshaller can be used to unmarshal built-in types."""105        serializer.register_custom_type(datetime, marshal_datetime, unmarshal_datetime)106        dt = datetime(2016, 9, 9, 7, 21, 16, tzinfo=timezone.utc)107        output = serializer.serialize(dt)108        dt2 = serializer.deserialize(output)109        assert dt == dt2110    def test_missing_getattr(self, serializer):111        testval = UnserializableSimpleType(1, 'a')112        serializer.register_custom_type(UnserializableSimpleType)113        exc = pytest.raises(TypeError, serializer.serialize, testval)114        exc.match("'test_serializers.UnserializableSimpleType' has no __dict__ attribute and does "115                  "not implement __getstate__()")116    def test_missing_setattr(self, serializer):117        testval = UnserializableSimpleType(1, 'a')118        serializer.register_custom_type(UnserializableSimpleType, lambda instance: {})119        serialized = serializer.serialize(testval)120        exc = pytest.raises(Exception, serializer.deserialize, serialized)121        exc.match(122            "'test_serializers.UnserializableSimpleType' has no __dict__ attribute and does not "123            "implement __setstate__()")124    def test_missing_marshaller(self, serializer_type, serializer):125        serializer.register_custom_type(SlottedSimpleType)126        testval = SimpleType(1, 'a')127        exc = pytest.raises(Exception, serializer.serialize, testval)128        exc.match('no marshaller found for type "test_serializers.SimpleType"')129    def test_missing_unmarshaller(self, serializer):130        serializer.register_custom_type(SlottedSimpleType)131        serializer.register_custom_type(SimpleType, unmarshaller=None)132        testval = SimpleType(1, 'a')133        serialized = serializer.serialize(testval)134        exc = pytest.raises(Exception, serializer.deserialize, serialized)135        exc.match('no unmarshaller found for type "test_serializers.SimpleType"')136    def test_nowrap(self, serializer):137        serializer.register_custom_type(SimpleType, wrap_state=False)138        testval = SimpleType(1, 'a')139        serialized = serializer.serialize(testval)140        deserialized = serializer.deserialize(serialized)141        assert deserialized == {'value_a': 1, 'value_b': 'a'}142def test_mime_types(serializer):143    assert re.match('[a-z]+/[a-z]+', serializer.mimetype)144@pytest.mark.parametrize('safe', [True, False], ids=['safe', 'unsafe'])145def test_yaml_safe_attribute(safe):146    serializer = YAMLSerializer(safe=safe)147    assert serializer.safe is safe148@pytest.mark.parametrize('serializer_type', ['msgpack'])149def test_msgpack_exttype_passthrough(serializer):150    serializer.register_custom_type(SlottedSimpleType)151    ext = ExtType(6, b'somedata')152    data = serializer.serialize(ext)153    obj = serializer.deserialize(data)154    assert isinstance(obj, ExtType)155    assert obj.code == 6156    assert obj.data == b'somedata'157@pytest.mark.parametrize('serializer_type', ['cbor'])158def test_cbor_self_referential_objects(serializer):159    value1 = SimpleNamespace()160    value1.val = 1161    value1.next = value2 = SimpleNamespace()162    value2.val = 2163    value2.previous = value1164    serializer.register_custom_type(SimpleNamespace, typename='Simple')165    data = serializer.serialize(value1)166    obj = serializer.deserialize(data)167    assert obj.val == 1168    assert obj.next.val == 2169    assert obj.next.previous is obj170@pytest.mark.parametrize('serializer_type', ['cbor'])171def test_cbor_oneshot_unmarshal(serializer):172    def unmarshal_simple(state):173        return SimpleType(**state)174    obj = SimpleType(1, 2)175    serializer.register_custom_type(SimpleType, unmarshaller=unmarshal_simple)176    data = serializer.serialize(obj)177    obj = serializer.deserialize(data)178    assert obj.value_a == 1179    assert obj.value_b == 2180@pytest.mark.parametrize('serializer_type', ['cbor'])181def test_cbor_raw_tag(serializer):182    tag = CBORTag(6000, 'Hello')183    serializer.register_custom_type(SimpleType)184    data = serializer.serialize(tag)185    tag = serializer.deserialize(data)186    assert tag.tag == 6000187    assert tag.value == 'Hello'188class TestObjectHook:189    @pytest.fixture(params=['msgpack', 'cbor'])190    def serializer(self, request):191        if request.param == 'msgpack':192            codec = MsgpackTypeCodec(type_code=None)193            return MsgpackSerializer(custom_type_codec=codec)194        else:195            codec = CBORTypeCodec(type_tag=None)196            return CBORSerializer(custom_type_codec=codec)197    def test_object_hook(self, serializer):198        value1 = SimpleNamespace()199        value1.val = 1200        value1.next = value2 = SimpleNamespace()201        value2.val = 2202        serializer.register_custom_type(SimpleNamespace, typename='Simple')203        data = serializer.serialize(value1)204        obj = serializer.deserialize(data)205        assert obj.val == 1...behave_utils.py
Source:behave_utils.py  
...6"""7from typing import List8import behave9from parse_type import TypeBuilder10def register_custom_type(pattern: str):11    """12    Maps a given regex to a transformation function that produces an object.13    Behave supports these types:14    http://behave.github.io/behave.example/datatype/builtin_types.html15    However, sometimes the addition of types can reduce complexity when writing16    step implementations.17    # TODO(pebaz): Examples for:18    1. Decorator usage with class19    2. Decorator usage with function20    """21    def wrapper(func):22        # TODO(pebaz): Shorter version. Does it work?23        '''24        behave.register_type(**{func.__name__ : func})25        if isinstance(func, type):26            func_to_return = func27        else:28            def inner(*args, **kwargs):29                return func(*args, **kwargs)30            func_to_return = inner31        func_to_return.pattern = pattern32        return func_to_return33        '''34        # Register custom data type35        if isinstance(func, type):36            behave.register_type(**{func.__name__ : func})37            func.pattern = pattern38            return func39        # Register custom parser function40        else:41            behave.register_type(**{func.__name__ : func})42            def inner(*args, **kwargs):43                return func(*args, **kwargs)44            inner.pattern = pattern45            return inner46    return wrapper47def register_choice_type(**kwargs: List[str]):48    """49    Register one or multiple enum types for use in step implementations.50    Usage:51    >>> register_choice_type(Persons=['Bob', 'Jane'], States=['1', '2', '3'])52    """53    for type_name, choices in kwargs.items():54        behave.register_type(**{type_name : TypeBuilder.make_choice(choices)})55@register_custom_type(r"\'.+\'")56def String(text):57    """58    Usage Example:59      Step: When I get an input like 'This'60      Impl: @when('I get an input like {string:String})61    """62    # FIXME(pebaz): This is not correct63    return text.strip("'")64@register_custom_type(r"\[({String},\s?)?\'.+\'\]")65def StringList(text):66    """67    Usage Example:68      Step: When I get an input like this: ['One', 'Two', 'Three']69      Impl: @when('I get an input like this: {the_list:StringList}')70    """71    body = text[1:-1]...test_schema.py
Source:test_schema.py  
...15    list_int_field = get_type({"type": "int", "number_dims": 1})16    assert list_int_field.np_type == int_field.np_type17    list_int_field = get_type({"type": "int", "number_dims": 2})18    assert list_int_field.np_type == int_field.np_type19def test_register_custom_type():20    """21    Test allowed to register marshmallow field and PartialField instances and22    test that uninitialized fields and random classes throw type errors.23    """24    custom_type = "custom"25    assert custom_type not in ALLOWED_TYPES26    register_custom_type(custom_type, ma.fields.String())27    assert custom_type in ALLOWED_TYPES28    register_custom_type("partial-test", PartialField(ma.fields.Str(), {}))29    assert "partial-test" in ALLOWED_TYPES30    with pytest.raises(TypeError):31        register_custom_type("custom", ma.fields.Str)32    class Whatever:33        pass34    with pytest.raises(TypeError):35        register_custom_type("whatever", Whatever())36def test_get_type():37    custom_type = "custom"38    register_custom_type(custom_type, ma.fields.String())39    assert isinstance(get_type({"type": custom_type}), ma.fields.String)40    with pytest.raises(UnknownTypeException):41        get_type({"type": "unknown"})42def test_make_schema():43    custom_type = "custom"44    register_custom_type(custom_type, ma.fields.String())45    schema = {46        "labels": {"lab": {"type": custom_type, "validators": {}}},47        "additional_members": {"custom": {"type": custom_type}},48    }49    assert get_param_schema(schema)50    bad_schema = copy.deepcopy(schema)51    bad_schema["labels"]["lab"]["type"] = "unknown"52    with pytest.raises(UnknownTypeException):53        get_param_schema(bad_schema)54    bad_schema = copy.deepcopy(schema)55    bad_schema["additional_members"]["custom"]["type"] = "unknown"56    with pytest.raises(UnknownTypeException):57        get_param_schema(bad_schema)58    schema = {...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!!
