dimanche 6 septembre 2015

Test the real function or mock the dependency for unittest?

Given the function below:

def _extract_row(self, rnumber, rcontent):
    number = rnumber.find('p').text.strip()
    p = rcontent.find('p')
    dloms = p.find_all('a')

    docs = {}
    for d in dloms:
        docs[d.text.strip()] = DOMAIN + d['href']

    ems = p.find_all('em')
    for e in ems:
        name = e.text.strip()
        if not docs.get(name):
            docs[name] = None

    ldocs = []
    for name, link in docs.iteritems():
        ldocs.append({'name': name,
                      'link': link})

    return {'number': number,
            'docs': ldocs}

where rnumber and rcontent are BS4 or Beautifulsoup objects, is it better to install BS4 as a test dependency and test the function normally or is it better to mock BS4 ?

Here is what I did:

@patch("agc_law.bs4.BeautifulSoup")
def test_law_pages_private_extract_row(self, mock_bs4):

    """Test asserting correct calls are made in _extract_row"""

    agc_law.DOMAIN = "http://example.com"
    mock_rnumber = mock_bs4
    mock_rcontent = mock_bs4

    result = self.lp._extract_row(mock_rnumber, mock_rcontent)
    for item in [call.find('p'),
                 call.find().text.strip(),
                 call.find('p'),
                 call.find().find_all('a'),
                 call.find().find_all('em')]:
        self.assertIn(item, mock_rcontent.mock_calls)

    for item in [call.find('p'),
                 call.find().text.strip(),
                 call.find('p'),
                 call.find().find_all('a'),
                 call.find().find_all('em')]:
        self.assertIn(item, mock_rnumber.mock_calls)

Would value comments.

Aucun commentaire:

Enregistrer un commentaire