1#
2# Copyright (c) 2009 Testrepository Contributors
3#
4# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
5# license at the users choice. A copy of both licenses are available in the
6# project source as Apache-2.0 and BSD. You may not use this file except in
7# compliance with one of these two licences.
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
12# license you chose for the specific language governing permissions and
13# limitations under that license.
14
15"""Monkeypatch helper function for tests.
16
17This has been moved to fixtures, and should be removed from here.
18"""
19
20def monkeypatch(name, new_value):
21    """Replace name with new_value.
22
23    :return: A callable which will restore the original value.
24    """
25    location, attribute = name.rsplit('.', 1)
26    # Import, swallowing all errors as any element of location may be
27    # a class or some such thing.
28    try:
29        __import__(location, {}, {})
30    except ImportError:
31        pass
32    components = location.split('.')
33    current = __import__(components[0], {}, {})
34    for component in components[1:]:
35        current = getattr(current, component)
36    old_value = getattr(current, attribute)
37    setattr(current, attribute, new_value)
38    def restore():
39        setattr(current, attribute, old_value)
40    return restore
41