Python: unittest.mock

0

Hello everyone, good afternoon.

Require once again the wisdom and experience of the community! : D

I have the following code:

def save_html_file(conteudo, filename, encoding='iso8859-1'):
    assert isinstance(conteudo, str), '"conteudo" deve ser um código HTML do tipo "str"'
    if '~' in filename:
        filename = os.path.join(os.path.join(os.path.commonpath(os.get_exec_path()), *filename.split(os.sep)))
    elif os.sep in filename:
        filename = os.path.abspath(os.path.join(os.path.abspath(os.sep), *filename.split(os.sep)))
    else:
        filename = os.path.abspath(os.getcwd(), filename)

    soup = BeautifulSoup(conteudo, 'html5lib')
    output_path = os.path.dirname(filename)
    logging.debug(f'Verificado "{os.path.dirname(filename)}"')
    os.makedirs(output_path, 0o777, True)
    with open(filename, 'wb') as file_out:
        file_out.write(soup.prettify(encoding=encoding))
    logging.debug(F'Arquivo "{filename}" gravado.')
    return True

I want to test it with mock by isolating it from the operating system. So I can test it without creating multiple files.

I created this test below, though it is inefficient.

    @patch('legis.os.makedirs')
    @patch('legis.save_html_file')
    def test_save_html_file(self, m_save_html_file, m_os_makedirs):
        with patch('__main__.open', mock_open()) as mock_system:
            m_save_html_file(self.soup2.prettify(), '/tmp/teste/arquivos/file.html')
            self.assertTrue(m_os_makedirs.assert_called)
            m_save_html_file.assert_called_once_with(self.soup2.prettify(), '/tmp/teste/arquivos/file.html')
            self.assertTrue(m_save_html_file.called)
            m_os_makedirs('/tmp/teste/arquivos')
            # print(m_os_makedirs.call_args_list)
            print(mock_system.mock_calls)
            m_save_html_file('file.html')

            print(mock_system.call_args_list)
            print(mock_system.mock_calls)
            m_save_html_file('~/file.html')

I need to test the creation, writing, and content of the following documents:

  • save_html_file ('/ tmp / file.txt')
  • save_html_file ('/ tmp / test / file.txt')
  • save_html_file ('~ / tmp / file.txt')
  • save_html_file ('~ / / file.txt')
  • save_html_file ('file.txt')

I count on your help once again! Thank you in advance.

    
asked by anonymous 25.10.2018 / 21:36

0 answers