Пример #1
0
    def testCustomClass(self):
        def something_serializer(obj, serializer, stream, level):
            d = {
                "__class__": "Something",
                "custom": True,
                "name": obj.name,
                "value": obj.value
            }
            serializer.ser_builtins_dict(d, stream, level)

        serpent.register_class(Something, something_serializer)
        s = Something("hello", 42)
        d = serpent.dumps(s)
        x = serpent.loads(d)
        self.assertEqual(
            {
                "__class__": "Something",
                "custom": True,
                "name": "hello",
                "value": 42
            }, x)
        serpent.unregister_class(Something)
        d = serpent.dumps(s)
        x = serpent.loads(d)
        self.assertEqual(("bogus", "state"), x)
Пример #2
0
 def test_deser_speed(self):
     ser = serpent.dumps(self.data, False)
     print("deserialize without indent:",
           timeit.timeit(lambda: serpent.loads(ser), number=1000))
     ser = serpent.dumps(self.data, True)
     print("deserialize with indent:",
           timeit.timeit(lambda: serpent.loads(ser), number=1000))
Пример #3
0
 def testDictCycle(self):
     d = {"x": 1, "y": 2}
     d["d"] = d
     with self.assertRaises(ValueError) as e:
         serpent.dumps(d)
     self.assertEqual("Circular reference detected (dict)",
                      str(e.exception))
Пример #4
0
 def test_unicode_with_escapes_py2(self):
     ser = serpent.dumps(unicode("\n"))
     d = strip_header(ser)
     self.assertEqual(b"'\\n'", d)
     ser = serpent.dumps(unicode("\a"))
     d = strip_header(ser)
     self.assertEqual(b"'\\x07'", d)
Пример #5
0
 def test_exception(self):
     x = ZeroDivisionError("wrong")
     ser = serpent.dumps(x)
     data = serpent.loads(ser)
     self.assertEqual(
         {
             '__class__': 'ZeroDivisionError',
             '__exception__': True,
             'args': ('wrong', ),
             'attributes': {}
         }, data)
     x = ZeroDivisionError("wrong", 42)
     ser = serpent.dumps(x)
     data = serpent.loads(ser)
     self.assertEqual(
         {
             '__class__': 'ZeroDivisionError',
             '__exception__': True,
             'args': ('wrong', 42),
             'attributes': {}
         }, data)
     x.custom_attribute = "custom_attr"
     ser = serpent.dumps(x)
     data = serpent.loads(ser)
     self.assertEqual(
         {
             '__class__': 'ZeroDivisionError',
             '__exception__': True,
             'args': ('wrong', 42),
             'attributes': {
                 'custom_attribute': 'custom_attr'
             }
         }, data)
Пример #6
0
 def test_unicode_quotes(self):
     ser = serpent.dumps(unicode("quotes'\""))
     data = strip_header(ser)
     self.assertEqual(b"'quotes\\'\"'", data)
     ser = serpent.dumps(unicode("quotes2'"))
     data = strip_header(ser)
     self.assertEqual(b"\"quotes2'\"", data)
Пример #7
0
    def test_dict(self):
        ser = serpent.dumps({})
        data = strip_header(ser)
        self.assertEqual(b"{}", data)
        ser = serpent.dumps({}, indent=True)
        data = strip_header(ser)
        self.assertEqual(b"{}", data)

        mydict = {
            42: 'fortytwo',
            'status': False,
            'name': 'Sally',
            'sixteen-and-half': 16.5
        }
        ser = serpent.dumps(mydict)
        data = strip_header(ser)
        self.assertEqual(69, len(data))
        if sys.version_info < (3, 0):
            self.assertEqual(b"{", data[0])
            self.assertEqual(b"}", data[-1])
        else:
            self.assertEqual(ord("{"), data[0])
            self.assertEqual(ord("}"), data[-1])
        ser = serpent.dumps(mydict, indent=True)
        data = strip_header(ser)
        self.assertEqual(86, len(data))
        if sys.version_info < (3, 0):
            self.assertEqual(b"{", data[0])
            self.assertEqual(b"}", data[-1])
        else:
            self.assertEqual(ord("{"), data[0])
            self.assertEqual(ord("}"), data[-1])
Пример #8
0
    def test_class(self):
        class Class1(object):
            def __init__(self):
                self.attr = 1

        class Class2(object):
            def __getstate__(self):
                return {"attr": 42}

        class SlotsClass(object):
            __slots__ = ["attr"]

            def __init__(self):
                self.attr = 1

        c = Class1()
        ser = serpent.dumps(c)
        data = serpent.loads(ser)
        self.assertEqual({'__class__': 'Class1', 'attr': 1}, data)
        c = Class2()
        ser = serpent.dumps(c)
        data = serpent.loads(ser)
        self.assertEqual({'attr': 42}, data)
        c = SlotsClass()
        ser = serpent.dumps(c)
        data = serpent.loads(ser)
        self.assertEqual({'__class__': 'SlotsClass', 'attr': 1}, data)
        import pprint
        p = pprint.PrettyPrinter(stream="dummy", width=99)
        ser = serpent.dumps(p)
        data = serpent.loads(ser)
        self.assertEqual("PrettyPrinter", data["__class__"])
        self.assertEqual(99, data["_width"])
Пример #9
0
 def test_exception(self):
     x = ZeroDivisionError("wrong")
     ser = serpent.dumps(x)
     data = serpent.loads(ser)
     self.assertEqual({
         '__class__': 'ZeroDivisionError',
         '__exception__': True,
         'args': ('wrong',),
         'attributes': {}
     }, data)
     x = ZeroDivisionError("wrong", 42)
     ser = serpent.dumps(x)
     data = serpent.loads(ser)
     self.assertEqual({
         '__class__': 'ZeroDivisionError',
         '__exception__': True,
         'args': ('wrong', 42),
         'attributes': {}
     }, data)
     x.custom_attribute = "custom_attr"
     ser = serpent.dumps(x)
     data = serpent.loads(ser)
     self.assertEqual({
         '__class__': 'ZeroDivisionError',
         '__exception__': True,
         'args': ('wrong', 42),
         'attributes': {'custom_attribute': 'custom_attr'}
     }, data)
Пример #10
0
    def test_class(self):
        class Class1(object):
            def __init__(self):
                self.attr = 1

        class Class2(object):
            def __getstate__(self):
                return {"attr": 42}

        class SlotsClass(object):
            __slots__ = ["attr"]

            def __init__(self):
                self.attr = 1

        c = Class1()
        ser = serpent.dumps(c)
        data = serpent.loads(ser)
        self.assertEqual({'__class__': 'Class1', 'attr': 1}, data)
        c = Class2()
        ser = serpent.dumps(c)
        data = serpent.loads(ser)
        self.assertEqual({'attr': 42}, data)
        c = SlotsClass()
        ser = serpent.dumps(c)
        data = serpent.loads(ser)
        self.assertEqual({'__class__': 'SlotsClass', 'attr': 1}, data)
        import pprint
        p = pprint.PrettyPrinter(stream="dummy", width=99)
        ser = serpent.dumps(p)
        data = serpent.loads(ser)
        self.assertEqual("PrettyPrinter", data["__class__"])
        self.assertEqual(99, data["_width"])
Пример #11
0
    def test_dict(self):
        ser = serpent.dumps({})
        data = strip_header(ser)
        self.assertEqual(b"{}", data)
        ser = serpent.dumps({}, indent=True)
        data = strip_header(ser)
        self.assertEqual(b"{}", data)

        mydict = {
            42: 'fortytwo',
            'status': False,
            'name': 'Sally',
            'sixteen-and-half': 16.5
        }
        ser = serpent.dumps(mydict)
        data = strip_header(ser)
        self.assertEqual(69, len(data))
        if sys.version_info < (3, 0):
            self.assertEqual(b"{", data[0])
            self.assertEqual(b"}", data[-1])
        else:
            self.assertEqual(ord("{"), data[0])
            self.assertEqual(ord("}"), data[-1])
        ser = serpent.dumps(mydict, indent=True)
        data = strip_header(ser)
        self.assertEqual(86, len(data))
        if sys.version_info < (3, 0):
            self.assertEqual(b"{", data[0])
            self.assertEqual(b"}", data[-1])
        else:
            self.assertEqual(ord("{"), data[0])
            self.assertEqual(ord("}"), data[-1])
Пример #12
0
 def testClassCycle(self):
     d = Cycle()
     d.make_cycle(d)
     with self.assertRaises(ValueError) as e:
         serpent.dumps(d)
     self.assertEqual("Circular reference detected (class)",
                      str(e.exception))
Пример #13
0
    def test_indent_sorting(self):
        # non-indented should not be sorted, indented should
        data = {"ee": 1, "dd": 1, "cc": 1, "bb": 1, "aa": 1, 'ff': 1, 'hh': 1, 'gg': 1}
        ser = serpent.dumps(data, False)
        ser = strip_header(ser)
        self.assertNotEqual(b"{'aa':1,'bb':1,'cc':1,'dd':1,'ee':1,'ff':1,'gg':1,'hh':1}", ser)
        ser = serpent.dumps(data, True)
        ser = strip_header(ser)
        self.assertEqual(b"""{
  'aa': 1,
  'bb': 1,
  'cc': 1,
  'dd': 1,
  'ee': 1,
  'ff': 1,
  'gg': 1,
  'hh': 1
}""", ser)
        data = set("irmen de jong irmen de jong666")
        ser = serpent.dumps(data, False)
        ser = strip_header(ser)
        self.assertNotEqual(b"' ','6','d','e','g','i','j','m','n','o','r'", ser[1:-1])
        ser = serpent.dumps(data, True)
        ser = strip_header(ser)
        self.assertEqual(b"\n  ' ',\n  '6',\n  'd',\n  'e',\n  'g',\n  'i',\n  'j',\n  'm',\n  'n',\n  'o',\n  'r'\n", ser[1:-1])
Пример #14
0
 def testListCycle(self):
     d = [1, 2, 3]
     d.append(d)
     with self.assertRaises(ValueError) as e:
         serpent.dumps(d)
     self.assertEqual("Circular reference detected (list)",
                      str(e.exception))
Пример #15
0
    def test_indent_containers(self):
        data = [1, 2, 3]
        ser = serpent.dumps(data, indent=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""[
  1,
  2,
  3
]""", ser)
        data = (1, 2, 3)
        ser = serpent.dumps(data, indent=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""(
  1,
  2,
  3
)""", ser)
        data = set([1])
        ser = serpent.dumps(data, indent=True,
                            set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  1
}""", ser)
        data = {"one": 1}
        ser = serpent.dumps(data, indent=True,
                            set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  'one': 1
}""", ser)

        data = {
            "first": [1, 2, ("a", "b")],
            "second": {
                1: False
            },
            "third": set([1, 2])
        }
        ser = serpent.dumps(data, indent=True,
                            set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual(
            """{
  'first': [
    1,
    2,
    (
      'a',
      'b'
    )
  ],
  'second': {
    1: False
  },
  'third': {
    1,
    2
  }
}""", ser)
Пример #16
0
 def test_ser_speed(self):
     print(
         "serialize without indent:",
         timeit.timeit(lambda: serpent.dumps(self.data, False),
                       number=1000))
     print(
         "serialize with indent:",
         timeit.timeit(lambda: serpent.dumps(self.data, True), number=1000))
Пример #17
0
 def test_deser_speed(self):
     use_set_literals = sys.version_info >= (3, 2)
     ser = serpent.dumps(self.data, False, set_literals=use_set_literals)
     print("deserialize without indent:",
           timeit.timeit(lambda: serpent.loads(ser), number=1000))
     ser = serpent.dumps(self.data, True, set_literals=use_set_literals)
     print("deserialize with indent:",
           timeit.timeit(lambda: serpent.loads(ser), number=1000))
Пример #18
0
    def serilized(configure):
        confs = configure.confs
        confFile = configure.confFile

        byteString = serpent.dumps(confs, indent=True)
        byteString = byteString + "####" + serpent.dumps(confFile, indent=True)

        return byteString
Пример #19
0
 def test_string(self):
     ser = serpent.dumps("hello")
     data = strip_header(ser)
     self.assertEqual(b"'hello'", data)
     ser = serpent.dumps("quotes'\"")
     data = strip_header(ser)
     self.assertEqual(b"'quotes\\'\"'", data)
     ser = serpent.dumps("quotes2'")
     data = strip_header(ser)
     self.assertEqual(b"\"quotes2'\"", data)
Пример #20
0
 def test_string(self):
     ser = serpent.dumps("hello")
     data = strip_header(ser)
     self.assertEqual(b"'hello'", data)
     ser = serpent.dumps("quotes'\"")
     data = strip_header(ser)
     self.assertEqual(b"'quotes\\'\"'", data)
     ser = serpent.dumps("quotes2'")
     data = strip_header(ser)
     self.assertEqual(b"\"quotes2'\"", data)
Пример #21
0
 def test_timezone(self):
     import pytz    # requires pytz library
     tz_nl = pytz.timezone("Europe/Amsterdam")
     dt_tz = tz_nl.localize(datetime.datetime(2013, 1, 20, 23, 59, 45, 999888))
     ser = serpent.dumps(dt_tz)
     data = strip_header(ser)
     self.assertEqual(b"'2013-01-20T23:59:45.999888+01:00'", data)   # normal time
     dt_tz = tz_nl.localize(datetime.datetime(2013, 5, 10, 13, 59, 45, 999888))
     ser = serpent.dumps(dt_tz)
     data = strip_header(ser)
     self.assertEqual(b"'2013-05-10T13:59:45.999888+02:00'", data)   # daylight saving time
Пример #22
0
 def test_array(self):
     ser = serpent.dumps(array.array('u', unicode("unicode")))
     data = strip_header(ser)
     self.assertEqual(b"'unicode'", data)
     ser = serpent.dumps(array.array('i', [44, 45, 46]))
     data = strip_header(ser)
     self.assertEqual(b"[44,45,46]", data)
     if sys.version_info < (3, 0):
         ser = serpent.dumps(array.array('c', "normal"))
         data = strip_header(ser)
         self.assertEqual(b"'normal'", data)
Пример #23
0
 def test_array(self):
     ser = serpent.dumps(array.array('u', unicode("unicode")))
     data = strip_header(ser)
     self.assertEqual(b"'unicode'", data)
     ser = serpent.dumps(array.array('i', [44, 45, 46]))
     data = strip_header(ser)
     self.assertEqual(b"[44,45,46]", data)
     if sys.version_info < (3, 0):
         ser = serpent.dumps(array.array('c', "normal"))
         data = strip_header(ser)
         self.assertEqual(b"'normal'", data)
Пример #24
0
 def test_dict_iters(self):
     data = {"john": 22, "sophie": 34, "bob": 26}
     ser = serpent.loads(serpent.dumps(data.keys()))
     self.assertIsInstance(ser, list)
     self.assertEqual(["bob", "john", "sophie"], sorted(ser))
     ser = serpent.loads(serpent.dumps(data.values()))
     self.assertIsInstance(ser, list)
     self.assertEqual([22, 26, 34], sorted(ser))
     ser = serpent.loads(serpent.dumps(data.items()))
     self.assertIsInstance(ser, list)
     self.assertEqual([("bob", 26), ("john", 22), ("sophie", 34)],
                      sorted(ser))
Пример #25
0
 def test_unicode(self):
     u = "euro" + unichr(0x20ac)
     self.assertTrue(type(u) is unicode)
     ser = serpent.dumps(u)
     data = serpent.loads(ser)
     self.assertEqual(u, data)
     ser = serpent.dumps(unicode("quotes'\""))
     data = strip_header(ser)
     self.assertEqual(b"'quotes\\'\"'", data)
     ser = serpent.dumps(unicode("quotes2'"))
     data = strip_header(ser)
     self.assertEqual(b"\"quotes2'\"", data)
Пример #26
0
 def test_bytes(self):
     if sys.version_info >= (3, 0):
         ser = serpent.dumps(bytes(b"abcdef"))
         data = serpent.loads(ser)
         self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
     ser = serpent.dumps(bytearray(b"abcdef"))
     data = serpent.loads(ser)
     self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
     if sys.version_info >= (2, 7):
         ser = serpent.dumps(memoryview(b"abcdef"))
         data = serpent.loads(ser)
         self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
Пример #27
0
 def test_bytes(self):
     if sys.version_info >= (3, 0):
         ser = serpent.dumps(bytes(b"abcdef"))
         data = serpent.loads(ser)
         self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
     ser = serpent.dumps(bytearray(b"abcdef"))
     data = serpent.loads(ser)
     self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
     if sys.version_info >= (2, 7):
         ser = serpent.dumps(memoryview(b"abcdef"))
         data = serpent.loads(ser)
         self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
Пример #28
0
 def test_unicode_with_escapes_unichrs(self):
     ser = serpent.dumps("\a" + unichr(0x20ac))
     d = strip_header(ser)
     self.assertEqual(b"'\\x07\\u20ac'", d)
     line = "'euro" + unichr(
         0x20ac) + "\nlastline\ttab\\@slash\a\b\f\n\r\t\v'"
     ser = serpent.dumps(line)
     d = strip_header(ser)
     self.assertEqual(
         b"\"'euro\\u20ac\\nlastline\\ttab\\\\@slash\\x07\\x08\\x0c\\n\\r\\t\\x0b'\"",
         d)
     data = serpent.loads(ser)
     self.assertEqual(line, data)
Пример #29
0
 def test_class_hashable_set_element_check(self):
     import pprint
     pp = pprint.PrettyPrinter(stream="dummy", width=42)
     with self.assertRaises(TypeError) as x:
         serpent.dumps({
             1, 2, 3, strip_header
         })  # can only serialize simple typles as set elements (hashable)
     self.assertTrue("hashable type" in str(x.exception))
     with self.assertRaises(TypeError) as x:
         serpent.dumps({
             1, 2, 3, pp
         })  # can only serialize simple typles as set elements (hashable)
     self.assertTrue("hashable type" in str(x.exception))
Пример #30
0
    def test_enums(self):
        import enum

        class Animal(enum.Enum):
            BEE = 1
            CAT = 2
            DOG = 3

        v = serpent.loads(serpent.dumps(Animal.CAT))
        self.assertEqual(2, v)
        Animal2 = enum.Enum("Animals2", "BEE CAT DOG HORSE RABBIT")
        v = serpent.loads(serpent.dumps(Animal2.HORSE))
        self.assertEqual(4, v)
Пример #31
0
    def test_indent_containers(self):
        data = [1, 2, 3]
        ser = serpent.dumps(data, indent=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""[
  1,
  2,
  3
]""", ser)
        data = (1, 2, 3)
        ser = serpent.dumps(data, indent=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""(
  1,
  2,
  3
)""", ser)
        data = set([1])
        ser = serpent.dumps(data, indent=True, set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  1
}""", ser)
        data = {"one": 1}
        ser = serpent.dumps(data, indent=True, set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  'one': 1
}""", ser)

        data = {"first": [1, 2, ("a", "b")], "second": {1: False}, "third": set([1, 2])}
        ser = serpent.dumps(data, indent=True, set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  'first': [
    1,
    2,
    (
      'a',
      'b'
    )
  ],
  'second': {
    1: False
  },
  'third': {
    1,
    2
  }
}""", ser)
Пример #32
0
    def test_sorting(self):
        obj = [3, 2, 1]
        ser = serpent.dumps(obj)
        data = strip_header(ser)
        self.assertEqual(b"[3,2,1]", data)
        obj = (3, 2, 1)
        ser = serpent.dumps(obj)
        data = strip_header(ser)
        self.assertEqual(b"(3,2,1)", data)

        obj = {3: "three", 4: "four", 2: "two", 1: "one"}
        ser = serpent.dumps(obj)
        data = strip_header(ser)
        self.assertEqual(36, len(data))
        obj = set([3, 4, 2, 1, 6, 5])
        ser = serpent.dumps(obj)
        data = strip_header(ser)
        self.assertEqual(13, len(data))
        ser = serpent.dumps(obj, indent=True)
        data = strip_header(ser)
        self.assertEqual(b"{\n  1,\n  2,\n  3,\n  4,\n  5,\n  6\n}",
                         data)  # sorted

        obj = set([3, "something"])
        ser = serpent.dumps(obj, indent=False)
        data = strip_header(ser)
        self.assertTrue(data == b"{3,'something'}"
                        or data == b"{'something',3}")
        ser = serpent.dumps(obj, indent=True)
        data = strip_header(ser)
        self.assertTrue(data == b"{\n  3,\n  'something'\n}"
                        or data == b"{\n  'something',\n  3\n}")

        obj = {3: "three", "something": 99}
        ser = serpent.dumps(obj, indent=False)
        data = strip_header(ser)
        self.assertTrue(data == b"{'something':99,3:'three'}"
                        or data == b"{3:'three','something':99}")
        ser = serpent.dumps(obj, indent=True)
        data = strip_header(ser)
        self.assertTrue(data == b"{\n  'something': 99,\n  3: 'three'\n}"
                        or data == b"{\n  3: 'three',\n  'something': 99\n}")

        obj = {3: "three", 4: "four", 5: "five", 2: "two", 1: "one"}
        ser = serpent.dumps(obj, indent=True)
        data = strip_header(ser)
        self.assertEqual(
            b"{\n  1: 'one',\n  2: 'two',\n  3: 'three',\n  4: 'four',\n  5: 'five'\n}",
            data)  # sorted
Пример #33
0
 def test_string_with_escapes(self):
     ser = serpent.dumps("\n")
     d = strip_header(ser)
     self.assertEqual(b"'\\n'", d)
     ser = serpent.dumps("\a")
     d = strip_header(ser)
     self.assertEqual(b"'\\x07'", d)  # repr() does this hex escape
     line = "'hello\nlastline\ttab\\@slash\a\b\f\n\r\t\v'"
     ser = serpent.dumps(line)
     d = strip_header(ser)
     self.assertEqual(
         b"\"'hello\\nlastline\\ttab\\\\@slash\\x07\\x08\\x0c\\n\\r\\t\\x0b'\"",
         d)  # the hex escapes are done by repr()
     data = serpent.loads(ser)
     self.assertEqual(line, data)
Пример #34
0
 def test_timezone(self):
     import pytz  # requires pytz library
     tz_nl = pytz.timezone("Europe/Amsterdam")
     dt_tz = tz_nl.localize(
         datetime.datetime(2013, 1, 20, 23, 59, 45, 999888))
     ser = serpent.dumps(dt_tz)
     data = strip_header(ser)
     self.assertEqual(b"'2013-01-20T23:59:45.999888+01:00'",
                      data)  # normal time
     dt_tz = tz_nl.localize(
         datetime.datetime(2013, 5, 10, 13, 59, 45, 999888))
     ser = serpent.dumps(dt_tz)
     data = strip_header(ser)
     self.assertEqual(b"'2013-05-10T13:59:45.999888+02:00'",
                      data)  # daylight saving time
Пример #35
0
 def testDefaultDict(self):
     dd = collections.defaultdict(list)
     dd['a'] = 1
     dd['b'] = 2
     d = serpent.dumps(dd)
     dd2 = serpent.loads(d)
     self.assertEqual({'a': 1, 'b': 2}, dd2)
Пример #36
0
 def test_unicode_with_escapes(self):
     line = "euro" + unichr(0x20ac) + "\nlastline\ttab\\@slash"
     ser = serpent.dumps(line)
     d = strip_header(ser)
     self.assertEqual(b"'euro\xe2\x82\xac\\nlastline\\ttab\\\\@slash'", d)
     data = serpent.loads(ser)
     self.assertEqual(line, data)
Пример #37
0
 def test_unicode_with_escapes(self):
     line = "euro"+unichr(0x20ac)+"\nlastline\ttab\\@slash"
     ser = serpent.dumps(line)
     d = strip_header(ser)
     self.assertEqual(b"'euro\xe2\x82\xac\\nlastline\\ttab\\\\@slash'", d)
     data = serpent.loads(ser)
     self.assertEqual(line, data)
Пример #38
0
 def test_weird_complex(self):
     c1 = complex(float('inf'), 4)
     ser = serpent.dumps(c1)
     c2 = serpent.loads(ser)
     self.assertEqual(c1, c2)
     c3 = serpent.loads(b"(1e30000+4.0j)")
     self.assertEqual(c1, c3)
Пример #39
0
 def test_numbers(self):
     ser = serpent.dumps(12345)
     data = strip_header(ser)
     self.assertEqual(b"12345", data)
     ser = serpent.dumps(123456789123456789123456789)
     data = strip_header(ser)
     self.assertEqual(b"123456789123456789123456789", data)
     ser = serpent.dumps(99.1234)
     data = strip_header(ser)
     self.assertEqual(b"99.1234", data)
     ser = serpent.dumps(decimal.Decimal("1234.9999999999"))
     data = strip_header(ser)
     self.assertEqual(b"'1234.9999999999'", data)
     ser = serpent.dumps(2 + 3j)
     data = strip_header(ser)
     self.assertEqual(b"(2+3j)", data)
Пример #40
0
def example():
    use_set_literals = sys.version_info >= (3, 2)  # check if we can use set literals

    data = {
        "tuple": (1, 2, 3),
        "date": datetime.datetime.now(),
        "set": {'a', 'b', 'c'},
        "class": CustomClass("Sally", 26)
    }

    # serialize the object
    ser = serpent.dumps(data, indent=True, set_literals=use_set_literals)
    # print it to the screen, but usually you'd save the bytes to a file or transfer them over a network connection
    print("Serialized data:")
    print(ser.decode("UTF-8"))

    # deserialize the bytes and print the objects
    obj = serpent.loads(ser)
    print("Deserialized data:")
    print("tuple:", obj["tuple"])
    print("date:", obj["date"])
    print("set:", obj["set"])
    clazz = obj["class"]
    print("class attributes: type={0} name={1} age={2}".format(
        clazz["__class__"], clazz["name"], clazz["age"]))
Пример #41
0
 def test_numbers(self):
     ser = serpent.dumps(12345)
     data = strip_header(ser)
     self.assertEqual(b"12345", data)
     ser = serpent.dumps(123456789123456789123456789)
     data = strip_header(ser)
     self.assertEqual(b"123456789123456789123456789", data)
     ser = serpent.dumps(99.1234)
     data = strip_header(ser)
     self.assertEqual(b"99.1234", data)
     ser = serpent.dumps(decimal.Decimal("1234.9999999999"))
     data = strip_header(ser)
     self.assertEqual(b"'1234.9999999999'", data)
     ser = serpent.dumps(2 + 3j)
     data = strip_header(ser)
     self.assertEqual(b"(2+3j)", data)
Пример #42
0
	def getMenus(self, fecha):
		try:
			print "Menus pyro"
			fecha = str(fecha).split('-')
			fecha = date(int(fecha[0]),int(fecha[1]),int(fecha[2]))
			menus = []
			for x in Menu_db.select().where( Menu_db.fecha_ini <= fecha  ).where( Menu_db.fecha_fin >= fecha ):
				p = [] #primeros
				s = [] #segundos
				d = [] #postres
				m = {}
				m['nombre'] = x.nombre
				m['disponible'] = x.disponible
				m['precio'] = float(x.precio)
				m['descripcion'] = x.descripcion
				m['fecha_ini'] = x.fecha_ini
				m['fecha_fin'] = x.fecha_fin
				m['imagen'] = x.imagen
				for y in Item_db.select().where(Item_db.primeros==x):
					p.append(y)
				for y in Item_db.select().where(Item_db.segundos==x):
					s.append(y)
				for y in Item_db.select().where(Item_db.postres==x):
					d.append(y)
				m['primeros'] = p
				m['segundos'] = s
				m['postres'] = d
				# agregamos el menu
				menus.append(m)
			return serpent.dumps(menus,indent=False)
		except Exception, e:
			return False
Пример #43
0
 def test_time(self):
     ser = serpent.dumps(datetime.datetime(2013, 1, 20, 23, 59, 45, 999888))
     data = strip_header(ser)
     self.assertEqual(b"'2013-01-20T23:59:45.999888'", data)
     ser = serpent.dumps(datetime.time(23, 59, 45, 999888))
     data = strip_header(ser)
     self.assertEqual(b"'23:59:45.999888'", data)
     ser = serpent.dumps(datetime.time(23, 59, 45))
     data = strip_header(ser)
     self.assertEqual(b"'23:59:45'", data)
     ser = serpent.dumps(datetime.timedelta(1, 4000, 999888, minutes=22))
     data = strip_header(ser)
     self.assertEqual(b"91720.999888", data)
     ser = serpent.dumps(datetime.timedelta(seconds=12345))
     data = strip_header(ser)
     self.assertEqual(b"12345.0", data)
Пример #44
0
 def test_nullbytesunicode(self):
     line = unichr(0) + "null"
     ser = serpent.dumps(line)
     data = strip_header(ser)
     self.assertEqual(b"'\\x00null'", data)
     data = serpent.loads(ser)
     self.assertEqual(line, data)
Пример #45
0
 def test_time(self):
     ser = serpent.dumps(datetime.datetime(2013, 1, 20, 23, 59, 45, 999888))
     data = strip_header(ser)
     self.assertEqual(b"'2013-01-20T23:59:45.999888'", data)
     ser = serpent.dumps(datetime.time(23, 59, 45, 999888))
     data = strip_header(ser)
     self.assertEqual(b"'23:59:45.999888'", data)
     ser = serpent.dumps(datetime.time(23, 59, 45))
     data = strip_header(ser)
     self.assertEqual(b"'23:59:45'", data)
     ser = serpent.dumps(datetime.timedelta(1, 4000, 999888, minutes=22))
     data = strip_header(ser)
     self.assertEqual(b"91720.999888", data)
     ser = serpent.dumps(datetime.timedelta(seconds=12345))
     data = strip_header(ser)
     self.assertEqual(b"12345.0", data)
Пример #46
0
 def test_unicode_with_escapes_py3(self):
     ser = serpent.dumps(unicode("\n"))
     d = strip_header(ser)
     self.assertEqual(b"'\\n'", d)
     ser = serpent.dumps(unicode("\a"))
     d = strip_header(ser)
     self.assertEqual(b"'\\x07'", d)
     ser = serpent.dumps("\a"+unichr(0x20ac))
     d = strip_header(ser)
     self.assertEqual(b"'\\x07\xe2\x82\xac'", d)
     line = "'euro" + unichr(0x20ac) + "\nlastline\ttab\\@slash\a\b\f\n\r\t\v'"
     ser = serpent.dumps(line)
     d = strip_header(ser)
     self.assertEqual(b"\"'euro\xe2\x82\xac\\nlastline\\ttab\\\\@slash\\x07\\x08\\x0c\\n\\r\\t\\x0b'\"", d)
     data = serpent.loads(ser)
     self.assertEqual(line, data)
Пример #47
0
 def testRegular(self):
     import pprint
     p = pprint.PrettyPrinter(stream="dummy", width=42)
     ser = serpent.dumps(p)
     data = serpent.loads(ser)
     self.assertEqual(42, data["_width"])
     self.assertEqual("PrettyPrinter", data["__class__"])
Пример #48
0
 def test_weird_doubles(self):
     values = [float('inf'), float('-inf'), float('nan')]
     ser = serpent.dumps(values)
     values2 = serpent.loads(ser)
     self.assertEqual([float('inf'), float('-inf'), {'__class__':'float','value':'nan'}], values2)
     values2 = serpent.loads(b"[1e30000,-1e30000]")
     self.assertEqual([float('inf'), float('-inf')], values2)
Пример #49
0
	def getMenu(self, menu):
		try:
			print "Menu pyro"
			x = Menu_db.select().where(Menu_db.nombre==menu).get()
			p = [] #primeros
			s = [] #segundos
			d = [] #postres
			m = {}
			m['nombre'] = x.nombre
			m['disponible'] = x.disponible
			m['precio'] = float(x.precio)
			m['descripcion'] = x.descripcion
			m['fecha_ini'] = x.fecha_ini
			m['fecha_fin'] = x.fecha_fin
			m['imagen'] = x.imagen
			for y in Item_db.select().where(Item_db.primeros==x):
				p.append(y)
			for y in Item_db.select().where(Item_db.segundos==x):
				s.append(y)
			for y in Item_db.select().where(Item_db.postres==x):
				d.append(y)
			m['primeros'] = p
			m['segundos'] = s
			m['postres'] = d
			return serpent.dumps(m,indent=False)
		except Exception, e:
			return False
Пример #50
0
 def testUserDict(self):
     obj = collections.UserDict()
     obj['a'] = 1
     obj['b'] = 2
     d = serpent.dumps(obj)
     obj2 = serpent.loads(d)
     self.assertEqual({'a': 1, 'b': 2}, obj2)
Пример #51
0
 def testRegular(self):
     import pprint
     p = pprint.PrettyPrinter(stream="dummy", width=42)
     ser = serpent.dumps(p)
     data = serpent.loads(ser)
     self.assertEqual(42, data["_width"])
     self.assertEqual("PrettyPrinter", data["__class__"])
Пример #52
0
 def testUserDict(self):
     obj = collections.UserDict()
     obj['a'] = 1
     obj['b'] = 2
     d = serpent.dumps(obj)
     obj2 = serpent.loads(d)
     self.assertEqual({'a': 1, 'b': 2}, obj2)
Пример #53
0
 def testDefaultDict(self):
     dd = collections.defaultdict(list)
     dd['a'] = 1
     dd['b'] = 2
     d = serpent.dumps(dd)
     dd2 = serpent.loads(d)
     self.assertEqual({'a': 1, 'b': 2}, dd2)
Пример #54
0
 def testOrderedDict(self):
     o = collections.OrderedDict()
     o['apple'] = 1
     o['banana'] = 2
     o['orange'] = 3
     d = serpent.dumps(o)
     o2 = serpent.loads(d)
     self.assertEqual({"__class__": "OrderedDict", "items": [('apple', 1), ('banana', 2), ('orange', 3)]}, o2)
Пример #55
0
    def testUUID(self):
        uid = uuid.uuid4()
        string_uid = str(uid)
        ser = serpent.dumps(uid)
        x = serpent.loads(ser)
        self.assertEqual(string_uid, x)

        def custom_uuid_translate(obj, serp, stream, level):
            serp._serialize("custom_uuid!", stream, level)

        serpent.register_class(uuid.UUID, custom_uuid_translate)
        try:
            ser = serpent.dumps(uid)
            x = serpent.loads(ser)
            self.assertEqual("custom_uuid!", x)
        finally:
            serpent.unregister_class(uuid.UUID)
Пример #56
0
    def testIntercept(self):
        ex = ZeroDivisionError("wrong")
        ser = serpent.dumps(ex)
        data = serpent.loads(ser)
        # default behavior is to serialize the exception to a dict
        self.assertEqual({'__exception__': True, 'args': ('wrong',), '__class__': 'ZeroDivisionError', 'attributes': {}}, data)

        def custom_exception_translate(obj, serializer, stream, indent):
            serializer._serialize("custom_exception!", stream, indent)

        try:
            serpent.register_class(Exception, custom_exception_translate)
            ser = serpent.dumps(ex)
            data = serpent.loads(ser)
            self.assertEqual("custom_exception!", data)
        finally:
            serpent.unregister_class(Exception)
Пример #57
0
 def test_header(self):
     ser = serpent.dumps(None, set_literals=True)
     if sys.platform == "cli":
         header, _, rest = ser.partition("\n")
     else:
         self.assertTrue(type(ser) is bytes)
         header, _, rest = ser.partition(b"\n")
     hdr = "# serpent utf-8 python3.2".encode("utf-8")
     self.assertEqual(hdr, header)
     ser = serpent.dumps(None, set_literals=False)
     if sys.platform == "cli":
         header, _, rest = ser.partition("\n")
     else:
         self.assertTrue(type(ser) is bytes)
         header, _, rest = ser.partition(b"\n")
     hdr = "# serpent utf-8 python2.6".encode("utf-8")
     self.assertEqual(hdr, header)
Пример #58
0
 def run(self):
     big_list = [Cycle() for _ in range(1000)]
     while not self.stop_running:
         try:
             _ = serpent.dumps(big_list)
         except RuntimeError as x:
             self.error = x
             print(x)
             break
Пример #59
0
 def test_pickle_api(self):
     ser = serpent.dumps([1, 2, 3])
     serpent.loads(ser)
     tmpfn = tempfile.mktemp()
     with open(tmpfn, "wb") as outf:
         serpent.dump([1, 2, 3], outf, indent=True, set_literals=True)
     with open(tmpfn, "rb") as inf:
         data = serpent.load(inf)
         self.assertEqual([1, 2, 3], data)
     os.remove(tmpfn)
Пример #60
0
    def testCustomClass(self):
        def something_serializer(obj, serializer, stream, level):
            d = {
                "__class__": "Something",
                "custom": True,
                "name": obj.name,
                "value": obj.value
            }
            serializer.ser_builtins_dict(d, stream, level)

        serpent.register_class(Something, something_serializer)
        s = Something("hello", 42)
        d = serpent.dumps(s)
        x = serpent.loads(d)
        self.assertEqual({"__class__": "Something", "custom": True, "name": "hello", "value": 42}, x)
        serpent.unregister_class(Something)
        d = serpent.dumps(s)
        x = serpent.loads(d)
        self.assertEqual(("bogus", "state"), x)