Update preferred method for reading/writing messages from files

This commit is contained in:
Jason Paryani
2013-09-01 02:13:19 -07:00
parent eb9e7511d0
commit 6fcdf841e4
7 changed files with 103 additions and 124 deletions

View File

@@ -9,7 +9,7 @@ this_dir = os.path.dirname(__file__)
def addressbook():
return capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
def test_addressbook(addressbook):
def test_addressbook_message_classes(addressbook):
def writeAddressBook(fd):
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
@@ -67,6 +67,63 @@ def test_addressbook(addressbook):
f = open('example', 'r')
printAddressBook(f.fileno())
def test_addressbook(addressbook):
def writeAddressBook(file):
addresses = addressbook.AddressBook.newMessage()
people = addresses.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhones = alice.init('phones', 1)
alicePhones[0].number = "555-1212"
alicePhones[0].type = 'mobile'
alice.employment.school = "MIT"
bob = people[1]
bob.id = 456
bob.name = 'Bob'
bob.email = 'bob@example.com'
bobPhones = bob.init('phones', 2)
bobPhones[0].number = "555-4567"
bobPhones[0].type = 'home'
bobPhones[1].number = "555-7654"
bobPhones[1].type = 'work'
bob.employment.unemployed = None
addresses.writeTo(file)
def printAddressBook(file):
addresses = addressbook.AddressBook.readFrom(file)
for person in addresses.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
which = person.employment.which()
print(which)
if which == 'unemployed':
print('unemployed')
elif which == 'employer':
print('employer:', person.employment.employer)
elif which == 'school':
print('student at:', person.employment.school)
elif which == 'selfEmployed':
print('self employed')
print()
f = open('example', 'w')
writeAddressBook(f)
f = open('example', 'r')
printAddressBook(f)
@pytest.fixture
def all_types():
return capnp.load(os.path.join(this_dir, 'all-types.capnp'))