Kuang-che Wu | 2ea804f | 2017-11-28 17:11:41 +0800 | [diff] [blame] | 1 | # Copyright 2017 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | """Common functions for testing""" |
| 5 | |
| 6 | from __future__ import print_function |
| 7 | import os |
| 8 | |
Kuang-che Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 9 | import contextlib |
| 10 | import mock |
| 11 | |
Kuang-che Wu | 2ea804f | 2017-11-28 17:11:41 +0800 | [diff] [blame] | 12 | |
| 13 | def get_testdata_path(filename=None): |
Kuang-che Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 14 | """Gets path to test data |
Kuang-che Wu | 2ea804f | 2017-11-28 17:11:41 +0800 | [diff] [blame] | 15 | |
| 16 | Args: |
| 17 | filename: path relative to the test data folder. |
| 18 | |
| 19 | Returns: |
| 20 | path to the file inside test data folder. If filename is None, the path of |
| 21 | test data folder is returned. |
| 22 | """ |
| 23 | path = os.path.join(os.path.dirname(__file__), '..', 'testdata') |
Kuang-che Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 24 | assert os.path.exists(path) |
Kuang-che Wu | 2ea804f | 2017-11-28 17:11:41 +0800 | [diff] [blame] | 25 | if filename: |
| 26 | path = os.path.join(path, filename) |
| 27 | return path |
Kuang-che Wu | e2563ea | 2018-01-05 20:30:28 +0800 | [diff] [blame] | 28 | |
| 29 | |
| 30 | @contextlib.contextmanager |
| 31 | def mock_function_by_file(module, name, filename): |
| 32 | """Context manager to mock function by test data |
| 33 | |
| 34 | Args: |
| 35 | module: module of function to mock |
| 36 | name: function name to mock |
| 37 | filename: path relative to the test data folder |
| 38 | |
| 39 | Returns: |
| 40 | context manager, which mocks the said function within its scope. |
| 41 | """ |
| 42 | data = open(get_testdata_path(filename)).read() |
| 43 | with mock.patch.object(module, name, return_value=data): |
| 44 | yield |