blob: 7f9a968b79d3e56d99f97359caf9663253371528 [file] [log] [blame]
C.J. Collier37141e42020-02-13 13:49:49 -08001# Copyright 2016 Google LLC
Jon Wayne Parrotta896d2a2016-11-02 23:42:51 -07002#
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
15import sys
16
17import mock
18import pytest
19
20
21@pytest.fixture
22def mock_non_existent_module(monkeypatch):
23 """Mocks a non-existing module in sys.modules.
24
25 Additionally mocks any non-existing modules specified in the dotted path.
26 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -070027
Jon Wayne Parrotta896d2a2016-11-02 23:42:51 -070028 def _mock_non_existent_module(path):
Bu Sun Kim9eec0912019-10-21 17:04:21 -070029 parts = path.split(".")
Jon Wayne Parrotta896d2a2016-11-02 23:42:51 -070030 partial = []
31 for part in parts:
32 partial.append(part)
Bu Sun Kim9eec0912019-10-21 17:04:21 -070033 current_module = ".".join(partial)
Jon Wayne Parrotta896d2a2016-11-02 23:42:51 -070034 if current_module not in sys.modules:
Bu Sun Kim9eec0912019-10-21 17:04:21 -070035 monkeypatch.setitem(sys.modules, current_module, mock.MagicMock())
Jon Wayne Parrotta896d2a2016-11-02 23:42:51 -070036
37 return _mock_non_existent_module