• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#
2# Copyright 2015 Google Inc.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Various utilities used in tests."""
17
18import contextlib
19import os
20import tempfile
21import shutil
22import sys
23
24import six
25import unittest2
26
27
28RunOnlyOnPython27 = unittest2.skipUnless(
29    sys.version_info[:2] == (2, 7), 'Only runs in Python 2.7')
30
31SkipOnWindows = unittest2.skipIf(
32    os.name == 'nt', 'Does not run on windows')
33
34
35@contextlib.contextmanager
36def TempDir(change_to=False):
37    if change_to:
38        original_dir = os.getcwd()
39    path = tempfile.mkdtemp()
40    try:
41        if change_to:
42            os.chdir(path)
43        yield path
44    finally:
45        if change_to:
46            os.chdir(original_dir)
47        shutil.rmtree(path)
48
49
50@contextlib.contextmanager
51def CaptureOutput():
52    new_stdout, new_stderr = six.StringIO(), six.StringIO()
53    old_stdout, old_stderr = sys.stdout, sys.stderr
54    try:
55        sys.stdout, sys.stderr = new_stdout, new_stderr
56        yield new_stdout, new_stderr
57    finally:
58        sys.stdout, sys.stderr = old_stdout, old_stderr
59