blob: 6db0f38ac7be46c27451c6221b1a186ec0c6f7a4 [file] [log] [blame]
Kuang-che Wu6e4beca2018-06-27 17:45:02 +08001# -*- coding: utf-8 -*-
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08002# Copyright 2017 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5"""Common functions for testing"""
6
7from __future__ import print_function
8import os
Kuang-che Wue2563ea2018-01-05 20:30:28 +08009import contextlib
Kuang-che Wua5723492019-11-25 20:59:34 +080010
11try:
12 from unittest import mock
13except ImportError:
14 # TODO(kcwu): remove once migrated to python3
15 import mock
Kuang-che Wue2563ea2018-01-05 20:30:28 +080016
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080017
18def get_testdata_path(filename=None):
Kuang-che Wue2563ea2018-01-05 20:30:28 +080019 """Gets path to test data
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080020
21 Args:
22 filename: path relative to the test data folder.
23
24 Returns:
25 path to the file inside test data folder. If filename is None, the path of
26 test data folder is returned.
27 """
28 path = os.path.join(os.path.dirname(__file__), '..', 'testdata')
Kuang-che Wue2563ea2018-01-05 20:30:28 +080029 assert os.path.exists(path)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080030 if filename:
31 path = os.path.join(path, filename)
32 return path
Kuang-che Wue2563ea2018-01-05 20:30:28 +080033
34
35@contextlib.contextmanager
36def mock_function_by_file(module, name, filename):
37 """Context manager to mock function by test data
38
39 Args:
40 module: module of function to mock
41 name: function name to mock
42 filename: path relative to the test data folder
43
44 Returns:
45 context manager, which mocks the said function within its scope.
46 """
Kuang-che Wua5723492019-11-25 20:59:34 +080047 with open(get_testdata_path(filename)) as f:
48 data = f.read()
Kuang-che Wue2563ea2018-01-05 20:30:28 +080049 with mock.patch.object(module, name, return_value=data):
50 yield