# Path: _stbt/imgproc_cache.py
# MAX_CACHE_SIZE_BYTES = 1024 * 1024 * 1024  # 1GiB
# def setup_cache(filename=None):
# def enable_caching(enable=True):
# def memoize(additional_fields=None):
#     def decorator(f):
#         def inner(*args, **kwargs):
# def memoize_iterator(additional_fields=None):
#     def decorator(f):
#         def inner(*args, **kwargs):
# def _cache_put(key, value):
#     def default(self, o):  # pylint:disable=method-hidden
# def _cache_hash(value):
#         def write(self, data):
# def test_that_cache_is_disabled_when_debug_match():
# def _fields_eq(a, b, fields):
# def _check_cache_behaviour(func):
# def test_memoize_iterator():
#     def cached_function(_arg):
# def test_memoize_iterator_on_empty_iterator():
#     def cached_function():
# def test_that_cache_speeds_up_match():
#     def match():
# def test_that_cache_speeds_up_match_all():
#     def match_all():
# def test_that_cache_speeds_up_ocr():
#     def ocr():
# def test_that_cache_speeds_up_match_text():
#     def match_text():
# class NotCachable(Exception):
# class _ArgsEncoder(json.JSONEncoder):
#     class HashWriter():
# 
# Path: _stbt/logging.py
# def debug(msg):
#     """Print the given string to stderr if stbt run `--verbose` was given."""
#     if get_debug_level() > 0:
#         sys.stderr.write("%s\n" % (msg,))
# 
# Path: _stbt/stbt_run.py
# def load_test_function(script, args):
#     sys.argv = [script] + args
#     if '::' in script:
#         filename, funcname = script.split('::', 1)
#         mod = _import_by_filename(filename)
#         func = getattr(mod, funcname)
#         return _TestFunction(
#             script, filename, funcname, func.__code__.co_firstlineno,
#             func)
#     else:
#         filename = os.path.abspath(script)
# 
#         test_globals = {
#             '__builtins__': __builtins__,
#             '__name__': '__main__',
#             '__file__': script,
#             '__doc__': None,
#             '__package__': None,
#         }
# 
#         def fn():
#             sys.path.insert(0, os.path.dirname(filename))
#             code = compile(open(filename, "rb").read(),
#                            filename,
#                            mode="exec",
#                            # Don't apply the __future__ imports in force in
#                            # this file.
#                            dont_inherit=1)
#             exec(code, test_globals)  # pylint:disable=exec-used
# 
#         return _TestFunction(script, script, "", 1, fn)
# 
# @contextmanager
# def sane_unicode_and_exception_handling(script):
#     try:
#         yield
#     except Exception as e:  # pylint:disable=broad-except
#         error_message = str(e)
#         if not error_message and isinstance(e, AssertionError):
#             error_message = traceback.extract_tb(sys.exc_info()[2])[-1][3]
#         sys.stdout.write("FAIL: %s: %s: %s\n" % (
#             script, type(e).__name__, error_message))
#         traceback.print_exc(file=sys.stderr)
#         if isinstance(e, (UITestFailure, AssertionError)):
#             sys.exit(1)  # Failure
#         else:
#             sys.exit(2)  # Error
# 
# @contextmanager
# def video(args, dut):
#     result_dir = os.path.abspath(os.curdir)
#     with _set_dut_singleton(dut), dut:
#         try:
#             yield
#         except Exception as e:
#             try:
#                 _save_screenshot(dut, result_dir, exception=e,
#                                  save_jpg=(args.save_thumbnail != 'never'),
#                                  save_png=(args.save_screenshot != 'never'))
#             except Exception:  # pylint: disable=broad-except
#                 pass
#             raise
#         else:
#             _save_screenshot(dut, result_dir, exception=None,
#                              save_jpg=(args.save_thumbnail == 'always'),
#                              save_png=(args.save_screenshot == 'always'))


import argparse
import sys
import _stbt.core
from _stbt import imgproc_cache
from _stbt.logging import debug
from _stbt.stbt_run import (load_test_function,
                            sane_unicode_and_exception_handling, video)
    parser = _stbt.core.argparser()
    parser.prog = 'stbt run'
    parser.description = 'Run an stb-tester test script'
    parser.add_argument(
        '--cache', default=imgproc_cache.default_filename,
        help="Path for image-processing cache (default: %(default)s")
    parser.add_argument(
        '--save-screenshot', default='on-failure',
        choices=['always', 'on-failure', 'never'],
        help="Save a screenshot at the end of the test to screenshot.png")
    parser.add_argument(
        '--save-thumbnail', default='never',
        choices=['always', 'on-failure', 'never'],
        help="Save a thumbnail at the end of the test to thumbnail.jpg")
    parser.add_argument(
        'script', metavar='FILE[::TESTCASE]', help=(
            "The python test script to run. Optionally specify a python "
            "function name to run that function; otherwise only the script's "
            "top-level will be executed."))
    parser.add_argument(
        'args', nargs=argparse.REMAINDER, metavar='ARG',
        help='Additional arguments passed on to the test script (in sys.argv)')

    args = parser.parse_args(argv[1:])
    debug("Arguments:\n" + "\n".join([
        "%s: %s" % (k, v) for k, v in args.__dict__.items()]))

    dut = _stbt.core.new_device_under_test_from_config(args)
    with sane_unicode_and_exception_handling(args.script), \
            video(args, dut), \

# Path: _stbt/imgproc_cache.py
# MAX_CACHE_SIZE_BYTES = 1024 * 1024 * 1024  # 1GiB
# def setup_cache(filename=None):
# def enable_caching(enable=True):
# def memoize(additional_fields=None):
#     def decorator(f):
#         def inner(*args, **kwargs):
# def memoize_iterator(additional_fields=None):
#     def decorator(f):
#         def inner(*args, **kwargs):
# def _cache_put(key, value):
#     def default(self, o):  # pylint:disable=method-hidden
# def _cache_hash(value):
#         def write(self, data):
# def test_that_cache_is_disabled_when_debug_match():
# def _fields_eq(a, b, fields):
# def _check_cache_behaviour(func):
# def test_memoize_iterator():
#     def cached_function(_arg):
# def test_memoize_iterator_on_empty_iterator():
#     def cached_function():
# def test_that_cache_speeds_up_match():
#     def match():
# def test_that_cache_speeds_up_match_all():
#     def match_all():
# def test_that_cache_speeds_up_ocr():
#     def ocr():
# def test_that_cache_speeds_up_match_text():
#     def match_text():
# class NotCachable(Exception):
# class _ArgsEncoder(json.JSONEncoder):
#     class HashWriter():
# 
# Path: _stbt/logging.py
# def debug(msg):
#     """Print the given string to stderr if stbt run `--verbose` was given."""
#     if get_debug_level() > 0:
#         sys.stderr.write("%s\n" % (msg,))
# 
# Path: _stbt/stbt_run.py
# def load_test_function(script, args):
#     sys.argv = [script] + args
#     if '::' in script:
#         filename, funcname = script.split('::', 1)
#         mod = _import_by_filename(filename)
#         func = getattr(mod, funcname)
#         return _TestFunction(
#             script, filename, funcname, func.__code__.co_firstlineno,
#             func)
#     else:
#         filename = os.path.abspath(script)
# 
#         test_globals = {
#             '__builtins__': __builtins__,
#             '__name__': '__main__',
#             '__file__': script,
#             '__doc__': None,
#             '__package__': None,
#         }
# 
#         def fn():
#             sys.path.insert(0, os.path.dirname(filename))
#             code = compile(open(filename, "rb").read(),
#                            filename,
#                            mode="exec",
#                            # Don't apply the __future__ imports in force in
#                            # this file.
#                            dont_inherit=1)
#             exec(code, test_globals)  # pylint:disable=exec-used
# 
#         return _TestFunction(script, script, "", 1, fn)
# 
# @contextmanager
# def sane_unicode_and_exception_handling(script):
#     try:
#         yield
#     except Exception as e:  # pylint:disable=broad-except
#         error_message = str(e)
#         if not error_message and isinstance(e, AssertionError):
#             error_message = traceback.extract_tb(sys.exc_info()[2])[-1][3]
#         sys.stdout.write("FAIL: %s: %s: %s\n" % (
#             script, type(e).__name__, error_message))
#         traceback.print_exc(file=sys.stderr)
#         if isinstance(e, (UITestFailure, AssertionError)):
#             sys.exit(1)  # Failure
#         else:
#             sys.exit(2)  # Error
# 
# @contextmanager
# def video(args, dut):
#     result_dir = os.path.abspath(os.curdir)
#     with _set_dut_singleton(dut), dut:
#         try:
#             yield
#         except Exception as e:
#             try:
#                 _save_screenshot(dut, result_dir, exception=e,
#                                  save_jpg=(args.save_thumbnail != 'never'),
#                                  save_png=(args.save_screenshot != 'never'))
#             except Exception:  # pylint: disable=broad-except
#                 pass
#             raise
#         else:
#             _save_screenshot(dut, result_dir, exception=None,
#                              save_jpg=(args.save_thumbnail == 'always'),
#                              save_png=(args.save_screenshot == 'always'))


# Path: stbt_run.py
import argparse
import sys
import _stbt.core
from _stbt import imgproc_cache
from _stbt.logging import debug
from _stbt.stbt_run import (load_test_function,
                            sane_unicode_and_exception_handling, video)

    parser = _stbt.core.argparser()
    parser.prog = 'stbt run'
    parser.description = 'Run an stb-tester test script'
    parser.add_argument(
        '--cache', default=imgproc_cache.default_filename,
        help="Path for image-processing cache (default: %(default)s")
    parser.add_argument(
        '--save-screenshot', default='on-failure',
        choices=['always', 'on-failure', 'never'],
        help="Save a screenshot at the end of the test to screenshot.png")
    parser.add_argument(
        '--save-thumbnail', default='never',
        choices=['always', 'on-failure', 'never'],
        help="Save a thumbnail at the end of the test to thumbnail.jpg")
    parser.add_argument(
        'script', metavar='FILE[::TESTCASE]', help=(
            "The python test script to run. Optionally specify a python "
            "function name to run that function; otherwise only the script's "
            "top-level will be executed."))
    parser.add_argument(
        'args', nargs=argparse.REMAINDER, metavar='ARG',
        help='Additional arguments passed on to the test script (in sys.argv)')

    args = parser.parse_args(argv[1:])
    debug("Arguments:\n" + "\n".join([
        "%s: %s" % (k, v) for k, v in args.__dict__.items()]))

    dut = _stbt.core.new_device_under_test_from_config(args)
    with sane_unicode_and_exception_handling(args.script), \
            video(args, dut), \

            imgproc_cache.setup_cache(filename=args.cache):