[Tutor] How to write tests for main() function that does not return anything

Peter Otten __peter__ at web.de
Wed Feb 3 04:18:13 EST 2016

Pedro Miguel wrote:

> Hi guys, I'm trying to test the code in the main() but I'm a bit unsure
> how to go about it since I'm not passing any arguments or even returning
> anything other then logging. For the purposes of the example I've
> shortened the tree statements in the function.. Can anyone point me in the
> right direction on how to test the logic below? Or perhaps give me an
> example on how to test the code below (that would be really appreciated).
> I've posted this question on Stackoverflow but the guys over there told me
> to mock it but no one provided an example (I'm fairly new on mocking)..and
> how could I mock the if statements or even the for loop? script.py
> from . import settings
> def main():
>     if settings.PATHS:  # list containing full paths to a directory of
>     files
>         paths = settings.PATHS
>         for path in paths:
>             data = read_file(path)
>             modified_data = do_something_with_the_data_collected(data)
>             write_to_new_file(modified_data)
>     else:
>         logger.warning("There are no files in
>         {}".format(settings.FILES_DIRECTORY))
> if __name__ == '__main__':
>     main()
> tests/file_tests.py
> import unittest
> from module.script import main
> class FileManagerTests(unittest.TestCase):
>     def test_main_func(self):
>         main()  # ?? this is where I am stuck, should I just test
>                 # that it logs correctly if certain data exists
>                 # in settings file?
> if __name__ == '__main__':
>     unittest.main()
> RegardsPedro+44(0)7549646235pedro.miguel at live.co.uk

Keep it simple and avoid mocking. Instead set up some test input data and a 
script that compares the actual with the expected output. If in addition you 
refactor the code in main in such a way that the building blocks can easily 
be tested with conventional unit tests you get better coverage for less 

Here's how main() might look after refactoring:

def main():
    if not process_files(settings.PATHS):

def process_files(paths):
    has_files = False
    for path in paths:
        has_files = True  
    return has_files

def process_file(path):

More information about the Tutor mailing list