Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / common / extensions / docs / server2 / test_util.py
blobfb70eae439fd783ec21f8a18b1d9886da76ca744
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.
5 from __future__ import print_function
7 from extensions_paths import SERVER2
8 import logging
9 import os
10 import sys
13 def CaptureLogging(f):
14 '''Call the function |f|, capturing any logging output generated. |f| must
15 take no arguments. Returns a list of LogRecords that were emitted.
16 '''
17 output = []
18 class Capture(object):
19 def filter(self, record):
20 output.append(record)
22 cf = Capture()
23 logging.getLogger('').addFilter(cf)
24 f()
25 logging.getLogger('').removeFilter(cf)
27 return output
30 def EnableLogging(name):
31 '''Returns the output of the log with |name| to stdout.
32 '''
34 return _ReplaceLogging(name, lambda message, *args: print(message % args))
37 def DisableLogging(name):
38 '''Disables the log with |name| for the duration of the decorated function.
39 '''
40 return _ReplaceLogging(name, lambda _, *args: None)
43 def _ReplaceLogging(name, replacement):
44 def decorator(fn):
45 def impl(*args, **optargs):
46 saved = getattr(logging, name)
47 setattr(logging, name, replacement)
48 try:
49 return fn(*args, **optargs)
50 finally:
51 setattr(logging, name, saved)
52 return impl
53 return decorator
56 def ChromiumPath(*path):
57 abspath = os.path.join(
58 sys.path[0], '..', '..', '..', '..', '..', *path)
59 # os.path.relpath kills any trailing '/'.
60 return os.path.relpath(abspath) + ('/' if abspath.endswith('/') else '')
63 def Server2Path(*path):
64 return ChromiumPath(SERVER2, *path)
67 def ReadFile(*path, **read_args):
68 with open(ChromiumPath(*path), **read_args) as f:
69 return f.read()