~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/tests/test_chat.py

  • Committer: David Coles
  • Date: 2010-02-24 12:23:57 UTC
  • Revision ID: coles.david@gmail.com-20100224122357-ejlonohh1l4dg0ng
chat: Factor out the encoding and decoding functions so we can test them and possibly reuse elsewhere

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
import os
20
20
import random
21
21
 
 
22
import cjson
22
23
from nose.tools import assert_equal, raises
23
24
 
24
25
import ivle.chat
87
88
        for i in range(10):
88
89
            assert_equal(ivle.chat.recv_netstring(self.s2), messages[i])
89
90
 
 
91
    def test_encode(self):
 
92
        """Check that we correctly encode a basic object
 
93
        """
 
94
        MESSAGE = {}
 
95
        MAGIC = "3EE"
 
96
        content = cjson.encode(MESSAGE)
 
97
        # Digest can be formed with `echo -n "${content}${MAGIC}" | md5sum`
 
98
        DIGEST = '2b59b68e1ac0852b87fb7e64946f2658'
 
99
        expected = {'digest': DIGEST,
 
100
                'content': content}
 
101
        encoded = ivle.chat.encode(MESSAGE, MAGIC)
 
102
        assert_equal(cjson.decode(encoded), expected)
 
103
 
 
104
    def test_encode_decode(self):
 
105
        """Check that a round trip encoding and decoding works
 
106
        """
 
107
        MESSAGE = {'message': 'Hello, world'}
 
108
        MAGIC = "MagicString"
 
109
        encoded = ivle.chat.encode(MESSAGE, MAGIC)
 
110
        decoded = ivle.chat.decode(encoded, MAGIC)
 
111
        assert_equal(decoded, MESSAGE)
 
112
 
 
113
    @raises(ivle.chat.ProtocolError)
 
114
    def test_decode_bad_magic(self):
 
115
        """Check that a bad digest causes a ProtocolError to be raised
 
116
        """
 
117
        CHATMESSAGE = ('{"content": "{\\"a\\": \\"b\\"}", "digest": ' +
 
118
                '"eb860a5fe8fdbef19ffb79e3a5c47113"}')
 
119
        CORRECTMAGIC = "AEIOU"
 
120
        INCORRECTMAGIC = "ABCDE"
 
121
 
 
122
        # Check our "correct" string decodes without a ProtocolError
 
123
        try:
 
124
            ivle.chat.decode(CHATMESSAGE, CORRECTMAGIC)
 
125
        except ivle.chat.ProtocolError:
 
126
            raise AssertionError("ProtocolError with 'correct' magic")
 
127
 
 
128
        # This should raise the ProtocolError
 
129
        ivle.chat.decode(CHATMESSAGE, INCORRECTMAGIC)