1# Copyright (C) 2016 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15'''This file contains utility functions used by both the test suite and the
16single test executor.'''
17
18from __future__ import absolute_import
19
20import os
21import importlib
22import sys
23
24
25def load_py_module(path):
26    '''Load a python file from disk.
27
28    Args:
29        path: String path to python file.
30
31    Returns:
32        python module if success, None otherwise.
33    '''
34    assert isinstance(path, str)
35    try:
36        if not os.path.exists(path):
37            print('Path does not exist: ' + path)
38            return None
39        path = os.path.abspath(path)
40        module_dir, module_file = os.path.split(path)
41        module_name, _ = os.path.splitext(module_file)
42        # adjust sys.path, runtime counterpart of PYTHONPATH, to temporarily
43        # include the folder containing the user configuration module
44        sys.path.append(module_dir)
45        module_obj = importlib.import_module(module_name)
46        sys.path.pop(0)
47        return module_obj
48    except ImportError as err:
49        print(str(err))
50        print("Looking in directory ")
51        print(module_dir)
52        return None
53