|
| 1 | +'''This file is recognized by pytest for defining specified behaviour |
| 2 | +
|
| 3 | +'conftest.py' files are directory-scope files that are shared by all |
| 4 | +sub-directories from where this file is placed. pytest recognises |
| 5 | +'conftest.py' for any unit test executed from within this directory |
| 6 | +tree. This file is used to define fixtures, hooks, plugins, and other |
| 7 | +functionality that can be shared by the unit tests. |
| 8 | +
|
| 9 | +This file has been created for the OpenML testing to primarily make use |
| 10 | +of the pytest hooks 'pytest_sessionstart' and 'pytest_sessionfinish', |
| 11 | +which are being used for managing the deletion of local and remote files |
| 12 | +created by the unit tests, run across more than one process. |
| 13 | +
|
| 14 | +This design allows one to comment or remove the conftest.py file to |
| 15 | +disable file deletions, without editing any of the test case files. |
| 16 | +
|
| 17 | +
|
| 18 | +Possible Future: class TestBase from openml/testing.py can be included |
| 19 | + under this file and there would not be any requirements to import |
| 20 | + testing.py in each of the unit test modules. |
| 21 | +''' |
| 22 | + |
| 23 | +import os |
| 24 | +import logging |
| 25 | +from typing import List |
| 26 | + |
| 27 | +import openml |
| 28 | +from openml.testing import TestBase |
| 29 | + |
| 30 | +# creating logger for unit test file deletion status |
| 31 | +logger = logging.getLogger("unit_tests") |
| 32 | +logger.setLevel(logging.DEBUG) |
| 33 | + |
| 34 | +file_list = [] |
| 35 | +directory = None |
| 36 | + |
| 37 | +# finding the root directory of conftest.py and going up to OpenML main directory |
| 38 | +# exploiting the fact that conftest.py always resides in the root directory for tests |
| 39 | +static_dir = os.path.dirname(os.path.abspath(__file__)) |
| 40 | +logging.info("static directory: {}".format(static_dir)) |
| 41 | +print("static directory: {}".format(static_dir)) |
| 42 | +while True: |
| 43 | + if 'openml' in os.listdir(static_dir): |
| 44 | + break |
| 45 | + static_dir = os.path.join(static_dir, '..') |
| 46 | + |
| 47 | + |
| 48 | +def worker_id() -> str: |
| 49 | + ''' Returns the name of the worker process owning this function call. |
| 50 | +
|
| 51 | + :return: str |
| 52 | + Possible outputs from the set of {'master', 'gw0', 'gw1', ..., 'gw(n-1)'} |
| 53 | + where n is the number of workers being used by pytest-xdist |
| 54 | + ''' |
| 55 | + vars_ = list(os.environ.keys()) |
| 56 | + if 'PYTEST_XDIST_WORKER' in vars_ or 'PYTEST_XDIST_WORKER_COUNT' in vars_: |
| 57 | + return os.environ['PYTEST_XDIST_WORKER'] |
| 58 | + else: |
| 59 | + return 'master' |
| 60 | + |
| 61 | + |
| 62 | +def read_file_list() -> List[str]: |
| 63 | + '''Returns a list of paths to all files that currently exist in 'openml/tests/files/' |
| 64 | +
|
| 65 | + :return: List[str] |
| 66 | + ''' |
| 67 | + directory = os.path.join(static_dir, 'tests/files/') |
| 68 | + if worker_id() == 'master': |
| 69 | + logger.info("Collecting file lists from: {}".format(directory)) |
| 70 | + files = os.walk(directory) |
| 71 | + file_list = [] |
| 72 | + for root, _, filenames in files: |
| 73 | + for filename in filenames: |
| 74 | + file_list.append(os.path.join(root, filename)) |
| 75 | + return file_list |
| 76 | + |
| 77 | + |
| 78 | +def compare_delete_files(old_list, new_list) -> None: |
| 79 | + '''Deletes files that are there in the new_list but not in the old_list |
| 80 | +
|
| 81 | + :param old_list: List[str] |
| 82 | + :param new_list: List[str] |
| 83 | + :return: None |
| 84 | + ''' |
| 85 | + file_list = list(set(new_list) - set(old_list)) |
| 86 | + for file in file_list: |
| 87 | + os.remove(file) |
| 88 | + logger.info("Deleted from local: {}".format(file)) |
| 89 | + |
| 90 | + |
| 91 | +def delete_remote_files(tracker) -> None: |
| 92 | + '''Function that deletes the entities passed as input, from the OpenML test server |
| 93 | +
|
| 94 | + The TestBase class in openml/testing.py has an attribute called publish_tracker. |
| 95 | + This function expects the dictionary of the same structure. |
| 96 | + It is a dictionary of lists, where the keys are entity types, while the values are |
| 97 | + lists of integer IDs, except for key 'flow' where the value is a tuple (ID, flow name). |
| 98 | +
|
| 99 | + Iteratively, multiple POST requests are made to the OpenML test server using |
| 100 | + openml.utils._delete_entity() to remove the entities uploaded by all the unit tests. |
| 101 | +
|
| 102 | + :param tracker: Dict |
| 103 | + :return: None |
| 104 | + ''' |
| 105 | + openml.config.server = TestBase.test_server |
| 106 | + openml.config.apikey = TestBase.apikey |
| 107 | + |
| 108 | + # reordering to delete sub flows at the end of flows |
| 109 | + # sub-flows have shorter names, hence, sorting by descending order of flow name length |
| 110 | + if 'flow' in tracker: |
| 111 | + flow_deletion_order = [entity_id for entity_id, _ in |
| 112 | + sorted(tracker['flow'], key=lambda x: len(x[1]), reverse=True)] |
| 113 | + tracker['flow'] = flow_deletion_order |
| 114 | + |
| 115 | + # deleting all collected entities published to test server |
| 116 | + # 'run's are deleted first to prevent dependency issue of entities on deletion |
| 117 | + logger.info("Entity Types: {}".format(['run', 'data', 'flow', 'task', 'study'])) |
| 118 | + for entity_type in ['run', 'data', 'flow', 'task', 'study']: |
| 119 | + logger.info("Deleting {}s...".format(entity_type)) |
| 120 | + for i, entity in enumerate(tracker[entity_type]): |
| 121 | + try: |
| 122 | + openml.utils._delete_entity(entity_type, entity) |
| 123 | + logger.info("Deleted ({}, {})".format(entity_type, entity)) |
| 124 | + except Exception as e: |
| 125 | + logger.warn("Cannot delete ({},{}): {}".format(entity_type, entity, e)) |
| 126 | + |
| 127 | + |
| 128 | +def pytest_sessionstart() -> None: |
| 129 | + '''pytest hook that is executed before any unit test starts |
| 130 | +
|
| 131 | + This function will be called by each of the worker processes, along with the master process |
| 132 | + when they are spawned. This happens even before the collection of unit tests. |
| 133 | + If number of workers, n=4, there will be a total of 5 (1 master + 4 workers) calls of this |
| 134 | + function, before execution of any unit test begins. The master pytest process has the name |
| 135 | + 'master' while the worker processes are named as 'gw{i}' where i = 0, 1, ..., n-1. |
| 136 | + The order of process spawning is: 'master' -> random ordering of the 'gw{i}' workers. |
| 137 | +
|
| 138 | + Since, master is always executed first, it is checked if the current process is 'master' and |
| 139 | + store a list of strings of paths of all files in the directory (pre-unit test snapshot). |
| 140 | +
|
| 141 | + :return: None |
| 142 | + ''' |
| 143 | + # file_list is global to maintain the directory snapshot during tear down |
| 144 | + global file_list |
| 145 | + worker = worker_id() |
| 146 | + if worker == 'master': |
| 147 | + file_list = read_file_list() |
| 148 | + |
| 149 | + |
| 150 | +def pytest_sessionfinish() -> None: |
| 151 | + '''pytest hook that is executed after all unit tests of a worker ends |
| 152 | +
|
| 153 | + This function will be called by each of the worker processes, along with the master process |
| 154 | + when they are done with the unit tests allocated to them. |
| 155 | + If number of workers, n=4, there will be a total of 5 (1 master + 4 workers) calls of this |
| 156 | + function, before execution of any unit test begins. The master pytest process has the name |
| 157 | + 'master' while the worker processes are named as 'gw{i}' where i = 0, 1, ..., n-1. |
| 158 | + The order of invocation is: random ordering of the 'gw{i}' workers -> 'master'. |
| 159 | +
|
| 160 | + Since, master is always executed last, it is checked if the current process is 'master' and, |
| 161 | + * Compares file list with pre-unit test snapshot and deletes all local files generated |
| 162 | + * Iterates over the list of entities uploaded to test server and deletes them remotely |
| 163 | +
|
| 164 | + :return: None |
| 165 | + ''' |
| 166 | + # allows access to the file_list read in the set up phase |
| 167 | + global file_list |
| 168 | + worker = worker_id() |
| 169 | + logger.info("Finishing worker {}".format(worker)) |
| 170 | + |
| 171 | + # Test file deletion |
| 172 | + logger.info("Deleting files uploaded to test server for worker {}".format(worker)) |
| 173 | + delete_remote_files(TestBase.publish_tracker) |
| 174 | + |
| 175 | + if worker == 'master': |
| 176 | + # Local file deletion |
| 177 | + new_file_list = read_file_list() |
| 178 | + compare_delete_files(file_list, new_file_list) |
| 179 | + logger.info("Local files deleted") |
| 180 | + |
| 181 | + logging.info("{} is killed".format(worker)) |
0 commit comments