test_util.py revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
1# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5from __future__ import print_function
6
7import logging
8import os
9import sys
10
11def EnableLogging(name):
12  '''Returns the output of the log with |name| to stdout.
13  '''
14  return _ReplaceLogging(name, lambda message: print(message))
15
16def DisableLogging(name):
17  '''Disables the log with |name| for the duration of the decorated function.
18  '''
19  return _ReplaceLogging(name, lambda _: None)
20
21def _ReplaceLogging(name, replacement):
22  def decorator(fn):
23    def impl(*args, **optargs):
24      saved = getattr(logging, name)
25      setattr(logging, name, replacement)
26      try:
27        return fn(*args, **optargs)
28      finally:
29        setattr(logging, name, saved)
30    return impl
31  return decorator
32
33# TODO(kalman): Use this everywhere. A lot of tests are doing this.
34def ReadFile(name):
35  with open(os.path.join(sys.path[0], os.pardir, os.pardir, name)) as f:
36    return f.read()
37