Ensure that the unit test is validated in an IF. Unit Test

Asked

Viewed 276 times

2

I need to create a unit test that validates the following code. But how can I guarantee that the test validates the downloaded and downloaded content?

if not (os.path.exists(filename)):
    melius.logger.debug('Obter codigo html on-line')
    codigo_html = melius.download(url)

    codigo_html = codigo_html.decode('utf-8')

else:
    melius.logger.debug('Obter codigo html off-line')

    with open(filename) as f:
        codigo_html = f.read()
        melius.logger.debug(f'carregado conteudo do arquivo local "{f.name}"')

melius.logger.debug(f'Download do atos de {ano} finalizado.')

To facilitate say that the codigo_html is the type str and have the text: Janeiro then just one.

self.assertIn(codigo_html, 'Janeiro')

1 answer

1


Usually automated tests (unit/integration) go to the "edge" of your system, and in your example the "edge" of the system is the HTTP request. We limit our tests to the edge because it makes them more deterministic (there is no guarantee that the website you are accessing during the tests really returns that content or that it is in the air), and we can run it even where there is no internet connection or where there is restricted connection.

Your test would look similar to this:

@patch.object(melius, 'download', return_value='dummy content')
@patch.object(os.path, 'exists', return_value=True)
def test_my_function_returns_website_content(os_exists_patch, melius_download_patch):
    # Arrange
    filename = 'somefile.html'
    website_url = 'http://spam.egg'

    # Act
    response_text = my_function(filename, website_url)

    # Assert
    self.assertEqual('dummy_content', response_text)
    self.assertEqual(melius_download_patch.call_args_list, [mock.call(website_url)])
    self.assertEqual(os_exists_patch.call_args_list, [mock.call(filename)])

Regarding the test of else it would be interesting to mock the function open also, and you can do this as described in documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.