Search code examples
pythonunit-testingnose

nosetest - run all tests in subdirectories


I am running the nosetest command below but it only runs the tests in the first folder, i have extra tests in subdirectories. How do you edit the command to run all the following tests in all subdirectories of the folder i specified?

nosetests -s -v --ckan --with-pylons=test-core.ini ckan/tests/legacy/*

Here is the basic structure of the tests in the following directory

https://github.com/ckan/ckan/tree/ckan-2.7.3/ckan/tests/legacy


Solution

  • You can write script that do generation of all required paths.

    I use something as:

    #coding: utf-8
    import os
    import logging
    log = logging.getLogger()
    skip_list = []
    
    def get_test_files(cur_path, test_files = []):
        """ Find all files that started with test_ """
        cur_dir_content = os.listdir(cur_path)
        for i in cur_dir_content:
            full_path = os.path.join(cur_path, i)
            if os.path.islink(full_path):
                continue
            if os.path.isfile(full_path) and is_file_test(full_path):
                test_files.append(full_path)
            elif os.path.isdir(full_path):
                get_test_files(full_path, test_files)
        return test_files
    
    def is_file_test(full_path):
        """ Check if file is test"""
        file_name, file_ext = os.path.splitext(os.path.basename(full_path))
        if file_name[:5] == "test_" and file_ext == ".py":
            if is_in_skip(full_path):
                log.info("FILE: %s ... SKIP", full_path)
                return False
            return True
        return False
    
    def is_in_skip(full_path):
        for i in skip_list:
            if full_path.find(i) >= 0:
                return True
        return False
    
    def execute_all_with_nosetests(path_list):
        """ Test with nosetests.
        """
        #compute paths
        cur_dir = os.getcwd()
        paths = map(lambda x: os.path.abspath(x), path_list)
        relpath = "INSERT YOUR PATH"
        paths = map(lambda x: os.path.relpath(x, relpath), paths)
        paths = " ".join(paths)
        os.chdir("INSERT TEST RUN FOLDER")
        cmd = "nosetests -s -v --ckan --with-pylons=test-core.ini " + paths
        os.system(cmd)
        os.chdir(cur_dir)
    
    if __name__ == "__main__":
        test_list = get_test_files("INSERT_BASE_PATH")
        execute_all_with_nosetests(test_list)
    

    Replace strings with "INSERT" to your own folders. Also, correction of execute_all_with_nosetests function is needed. I don't run it, but it is subscript of my test running script.