1

If I have a function like this:

def get_vcard():
    new_vcard = vobject.vCard()
    new_vcard.add('fn')
    new_card.fn.value = 'First Last'
    work_phone = new_vcard.add('tel')
    work_phone.value = '+18005555555'
    mobile_phone = new_vcard.add('tel')
    mobile_phone.value = '+18885555555'

And a test like this:

@patch('myapp.vobject.vCard', autospec=True)
def test_create_card(self, mock_vcard_constructor):
    mock_vcard = mock_vcard_constructor.return_value
    myapp.get_vcard()
    self.assertEqual('First Last', mock_vcard.fn.value)

I want to also reference those different phone number objects so I can check that they are set correctly as well. I'm not sure how I can get a reference to them.

Tamerz
  • 897
  • 1
  • 10
  • 25
  • This test makes no sense. You don't call any of the actual code, all you do is assert your mock has a value (which it won't). – Daniel Roseman Sep 03 '18 at 09:54
  • Sorry, this was just a small bit of the actual code. In reality, it is not just a function, but a method of a much larger class. I didn't think all the code was necessary. I'll edit the original. – Tamerz Sep 03 '18 at 09:58

1 Answers1

0

You can access all children of the vCard with .getChildren() For example:

def get_vcard(new_vcard=vobject.vCard()):
    new_vcard.add('fn')
    new_vcard.fn.value = 'First Last'
    work_phone = new_vcard.add('tel')
    work_phone.value = '+18005555555'
    mobile_phone = new_vcard.add('tel')
    mobile_phone.value = '+18885555555'

    return new_vcard

Now your unit test would look like:

def has_phone(vcard, value):
    for child in vcard.getChildren():
        if child.value == value:
            return True
    return False

@patch('myapp.vobject.vCard', autospec=True)
def test_create_card(self, mock_vcard_constructor):
    mock_vcard = get_vcard()

    self.assertEqual('First Last', mock_vcard.fn.value)
    self.assertTrue(has_phone(mock_vcard, '+18005555555'))
    self.assertTrue(has_phone(mock_vcard, '+18885555555'))

Another possibility is accessing all the phone numbers with vcard.contents['tel'] and then interating over them.

kalehmann
  • 4,821
  • 6
  • 26
  • 36