aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/test/test_stateful.py
blob: 365bfacdc0801d2033be6c1b796e437df0fdcf2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.


"""
Test cases for twisted.protocols.stateful
"""

from twisted.trial.unittest import TestCase
from twisted.test import test_protocols
from twisted.protocols.stateful import StatefulProtocol

from struct import pack, unpack, calcsize


class MyInt32StringReceiver(StatefulProtocol):
    """
    A stateful Int32StringReceiver.
    """
    MAX_LENGTH = 99999
    structFormat = "!I"
    prefixLength = calcsize(structFormat)

    def getInitialState(self):
        return self._getHeader, 4

    def lengthLimitExceeded(self, length):
        self.transport.loseConnection()

    def _getHeader(self, msg):
        length, = unpack("!i", msg)
        if length > self.MAX_LENGTH:
            self.lengthLimitExceeded(length)
            return
        return self._getString, length

    def _getString(self, msg):
        self.stringReceived(msg)
        return self._getHeader, 4

    def stringReceived(self, msg):
        """
        Override this.
        """
        raise NotImplementedError

    def sendString(self, data):
        """
        Send an int32-prefixed string to the other end of the connection.
        """
        self.transport.write(pack(self.structFormat, len(data)) + data)


class TestInt32(MyInt32StringReceiver):
    def connectionMade(self):
        self.received = []

    def stringReceived(self, s):
        self.received.append(s)

    MAX_LENGTH = 50
    closed = 0

    def connectionLost(self, reason):
        self.closed = 1


class Int32TestCase(TestCase, test_protocols.IntNTestCaseMixin):
    protocol = TestInt32
    strings = ["a", "b" * 16]
    illegalStrings = ["\x10\x00\x00\x00aaaaaa"]
    partialStrings = ["\x00\x00\x00", "hello there", ""]

    def test_bigReceive(self):
        r = self.getProtocol()
        big = ""
        for s in self.strings * 4:
            big += pack("!i", len(s)) + s
        r.dataReceived(big)
        self.assertEqual(r.received, self.strings * 4)