from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest

from DefaultValuesTest import *
from DefaultValuesTest.ttypes import *

from thrift.protocol.TBinaryProtocol import *
from thrift.transport.TTransport import *

class TestDefaultValues(unittest.TestCase):

    def testReadDefaults(self):
        w = DefaultValues(def_reg=11, req_reg=22)
        r = DefaultValues()
        write_to_read(w, r)
        self.assertEquals(r.def_reg, 11)
        self.assertEquals(r.req_reg, 22)
        self.assertEquals(r.def_val, 12)
        self.assertEquals(r.req_val, 34)
        self.assertEquals(r.opt_val, 56)
        self.assertIsNone(r.opt_list_reg)
        self.assertEquals(r.opt_list_val, [56, 78, 90])

    def testDefaultsAreNotOnTheWire(self):
        w = DefaultValues(def_reg=11, req_reg=22)
        r = DefaultValues(def_reg=0, opt_reg=33, opt_val=44)
        write_to_read(w, r)
        self.assertEquals(r.def_reg, 11)
        self.assertEquals(r.opt_reg, 33)
        self.assertEquals(r.opt_val, 44, "defaults are transmitted on the wire")

    def testCompoundDefaults(self):
        w = DefaultValues(def_reg=11, req_reg=22)
        r = DefaultValues(def_reg=0, req_reg=33, opt_list_val=[11, 22, 33])
        write_to_read(w, r)
        self.assertEquals(r.opt_list_val, [11, 22, 33],
                          "defaults are transmitted on the wire")

def write_to_read(write_struct, read_struct):
    write_buffer = TMemoryBuffer()
    write_protocol = TBinaryProtocol(write_buffer)
    write_struct.write(write_protocol)

    # The implementation of TMemoryBuffer is slightly different from C++
    # the read/write buffer is not shared, thus we have to create another
    # TMemoryBuffer
    read_buffer = TMemoryBuffer(write_buffer.getvalue())
    read_protocol = TBinaryProtocol(read_buffer)
    read_struct.read(read_protocol)

if __name__ == '__main__':
    unittest.main()
