~smoser/curtin/yakkety.lp1666986

« back to all changes in this revision

Viewing changes to tests/unittests/helpers.py

  • Committer: Ryan Harper
  • Date: 2016-09-29 18:31:02 UTC
  • mto: (58.1.1 pkg)
  • mto: This revision was merged to the branch mainline in revision 59.
  • Revision ID: ryan.harper@canonical.com-20160929183102-qwcn73t5h6o0ag3k
Tags: upstream-0.1.0~bzr425
ImportĀ upstreamĀ versionĀ 0.1.0~bzr425

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#   Copyright (C) 2016 Canonical Ltd.
 
2
#
 
3
#   Author: Scott Moser <scott.moser@canonical.com>
 
4
#
 
5
#   Curtin is free software: you can redistribute it and/or modify it under
 
6
#   the terms of the GNU Affero General Public License as published by the
 
7
#   Free Software Foundation, either version 3 of the License, or (at your
 
8
#   option) any later version.
 
9
#
 
10
#   Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
 
11
#   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 
12
#   FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for
 
13
#   more details.
 
14
#
 
15
#   You should have received a copy of the GNU Affero General Public License
 
16
#   along with Curtin.  If not, see <http://www.gnu.org/licenses/>.
 
17
import mock
 
18
 
 
19
 
 
20
class mocked_open(object):
 
21
    # older versions of mock can't really mock the builtin 'open' easily.
 
22
    def __init__(self):
 
23
        self.mocked = None
 
24
 
 
25
    def __enter__(self):
 
26
        if self.mocked:
 
27
            return self.mocked.start()
 
28
 
 
29
        py2_p = '__builtin__.open'
 
30
        py3_p = 'builtins.open'
 
31
        try:
 
32
            self.mocked = mock.patch(py2_p, new_callable=mock.mock_open())
 
33
            return self.mocked.start()
 
34
        except ImportError:
 
35
            self.mocked = mock.patch(py3_p, new_callable=mock.mock_open())
 
36
            return self.mocked.start()
 
37
 
 
38
    def __exit__(self, etype, value, trace):
 
39
        if self.mocked:
 
40
            self.mocked.stop()
 
41
        self.mocked = None