Home | History | Annotate | Download | only in server2
      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 
      5 from __future__ import print_function
      6 
      7 from extensions_paths import SERVER2
      8 import logging
      9 import os
     10 import sys
     11 
     12 
     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)
     21 
     22   cf = Capture()
     23   logging.getLogger('').addFilter(cf)
     24   f()
     25   logging.getLogger('').removeFilter(cf)
     26 
     27   return output
     28 
     29 
     30 def EnableLogging(name):
     31   '''Returns the output of the log with |name| to stdout.
     32   '''
     33 
     34   return _ReplaceLogging(name, lambda message, *args: print(message % args))
     35 
     36 
     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)
     41 
     42 
     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
     54 
     55 
     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 '')
     61 
     62 
     63 def Server2Path(*path):
     64   return ChromiumPath(SERVER2, *path)
     65 
     66 
     67 def ReadFile(*path, **read_args):
     68   with open(ChromiumPath(*path), **read_args) as f:
     69     return f.read()
     70