blob: 0a1ac3ed49b7ac3c7ba73e2c37f0911e58a5ee63 [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
9
Kuang-che Wue2563ea2018-01-05 20:30:28 +080010import contextlib
11import mock
12
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080013
14def get_testdata_path(filename=None):
Kuang-che Wue2563ea2018-01-05 20:30:28 +080015 """Gets path to test data
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080016
17 Args:
18 filename: path relative to the test data folder.
19
20 Returns:
21 path to the file inside test data folder. If filename is None, the path of
22 test data folder is returned.
23 """
24 path = os.path.join(os.path.dirname(__file__), '..', 'testdata')
Kuang-che Wue2563ea2018-01-05 20:30:28 +080025 assert os.path.exists(path)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080026 if filename:
27 path = os.path.join(path, filename)
28 return path
Kuang-che Wue2563ea2018-01-05 20:30:28 +080029
30
31@contextlib.contextmanager
32def mock_function_by_file(module, name, filename):
33 """Context manager to mock function by test data
34
35 Args:
36 module: module of function to mock
37 name: function name to mock
38 filename: path relative to the test data folder
39
40 Returns:
41 context manager, which mocks the said function within its scope.
42 """
43 data = open(get_testdata_path(filename)).read()
44 with mock.patch.object(module, name, return_value=data):
45 yield