{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Logging support for Tornado.\n\nTornado uses three logger streams:\n\n* ``tornado.access``: Per-request logging for Tornado's HTTP servers (and\n  potentially other servers in the future)\n* ``tornado.application``: Logging of errors from application code (i.e.\n  uncaught exceptions from callbacks)\n* ``tornado.general``: General-purpose logging, including any errors\n  or warnings from Tornado itself.\n\nThese streams may be configured independently using the standard library's\n`logging` module.  For example, you may wish to send ``tornado.access`` logs\nto a separate file for analysis.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport logging\nimport logging.handlers\nimport sys\n\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\n\ntry:\n    import curses\nexcept ImportError:\n    curses = None\n\n# Logger objects for internal tornado use\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\n\ndef _stderr_supports_color():\n    color = False\n    if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():\n        try:\n            curses.setupterm()\n            if curses.tigetnum(\"colors\") > 0:\n                color = True\n        except Exception:\n            pass\n    return color\n\n\ndef _safe_unicode(s):\n    try:\n        return _unicode(s)\n    except UnicodeDecodeError:\n        return repr(s)\n\n\nclass LogFormatter(logging.Formatter):\n    \"\"\"Log formatter used in Tornado.\n\n    Key features of this formatter are:\n\n    * Color support when logging to a terminal that supports it.\n    * Timestamps on every log line.\n    * Robust against str/bytes encoding problems.\n\n    This formatter is enabled automatically by\n    `tornado.options.parse_command_line` (unless ``--logging=none`` is\n    used).\n    \"\"\"\n    DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'\n    DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'\n    DEFAULT_COLORS = {\n        logging.DEBUG:      4,  # Blue\n        logging.INFO:       2,  # Green\n        logging.WARNING:    3,  # Yellow\n        logging.ERROR:      1,  # Red\n    }\n\n    def __init__(self, color=True, fmt=DEFAULT_FORMAT,\n                 datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):\n        r\"\"\"\n        :arg bool color: Enables color support.\n        :arg string fmt: Log message format.\n          It will be applied to the attributes dict of log records. The\n          text between ``%(color)s`` and ``%(end_color)s`` will be colored\n          depending on the level if color support is on.\n        :arg dict colors: color mappings from logging level to terminal color\n          code\n        :arg string datefmt: Datetime format.\n          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n        .. versionchanged:: 3.2\n\n           Added ``fmt`` and ``datefmt`` arguments.\n        \"\"\"\n        logging.Formatter.__init__(self, datefmt=datefmt)\n        self._fmt = fmt\n\n        self._colors = {}\n        if color and _stderr_supports_color():\n            # The curses module has some str/bytes confusion in\n            # python3.  Until version 3.2.3, most methods return\n            # bytes, but only accept strings.  In addition, we want to\n            # output these strings with the logging module, which\n            # works with unicode strings.  The explicit calls to\n            # unicode() below are harmless in python2 but will do the\n            # right conversion in python 3.\n            fg_color = (curses.tigetstr(\"setaf\") or\n                        curses.tigetstr(\"setf\") or \"\")\n            if (3, 0) < sys.version_info < (3, 2, 3):\n                fg_color = unicode_type(fg_color, \"ascii\")\n\n            for levelno, code in colors.items():\n                self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), \"ascii\")\n            self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n        else:\n            self._normal = ''\n\n    def format(self, record):\n        try:\n            message = record.getMessage()\n            assert isinstance(message, basestring_type)  # guaranteed by logging\n            # Encoding notes:  The logging module prefers to work with character\n            # strings, but only enforces that log messages are instances of\n            # basestring.  In python 2, non-ascii bytestrings will make\n            # their way through the logging framework until they blow up with\n            # an unhelpful decoding error (with this formatter it happens\n            # when we attach the prefix, but there are other opportunities for\n            # exceptions further along in the framework).\n            #\n            # If a byte string makes it this far, convert it to unicode to\n            # ensure it will make it out to the logs.  Use repr() as a fallback\n            # to ensure that all byte strings can be converted successfully,\n            # but don't do it by default so we don't add extra quotes to ascii\n            # bytestrings.  This is a bit of a hacky place to do this, but\n            # it's worth it since the encoding errors that would otherwise\n            # result are so useless (and tornado is fond of using utf8-encoded\n            # byte strings whereever possible).\n            record.message = _safe_unicode(message)\n        except Exception as e:\n            record.message = \"Bad message (%r): %r\" % (e, record.__dict__)\n\n        record.asctime = self.formatTime(record, self.datefmt)\n\n        if record.levelno in self._colors:\n            record.color = self._colors[record.levelno]\n            record.end_color = self._normal\n        else:\n            record.color = record.end_color = ''\n\n        formatted = self._fmt % record.__dict__\n\n        if record.exc_info:\n            if not record.exc_text:\n                record.exc_text = self.formatException(record.exc_info)\n        if record.exc_text:\n            # exc_text contains multiple lines.  We need to _safe_unicode\n            # each line separately so that non-utf8 bytes don't cause\n            # all the newlines to turn into '\\n'.\n            lines = [formatted.rstrip()]\n            lines.extend(_safe_unicode(ln) for ln in record.exc_text.split('\\n'))\n            formatted = '\\n'.join(lines)\n        return formatted.replace(\"\\n\", \"\\n    \")\n\n\ndef enable_pretty_logging(options=None, logger=None):\n    \"\"\"Turns on formatted logging output as configured.\n\n    This is called automaticaly by `tornado.options.parse_command_line`\n    and `tornado.options.parse_config_file`.\n    \"\"\"\n    if options is None:\n        from tornado.options import options\n    if options.logging == 'none':\n        return\n    if logger is None:\n        logger = logging.getLogger()\n    logger.setLevel(getattr(logging, options.logging.upper()))\n    if options.log_file_prefix:\n        channel = logging.handlers.RotatingFileHandler(\n            filename=options.log_file_prefix,\n            maxBytes=options.log_file_max_size,\n            backupCount=options.log_file_num_backups)\n        channel.setFormatter(LogFormatter(color=False))\n        logger.addHandler(channel)\n\n    if (options.log_to_stderr or\n            (options.log_to_stderr is None and not logger.handlers)):\n        # Set up color if we are in a tty and curses is installed\n        channel = logging.StreamHandler()\n        channel.setFormatter(LogFormatter())\n        logger.addHandler(channel)\n\n\ndef define_logging_options(options=None):\n    if options is None:\n        # late import to prevent cycle\n        from tornado.options import options\n    options.define(\"logging\", default=\"info\",\n                   help=(\"Set the Python log level. If 'none', tornado won't touch the \"\n                         \"logging configuration.\"),\n                   metavar=\"debug|info|warning|error|none\")\n    options.define(\"log_to_stderr\", type=bool, default=None,\n                   help=(\"Send log output to stderr (colorized if possible). \"\n                         \"By default use stderr if --log_file_prefix is not set and \"\n                         \"no other logging is configured.\"))\n    options.define(\"log_file_prefix\", type=str, default=None, metavar=\"PATH\",\n                   help=(\"Path prefix for log files. \"\n                         \"Note that if you are running multiple tornado processes, \"\n                         \"log_file_prefix must be different for each of them (e.g. \"\n                         \"include the port number)\"))\n    options.define(\"log_file_max_size\", type=int, default=100 * 1000 * 1000,\n                   help=\"max size of log files before rollover\")\n    options.define(\"log_file_num_backups\", type=int, default=10,\n                   help=\"number of log files to keep\")\n\n    options.add_parse_callback(enable_pretty_logging)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Logging support for Tornado.\n\nTornado uses three logger streams:\n\n* ``tornado.access``: Per-request logging for Tornado's HTTP servers (and\n  potentially other servers in the future)\n* ``tornado.application``: Logging of errors from application code (i.e.\n  uncaught exceptions from callbacks)\n* ``tornado.general``: General-purpose logging, including any errors\n  or warnings from Tornado itself.\n\nThese streams may be configured independently using the standard library's\n`logging` module.  For example, you may wish to send ``tornado.access`` logs\nto a separate file for analysis.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport logging\nimport logging.handlers\nimport sys\n\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\n\ntry:\n    import curses\nexcept ImportError:\n    curses = None\n\n# Logger objects for internal tornado use\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\n\ndef _stderr_supports_color():\n    color = False\n    if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():\n        try:\n            curses.setupterm()\n            if curses.tigetnum(\"colors\") > 0:\n                color = True\n        except Exception:\n            pass\n    return color\n\n\ndef _safe_unicode(s):\n    try:\n        return _unicode(s)\n    except UnicodeDecodeError:\n        return repr(s)\n\n\nclass LogFormatter(logging.Formatter):\n    \"\"\"Log formatter used in Tornado.\n\n    Key features of this formatter are:\n\n    * Color support when logging to a terminal that supports it.\n    * Timestamps on every log line.\n    * Robust against str/bytes encoding problems.\n\n    This formatter is enabled automatically by\n    `tornado.options.parse_command_line` (unless ``--logging=none`` is\n    used).\n    \"\"\"\n    DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'\n    DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'\n    DEFAULT_COLORS = {\n        logging.DEBUG:      4,  # Blue\n        logging.INFO:       2,  # Green\n        logging.WARNING:    3,  # Yellow\n        logging.ERROR:      1,  # Red\n    }\n\n    def __init__(self, color=True, fmt=DEFAULT_FORMAT,\n                 datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):\n        r\"\"\"\n        :arg bool color: Enables color support.\n        :arg string fmt: Log message format.\n          It will be applied to the attributes dict of log records. The\n          text between ``%(color)s`` and ``%(end_color)s`` will be colored\n          depending on the level if color support is on.\n        :arg dict colors: color mappings from logging level to terminal color\n          code\n        :arg string datefmt: Datetime format.\n          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n        .. versionchanged:: 3.2\n\n           Added ``fmt`` and ``datefmt`` arguments.\n        \"\"\"\n        logging.Formatter.__init__(self, datefmt=datefmt)\n        self._fmt = fmt\n\n        self._colors = {}\n        if color and _stderr_supports_color():\n            # The curses module has some str/bytes confusion in\n            # python3.  Until version 3.2.3, most methods return\n            # bytes, but only accept strings.  In addition, we want to\n            # output these strings with the logging module, which\n            # works with unicode strings.  The explicit calls to\n            # unicode() below are harmless in python2 but will do the\n            # right conversion in python 3.\n            fg_color = (curses.tigetstr(\"setaf\") or\n                        curses.tigetstr(\"setf\") or \"\")\n            if (3, 0) < sys.version_info < (3, 2, 3):\n                fg_color = unicode_type(fg_color, \"ascii\")\n\n            for levelno, code in colors.items():\n                self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), \"ascii\")\n            self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n        else:\n            self._normal = ''\n\n    def format(self, record):\n        try:\n            message = record.getMessage()\n            assert isinstance(message, basestring_type)  # guaranteed by logging\n            # Encoding notes:  The logging module prefers to work with character\n            # strings, but only enforces that log messages are instances of\n            # basestring.  In python 2, non-ascii bytestrings will make\n            # their way through the logging framework until they blow up with\n            # an unhelpful decoding error (with this formatter it happens\n            # when we attach the prefix, but there are other opportunities for\n            # exceptions further along in the framework).\n            #\n            # If a byte string makes it this far, convert it to unicode to\n            # ensure it will make it out to the logs.  Use repr() as a fallback\n            # to ensure that all byte strings can be converted successfully,\n            # but don't do it by default so we don't add extra quotes to ascii\n            # bytestrings.  This is a bit of a hacky place to do this, but\n            # it's worth it since the encoding errors that would otherwise\n            # result are so useless (and tornado is fond of using utf8-encoded\n            # byte strings whereever possible).\n            record.message = _safe_unicode(message)\n        except Exception as e:\n            record.message = \"Bad message (%r): %r\" % (e, record.__dict__)\n\n        record.asctime = self.formatTime(record, self.datefmt)\n\n        if record.levelno in self._colors:\n            record.color = self._colors[record.levelno]\n            record.end_color = self._normal\n        else:\n            record.color = record.end_color = ''\n\n        formatted = self._fmt % record.__dict__\n\n        if record.exc_info:\n            if not record.exc_text:\n                record.exc_text = self.formatException(record.exc_info)\n        if record.exc_text:\n            # exc_text contains multiple lines.  We need to _safe_unicode\n            # each line separately so that non-utf8 bytes don't cause\n            # all the newlines to turn into '\\n'.\n            lines = [formatted.rstrip()]\n            lines.extend(_safe_unicode(ln) for ln in record.exc_text.split('\\n'))\n            formatted = '\\n'.join(lines)\n        return formatted.replace(\"\\n\", \"\\n    \")\n\n\ndef enable_pretty_logging(options=None, logger=None):\n    \"\"\"Turns on formatted logging output as configured.\n\n    This is called automaticaly by `tornado.options.parse_command_line`\n    and `tornado.options.parse_config_file`.\n    \"\"\"\n    if options is None:\n        from tornado.options import options\n    if options.logging is None or options.logging.lower() == 'none':\n        return\n    if logger is None:\n        logger = logging.getLogger()\n    logger.setLevel(getattr(logging, options.logging.upper()))\n    if options.log_file_prefix:\n        channel = logging.handlers.RotatingFileHandler(\n            filename=options.log_file_prefix,\n            maxBytes=options.log_file_max_size,\n            backupCount=options.log_file_num_backups)\n        channel.setFormatter(LogFormatter(color=False))\n        logger.addHandler(channel)\n\n    if (options.log_to_stderr or\n            (options.log_to_stderr is None and not logger.handlers)):\n        # Set up color if we are in a tty and curses is installed\n        channel = logging.StreamHandler()\n        channel.setFormatter(LogFormatter())\n        logger.addHandler(channel)\n\n\ndef define_logging_options(options=None):\n    if options is None:\n        # late import to prevent cycle\n        from tornado.options import options\n    options.define(\"logging\", default=\"info\",\n                   help=(\"Set the Python log level. If 'none', tornado won't touch the \"\n                         \"logging configuration.\"),\n                   metavar=\"debug|info|warning|error|none\")\n    options.define(\"log_to_stderr\", type=bool, default=None,\n                   help=(\"Send log output to stderr (colorized if possible). \"\n                         \"By default use stderr if --log_file_prefix is not set and \"\n                         \"no other logging is configured.\"))\n    options.define(\"log_file_prefix\", type=str, default=None, metavar=\"PATH\",\n                   help=(\"Path prefix for log files. \"\n                         \"Note that if you are running multiple tornado processes, \"\n                         \"log_file_prefix must be different for each of them (e.g. \"\n                         \"include the port number)\"))\n    options.define(\"log_file_max_size\", type=int, default=100 * 1000 * 1000,\n                   help=\"max size of log files before rollover\")\n    options.define(\"log_file_num_backups\", type=int, default=10,\n                   help=\"number of log files to keep\")\n\n    options.add_parse_callback(enable_pretty_logging)\n",
            "header": {
                "file": {
                    "path": "tornado/log.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "36c3dd40",
                "new_commit_hash": "306220cd",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/log.py"
            },
            "plus_file": {
                "path": "b/tornado/log.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 184,
                            "length": 7
                        },
                        "new_range": {
                            "start": 184,
                            "length": 7
                        },
                        "section": "def enable_pretty_logging(options=None, logger=None):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    if options is None:",
                                "type": "context"
                            },
                            {
                                "content": "        from tornado.options import options",
                                "type": "context"
                            },
                            {
                                "content": "    if options.logging == 'none':",
                                "type": "deleted"
                            },
                            {
                                "content": "    if options.logging is None or options.logging.lower() == 'none':",
                                "type": "added"
                            },
                            {
                                "content": "        return",
                                "type": "context"
                            },
                            {
                                "content": "    if logger is None:",
                                "type": "context"
                            },
                            {
                                "content": "        logger = logging.getLogger()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/log.py",
                            "type": "function",
                            "name": "enable_pretty_logging",
                            "content": "def enable_pretty_logging(options=None, logger=None):\n    \"\"\"Turns on formatted logging output as configured.\n\n    This is called automaticaly by `tornado.options.parse_command_line`\n    and `tornado.options.parse_config_file`.\n    \"\"\"\n    if options is None:\n        from tornado.options import options\n    if options.logging == 'none':\n        return\n    if logger is None:\n        logger = logging.getLogger()\n    logger.setLevel(getattr(logging, options.logging.upper()))\n    if options.log_file_prefix:\n        channel = logging.handlers.RotatingFileHandler(\n            filename=options.log_file_prefix,\n            maxBytes=options.log_file_max_size,\n            backupCount=options.log_file_num_backups)\n        channel.setFormatter(LogFormatter(color=False))\n        logger.addHandler(channel)\n\n    if (options.log_to_stderr or\n            (options.log_to_stderr is None and not logger.handlers)):\n        # Set up color if we are in a tty and curses is installed\n        channel = logging.StreamHandler()\n        channel.setFormatter(LogFormatter())\n        logger.addHandler(channel)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 179,
                            "end_lineno": 205,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\n\nfrom tornado.escape import _unicode\nfrom tornado.log import define_logging_options\nfrom tornado import stack_context\nfrom tornado.util import basestring_type, exec_in\n\n\nclass Error(Exception):\n    \"\"\"Exception raised by errors in the options module.\"\"\"\n    pass\n\n\nclass OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\" %\n                        (name, self._options[name].file_name))\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)\n\n\nclass _Mockable(object):\n    \"\"\"`mock.patch` compatible wrapper for `OptionParser`.\n\n    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``\n    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete\n    the attribute it set instead of setting a new one (assuming that\n    the object does not catpure ``__setattr__``, so the patch\n    created a new attribute in ``__dict__``).\n\n    _Mockable's getattr and setattr pass through to the underlying\n    OptionParser, and delattr undoes the effect of a previous setattr.\n    \"\"\"\n    def __init__(self, options):\n        # Modify __dict__ directly to bypass __setattr__\n        self.__dict__['_options'] = options\n        self.__dict__['_originals'] = {}\n\n    def __getattr__(self, name):\n        return getattr(self._options, name)\n\n    def __setattr__(self, name, value):\n        assert name not in self._originals, \"don't reuse mockable objects\"\n        self._originals[name] = getattr(self._options, name)\n        setattr(self._options, name, value)\n\n    def __delattr__(self, name):\n        setattr(self._options, name, self._originals.pop(name))\n\n\nclass _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)\n\n\noptions = OptionParser()\n\"\"\"Global options object.\n\nAll defined options are available as attributes on this object.\n\"\"\"\n\n\ndef define(name, default=None, type=None, help=None, metavar=None,\n           multiple=False, group=None, callback=None):\n    \"\"\"Defines an option in the global namespace.\n\n    See `OptionParser.define`.\n    \"\"\"\n    return options.define(name, default=default, type=type, help=help,\n                          metavar=metavar, multiple=multiple, group=group,\n                          callback=callback)\n\n\ndef parse_command_line(args=None, final=True):\n    \"\"\"Parses global options from the command line.\n\n    See `OptionParser.parse_command_line`.\n    \"\"\"\n    return options.parse_command_line(args, final=final)\n\n\ndef parse_config_file(path, final=True):\n    \"\"\"Parses global options from a config file.\n\n    See `OptionParser.parse_config_file`.\n    \"\"\"\n    return options.parse_config_file(path, final=final)\n\n\ndef print_help(file=None):\n    \"\"\"Prints all the command line options to stderr (or another file).\n\n    See `OptionParser.print_help`.\n    \"\"\"\n    return options.print_help(file)\n\n\ndef add_parse_callback(callback):\n    \"\"\"Adds a parse callback, to be invoked when option parsing is done.\n\n    See `OptionParser.add_parse_callback`\n    \"\"\"\n    options.add_parse_callback(callback)\n\n\n# Default options\ndefine_logging_options(options)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\n.. note::\n\n   By default, several options are defined that will configure the\n   standard `logging` module when `parse_command_line` or `parse_config_file`\n   are called.  If you want Tornado to leave the logging configuration\n   alone so you can manage it yourself, either pass ``--logging=none``\n   on the command line or do the following to disable it in code::\n\n       from tornado.options import options, parse_command_line\n       options.logging = None\n       parse_command_line()\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\n\nfrom tornado.escape import _unicode\nfrom tornado.log import define_logging_options\nfrom tornado import stack_context\nfrom tornado.util import basestring_type, exec_in\n\n\nclass Error(Exception):\n    \"\"\"Exception raised by errors in the options module.\"\"\"\n    pass\n\n\nclass OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\" %\n                        (name, self._options[name].file_name))\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)\n\n\nclass _Mockable(object):\n    \"\"\"`mock.patch` compatible wrapper for `OptionParser`.\n\n    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``\n    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete\n    the attribute it set instead of setting a new one (assuming that\n    the object does not catpure ``__setattr__``, so the patch\n    created a new attribute in ``__dict__``).\n\n    _Mockable's getattr and setattr pass through to the underlying\n    OptionParser, and delattr undoes the effect of a previous setattr.\n    \"\"\"\n    def __init__(self, options):\n        # Modify __dict__ directly to bypass __setattr__\n        self.__dict__['_options'] = options\n        self.__dict__['_originals'] = {}\n\n    def __getattr__(self, name):\n        return getattr(self._options, name)\n\n    def __setattr__(self, name, value):\n        assert name not in self._originals, \"don't reuse mockable objects\"\n        self._originals[name] = getattr(self._options, name)\n        setattr(self._options, name, value)\n\n    def __delattr__(self, name):\n        setattr(self._options, name, self._originals.pop(name))\n\n\nclass _Option(object):\n    UNSET = object()\n\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = _Option.UNSET\n\n    def value(self):\n        return self.default if self._value is _Option.UNSET else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)\n\n\noptions = OptionParser()\n\"\"\"Global options object.\n\nAll defined options are available as attributes on this object.\n\"\"\"\n\n\ndef define(name, default=None, type=None, help=None, metavar=None,\n           multiple=False, group=None, callback=None):\n    \"\"\"Defines an option in the global namespace.\n\n    See `OptionParser.define`.\n    \"\"\"\n    return options.define(name, default=default, type=type, help=help,\n                          metavar=metavar, multiple=multiple, group=group,\n                          callback=callback)\n\n\ndef parse_command_line(args=None, final=True):\n    \"\"\"Parses global options from the command line.\n\n    See `OptionParser.parse_command_line`.\n    \"\"\"\n    return options.parse_command_line(args, final=final)\n\n\ndef parse_config_file(path, final=True):\n    \"\"\"Parses global options from a config file.\n\n    See `OptionParser.parse_config_file`.\n    \"\"\"\n    return options.parse_config_file(path, final=final)\n\n\ndef print_help(file=None):\n    \"\"\"Prints all the command line options to stderr (or another file).\n\n    See `OptionParser.print_help`.\n    \"\"\"\n    return options.print_help(file)\n\n\ndef add_parse_callback(callback):\n    \"\"\"Adds a parse callback, to be invoked when option parsing is done.\n\n    See `OptionParser.add_parse_callback`\n    \"\"\"\n    options.add_parse_callback(callback)\n\n\n# Default options\ndefine_logging_options(options)\n",
            "header": {
                "file": {
                    "path": "tornado/options.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "1105c0e9",
                "new_commit_hash": "fa9c269e",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/options.py"
            },
            "plus_file": {
                "path": "b/tornado/options.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 56,
                            "length": 6
                        },
                        "new_range": {
                            "start": 56,
                            "length": 18
                        },
                        "section": "We support `datetimes <datetime.datetime>`, `timedeltas"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "the top-level functions in this module (`define`, `parse_command_line`, etc)",
                                "type": "context"
                            },
                            {
                                "content": "simply call methods on it.  You may create additional `OptionParser`",
                                "type": "context"
                            },
                            {
                                "content": "instances to define isolated sets of options, such as for subcommands.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": ".. note::",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "   By default, several options are defined that will configure the",
                                "type": "added"
                            },
                            {
                                "content": "   standard `logging` module when `parse_command_line` or `parse_config_file`",
                                "type": "added"
                            },
                            {
                                "content": "   are called.  If you want Tornado to leave the logging configuration",
                                "type": "added"
                            },
                            {
                                "content": "   alone so you can manage it yourself, either pass ``--logging=none``",
                                "type": "added"
                            },
                            {
                                "content": "   on the command line or do the following to disable it in code::",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "       from tornado.options import options, parse_command_line",
                                "type": "added"
                            },
                            {
                                "content": "       options.logging = None",
                                "type": "added"
                            },
                            {
                                "content": "       parse_command_line()",
                                "type": "added"
                            },
                            {
                                "content": "\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from __future__ import absolute_import, division, print_function, with_statement",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/options.py",
                            "type": "statement",
                            "name": "",
                            "content": "\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\n.. note::\n\n   By default, several options are defined that will configure the\n   standard `logging` module when `parse_command_line` or `parse_config_file`\n   are called.  If you want Tornado to leave the logging configuration\n   alone so you can manage it yourself, either pass ``--logging=none``\n   on the command line or do the following to disable it in code::\n\n       from tornado.options import options, parse_command_line\n       options.logging = None\n       parse_command_line()\n\"\"\"",
                            "ast_type_str": "Expr",
                            "start_lineno": 17,
                            "end_lineno": 71,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 360,
                            "length": 6
                        },
                        "new_range": {
                            "start": 372,
                            "length": 8
                        },
                        "section": "class _Mockable(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class _Option(object):",
                                "type": "context"
                            },
                            {
                                "content": "    UNSET = object()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def __init__(self, name, default=None, type=basestring_type, help=None,",
                                "type": "context"
                            },
                            {
                                "content": "                 metavar=None, multiple=False, file_name=None, group_name=None,",
                                "type": "context"
                            },
                            {
                                "content": "                 callback=None):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/options.py",
                            "type": "class",
                            "name": "_Option",
                            "content": "class _Option(object):\n    UNSET = object()\n\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = _Option.UNSET\n\n    def value(self):\n        return self.default if self._value is _Option.UNSET else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 374,
                            "end_lineno": 499,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 374,
                            "length": 10
                        },
                        "new_range": {
                            "start": 388,
                            "length": 10
                        },
                        "section": "class _Option(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.group_name = group_name",
                                "type": "context"
                            },
                            {
                                "content": "        self.callback = callback",
                                "type": "context"
                            },
                            {
                                "content": "        self.default = default",
                                "type": "context"
                            },
                            {
                                "content": "        self._value = None",
                                "type": "deleted"
                            },
                            {
                                "content": "        self._value = _Option.UNSET",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def value(self):",
                                "type": "context"
                            },
                            {
                                "content": "        return self.default if self._value is None else self._value",
                                "type": "deleted"
                            },
                            {
                                "content": "        return self.default if self._value is _Option.UNSET else self._value",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def parse(self, value):",
                                "type": "context"
                            },
                            {
                                "content": "        _parse = {",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/options.py",
                            "type": "method",
                            "name": "_Option.__init__",
                            "content": "class _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 363,
                            "end_lineno": 377,
                            "parent": {
                                "file_name": "tornado/options.py",
                                "type": "class",
                                "name": "_Option",
                                "content": "class _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 362,
                                "end_lineno": 485,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/options.py",
                            "type": "method",
                            "name": "_Option.value",
                            "content": "class _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 379,
                            "end_lineno": 380,
                            "parent": {
                                "file_name": "tornado/options.py",
                                "type": "class",
                                "name": "_Option",
                                "content": "class _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 362,
                                "end_lineno": 485,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/options.py",
                            "type": "class",
                            "name": "_Option",
                            "content": "class _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 362,
                            "end_lineno": 485,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport glob\nimport logging\nimport os\nimport re\nimport tempfile\nimport warnings\n\nfrom tornado.escape import utf8\nfrom tornado.log import LogFormatter, define_logging_options, enable_pretty_logging\nfrom tornado.options import OptionParser\nfrom tornado.test.util import unittest\nfrom tornado.util import u, bytes_type, basestring_type\n\n\n@contextlib.contextmanager\ndef ignore_bytes_warning():\n    with warnings.catch_warnings():\n        warnings.simplefilter('ignore', category=BytesWarning)\n        yield\n\n\nclass LogFormatterTest(unittest.TestCase):\n    # Matches the output of a single logging call (which may be multiple lines\n    # if a traceback was included, so we use the DOTALL option)\n    LINE_RE = re.compile(b\"(?s)\\x01\\\\[E [0-9]{6} [0-9]{2}:[0-9]{2}:[0-9]{2} log_test:[0-9]+\\\\]\\x02 (.*)\")\n\n    def setUp(self):\n        self.formatter = LogFormatter(color=False)\n        # Fake color support.  We can't guarantee anything about the $TERM\n        # variable when the tests are run, so just patch in some values\n        # for testing.  (testing with color off fails to expose some potential\n        # encoding issues from the control characters)\n        self.formatter._colors = {\n            logging.ERROR: u(\"\\u0001\"),\n        }\n        self.formatter._normal = u(\"\\u0002\")\n        # construct a Logger directly to bypass getLogger's caching\n        self.logger = logging.Logger('LogFormatterTest')\n        self.logger.propagate = False\n        self.tempdir = tempfile.mkdtemp()\n        self.filename = os.path.join(self.tempdir, 'log.out')\n        self.handler = self.make_handler(self.filename)\n        self.handler.setFormatter(self.formatter)\n        self.logger.addHandler(self.handler)\n\n    def tearDown(self):\n        self.handler.close()\n        os.unlink(self.filename)\n        os.rmdir(self.tempdir)\n\n    def make_handler(self, filename):\n        # Base case: default setup without explicit encoding.\n        # In python 2, supports arbitrary byte strings and unicode objects\n        # that contain only ascii.  In python 3, supports ascii-only unicode\n        # strings (but byte strings will be repr'd automatically).\n        return logging.FileHandler(filename)\n\n    def get_output(self):\n        with open(self.filename, \"rb\") as f:\n            line = f.read().strip()\n            m = LogFormatterTest.LINE_RE.match(line)\n            if m:\n                return m.group(1)\n            else:\n                raise Exception(\"output didn't match regex: %r\" % line)\n\n    def test_basic_logging(self):\n        self.logger.error(\"foo\")\n        self.assertEqual(self.get_output(), b\"foo\")\n\n    def test_bytes_logging(self):\n        with ignore_bytes_warning():\n            # This will be \"\\xe9\" on python 2 or \"b'\\xe9'\" on python 3\n            self.logger.error(b\"\\xe9\")\n            self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n\n    def test_utf8_logging(self):\n        self.logger.error(u(\"\\u00e9\").encode(\"utf8\"))\n        if issubclass(bytes_type, basestring_type):\n            # on python 2, utf8 byte strings (and by extension ascii byte\n            # strings) are passed through as-is.\n            self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n        else:\n            # on python 3, byte strings always get repr'd even if\n            # they're ascii-only, so this degenerates into another\n            # copy of test_bytes_logging.\n            self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n\n    def test_bytes_exception_logging(self):\n        try:\n            raise Exception(b'\\xe9')\n        except Exception:\n            self.logger.exception('caught exception')\n        # This will be \"Exception: \\xe9\" on python 2 or\n        # \"Exception: b'\\xe9'\" on python 3.\n        output = self.get_output()\n        self.assertRegexpMatches(output, br'Exception.*\\\\xe9')\n        # The traceback contains newlines, which should not have been escaped.\n        self.assertNotIn(br'\\n', output)\n\n\nclass UnicodeLogFormatterTest(LogFormatterTest):\n    def make_handler(self, filename):\n        # Adding an explicit encoding configuration allows non-ascii unicode\n        # strings in both python 2 and 3, without changing the behavior\n        # for byte strings.\n        return logging.FileHandler(filename, encoding=\"utf8\")\n\n    def test_unicode_logging(self):\n        self.logger.error(u(\"\\u00e9\"))\n        self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n\n\nclass EnablePrettyLoggingTest(unittest.TestCase):\n    def setUp(self):\n        super(EnablePrettyLoggingTest, self).setUp()\n        self.options = OptionParser()\n        define_logging_options(self.options)\n        self.logger = logging.Logger('tornado.test.log_test.EnablePrettyLoggingTest')\n        self.logger.propagate = False\n\n    def test_log_file(self):\n        tmpdir = tempfile.mkdtemp()\n        try:\n            self.options.log_file_prefix = tmpdir + '/test_log'\n            enable_pretty_logging(options=self.options, logger=self.logger)\n            self.assertEqual(1, len(self.logger.handlers))\n            self.logger.error('hello')\n            self.logger.handlers[0].flush()\n            filenames = glob.glob(tmpdir + '/test_log*')\n            self.assertEqual(1, len(filenames))\n            with open(filenames[0]) as f:\n                self.assertRegexpMatches(f.read(), r'^\\[E [^]]*\\] hello$')\n        finally:\n            for handler in self.logger.handlers:\n                handler.flush()\n                handler.close()\n            for filename in glob.glob(tmpdir + '/test_log*'):\n                os.unlink(filename)\n            os.rmdir(tmpdir)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport glob\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nimport warnings\n\nfrom tornado.escape import utf8\nfrom tornado.log import LogFormatter, define_logging_options, enable_pretty_logging\nfrom tornado.options import OptionParser\nfrom tornado.test.util import unittest\nfrom tornado.util import u, bytes_type, basestring_type\n\n\n@contextlib.contextmanager\ndef ignore_bytes_warning():\n    with warnings.catch_warnings():\n        warnings.simplefilter('ignore', category=BytesWarning)\n        yield\n\n\nclass LogFormatterTest(unittest.TestCase):\n    # Matches the output of a single logging call (which may be multiple lines\n    # if a traceback was included, so we use the DOTALL option)\n    LINE_RE = re.compile(b\"(?s)\\x01\\\\[E [0-9]{6} [0-9]{2}:[0-9]{2}:[0-9]{2} log_test:[0-9]+\\\\]\\x02 (.*)\")\n\n    def setUp(self):\n        self.formatter = LogFormatter(color=False)\n        # Fake color support.  We can't guarantee anything about the $TERM\n        # variable when the tests are run, so just patch in some values\n        # for testing.  (testing with color off fails to expose some potential\n        # encoding issues from the control characters)\n        self.formatter._colors = {\n            logging.ERROR: u(\"\\u0001\"),\n        }\n        self.formatter._normal = u(\"\\u0002\")\n        # construct a Logger directly to bypass getLogger's caching\n        self.logger = logging.Logger('LogFormatterTest')\n        self.logger.propagate = False\n        self.tempdir = tempfile.mkdtemp()\n        self.filename = os.path.join(self.tempdir, 'log.out')\n        self.handler = self.make_handler(self.filename)\n        self.handler.setFormatter(self.formatter)\n        self.logger.addHandler(self.handler)\n\n    def tearDown(self):\n        self.handler.close()\n        os.unlink(self.filename)\n        os.rmdir(self.tempdir)\n\n    def make_handler(self, filename):\n        # Base case: default setup without explicit encoding.\n        # In python 2, supports arbitrary byte strings and unicode objects\n        # that contain only ascii.  In python 3, supports ascii-only unicode\n        # strings (but byte strings will be repr'd automatically).\n        return logging.FileHandler(filename)\n\n    def get_output(self):\n        with open(self.filename, \"rb\") as f:\n            line = f.read().strip()\n            m = LogFormatterTest.LINE_RE.match(line)\n            if m:\n                return m.group(1)\n            else:\n                raise Exception(\"output didn't match regex: %r\" % line)\n\n    def test_basic_logging(self):\n        self.logger.error(\"foo\")\n        self.assertEqual(self.get_output(), b\"foo\")\n\n    def test_bytes_logging(self):\n        with ignore_bytes_warning():\n            # This will be \"\\xe9\" on python 2 or \"b'\\xe9'\" on python 3\n            self.logger.error(b\"\\xe9\")\n            self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n\n    def test_utf8_logging(self):\n        self.logger.error(u(\"\\u00e9\").encode(\"utf8\"))\n        if issubclass(bytes_type, basestring_type):\n            # on python 2, utf8 byte strings (and by extension ascii byte\n            # strings) are passed through as-is.\n            self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n        else:\n            # on python 3, byte strings always get repr'd even if\n            # they're ascii-only, so this degenerates into another\n            # copy of test_bytes_logging.\n            self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n\n    def test_bytes_exception_logging(self):\n        try:\n            raise Exception(b'\\xe9')\n        except Exception:\n            self.logger.exception('caught exception')\n        # This will be \"Exception: \\xe9\" on python 2 or\n        # \"Exception: b'\\xe9'\" on python 3.\n        output = self.get_output()\n        self.assertRegexpMatches(output, br'Exception.*\\\\xe9')\n        # The traceback contains newlines, which should not have been escaped.\n        self.assertNotIn(br'\\n', output)\n\n\nclass UnicodeLogFormatterTest(LogFormatterTest):\n    def make_handler(self, filename):\n        # Adding an explicit encoding configuration allows non-ascii unicode\n        # strings in both python 2 and 3, without changing the behavior\n        # for byte strings.\n        return logging.FileHandler(filename, encoding=\"utf8\")\n\n    def test_unicode_logging(self):\n        self.logger.error(u(\"\\u00e9\"))\n        self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n\n\nclass EnablePrettyLoggingTest(unittest.TestCase):\n    def setUp(self):\n        super(EnablePrettyLoggingTest, self).setUp()\n        self.options = OptionParser()\n        define_logging_options(self.options)\n        self.logger = logging.Logger('tornado.test.log_test.EnablePrettyLoggingTest')\n        self.logger.propagate = False\n\n    def test_log_file(self):\n        tmpdir = tempfile.mkdtemp()\n        try:\n            self.options.log_file_prefix = tmpdir + '/test_log'\n            enable_pretty_logging(options=self.options, logger=self.logger)\n            self.assertEqual(1, len(self.logger.handlers))\n            self.logger.error('hello')\n            self.logger.handlers[0].flush()\n            filenames = glob.glob(tmpdir + '/test_log*')\n            self.assertEqual(1, len(filenames))\n            with open(filenames[0]) as f:\n                self.assertRegexpMatches(f.read(), r'^\\[E [^]]*\\] hello$')\n        finally:\n            for handler in self.logger.handlers:\n                handler.flush()\n                handler.close()\n            for filename in glob.glob(tmpdir + '/test_log*'):\n                os.unlink(filename)\n            os.rmdir(tmpdir)\n\n\nclass LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))\n",
            "header": {
                "file": {
                    "path": "tornado/test/log_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "d60cbad4",
                "new_commit_hash": "ee832c54",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/log_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/log_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 20,
                            "length": 6
                        },
                        "new_range": {
                            "start": 20,
                            "length": 8
                        },
                        "section": "import glob"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import logging",
                                "type": "context"
                            },
                            {
                                "content": "import os",
                                "type": "context"
                            },
                            {
                                "content": "import re",
                                "type": "context"
                            },
                            {
                                "content": "import subprocess",
                                "type": "added"
                            },
                            {
                                "content": "import sys",
                                "type": "added"
                            },
                            {
                                "content": "import tempfile",
                                "type": "context"
                            },
                            {
                                "content": "import warnings",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "import",
                            "name": "sys",
                            "content": "import sys",
                            "ast_type_str": "Import",
                            "start_lineno": 24,
                            "end_lineno": 24,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "import",
                            "name": "subprocess",
                            "content": "import subprocess",
                            "ast_type_str": "Import",
                            "start_lineno": 23,
                            "end_lineno": 23,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 156,
                            "length": 3
                        },
                        "new_range": {
                            "start": 158,
                            "length": 50
                        },
                        "section": "class EnablePrettyLoggingTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            for filename in glob.glob(tmpdir + '/test_log*'):",
                                "type": "context"
                            },
                            {
                                "content": "                os.unlink(filename)",
                                "type": "context"
                            },
                            {
                                "content": "            os.rmdir(tmpdir)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class LoggingOptionTest(unittest.TestCase):",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "    def logs_present(self, statement, args=None):",
                                "type": "added"
                            },
                            {
                                "content": "        # Each test may manipulate and/or parse the options and then logs",
                                "type": "added"
                            },
                            {
                                "content": "        # a line at the 'info' level.  This level is ignored in the",
                                "type": "added"
                            },
                            {
                                "content": "        # logging module by default, but Tornado turns it on by default",
                                "type": "added"
                            },
                            {
                                "content": "        # so it is the easiest way to tell whether tornado's logging hooks",
                                "type": "added"
                            },
                            {
                                "content": "        # ran.",
                                "type": "added"
                            },
                            {
                                "content": "        IMPORT = 'from tornado.options import options, parse_command_line'",
                                "type": "added"
                            },
                            {
                                "content": "        LOG_INFO = 'import logging; logging.info(\"hello\")'",
                                "type": "added"
                            },
                            {
                                "content": "        program = ';'.join([IMPORT, statement, LOG_INFO])",
                                "type": "added"
                            },
                            {
                                "content": "        proc = subprocess.Popen(",
                                "type": "added"
                            },
                            {
                                "content": "            [sys.executable, '-c', program] + (args or []),",
                                "type": "added"
                            },
                            {
                                "content": "            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)",
                                "type": "added"
                            },
                            {
                                "content": "        stdout, stderr = proc.communicate()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)",
                                "type": "added"
                            },
                            {
                                "content": "        return b'hello' in stdout",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_default(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(self.logs_present('pass'))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_tornado_default(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(self.logs_present('parse_command_line()'))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_disable_command_line(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(self.logs_present('parse_command_line()',",
                                "type": "added"
                            },
                            {
                                "content": "                                           ['--logging=none']))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_disable_command_line_case_insensitive(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(self.logs_present('parse_command_line()',",
                                "type": "added"
                            },
                            {
                                "content": "                                           ['--logging=None']))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_disable_code_string(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(self.logs_present(",
                                "type": "added"
                            },
                            {
                                "content": "            'options.logging = \"none\"; parse_command_line()'))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_disable_code_none(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(self.logs_present(",
                                "type": "added"
                            },
                            {
                                "content": "            'options.logging = None; parse_command_line()'))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_disable_override(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # command line trumps code defaults",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(self.logs_present(",
                                "type": "added"
                            },
                            {
                                "content": "            'options.logging = None; parse_command_line()',",
                                "type": "added"
                            },
                            {
                                "content": "            ['--logging=info']))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_disable_command_line",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 187,
                            "end_lineno": 189,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_disable_override",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 203,
                            "end_lineno": 207,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_disable_code_string",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 195,
                            "end_lineno": 197,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_disable_command_line_case_insensitive",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 191,
                            "end_lineno": 193,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_tornado_default",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 184,
                            "end_lineno": 185,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_disable_code_none",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 199,
                            "end_lineno": 201,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "class",
                            "name": "LoggingOptionTest",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 163,
                            "end_lineno": 207,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.logs_present",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 165,
                            "end_lineno": 179,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/log_test.py",
                            "type": "method",
                            "name": "LoggingOptionTest.test_default",
                            "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 181,
                            "end_lineno": 182,
                            "parent": {
                                "file_name": "tornado/test/log_test.py",
                                "type": "class",
                                "name": "LoggingOptionTest",
                                "content": "class LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 163,
                                "end_lineno": 207,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "2dc57c57b1a4e64e0c10796718f54f0792968dba^",
    "new_commit_hash": "2dc57c57b1a4e64e0c10796718f54f0792968dba",
    "commit_message": "Document the fact that tornado.options configures logging by default.\n\nAdd tests and comments for how to disable this configuration.\nMake it slightly easier to disable by making the command line\nflag case-insensitive and allowing `None` instead of the string \"none\"\nwhen setting the flag in code.\n\nCloses #952.",
    "commit_date": "2014-02-18T23:35:55-05:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "2dc57c57b1a4e64e0c10796718f54f0792968dba",
    "test_file_codes": [
        "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport contextlib\nimport glob\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nimport warnings\n\nfrom tornado.escape import utf8\nfrom tornado.log import LogFormatter, define_logging_options, enable_pretty_logging\nfrom tornado.options import OptionParser\nfrom tornado.test.util import unittest\nfrom tornado.util import u, bytes_type, basestring_type\n\n\n@contextlib.contextmanager\ndef ignore_bytes_warning():\n    with warnings.catch_warnings():\n        warnings.simplefilter('ignore', category=BytesWarning)\n        yield\n\n\nclass LogFormatterTest(unittest.TestCase):\n    # Matches the output of a single logging call (which may be multiple lines\n    # if a traceback was included, so we use the DOTALL option)\n    LINE_RE = re.compile(b\"(?s)\\x01\\\\[E [0-9]{6} [0-9]{2}:[0-9]{2}:[0-9]{2} log_test:[0-9]+\\\\]\\x02 (.*)\")\n\n    def setUp(self):\n        self.formatter = LogFormatter(color=False)\n        # Fake color support.  We can't guarantee anything about the $TERM\n        # variable when the tests are run, so just patch in some values\n        # for testing.  (testing with color off fails to expose some potential\n        # encoding issues from the control characters)\n        self.formatter._colors = {\n            logging.ERROR: u(\"\\u0001\"),\n        }\n        self.formatter._normal = u(\"\\u0002\")\n        # construct a Logger directly to bypass getLogger's caching\n        self.logger = logging.Logger('LogFormatterTest')\n        self.logger.propagate = False\n        self.tempdir = tempfile.mkdtemp()\n        self.filename = os.path.join(self.tempdir, 'log.out')\n        self.handler = self.make_handler(self.filename)\n        self.handler.setFormatter(self.formatter)\n        self.logger.addHandler(self.handler)\n\n    def tearDown(self):\n        self.handler.close()\n        os.unlink(self.filename)\n        os.rmdir(self.tempdir)\n\n    def make_handler(self, filename):\n        # Base case: default setup without explicit encoding.\n        # In python 2, supports arbitrary byte strings and unicode objects\n        # that contain only ascii.  In python 3, supports ascii-only unicode\n        # strings (but byte strings will be repr'd automatically).\n        return logging.FileHandler(filename)\n\n    def get_output(self):\n        with open(self.filename, \"rb\") as f:\n            line = f.read().strip()\n            m = LogFormatterTest.LINE_RE.match(line)\n            if m:\n                return m.group(1)\n            else:\n                raise Exception(\"output didn't match regex: %r\" % line)\n\n    def test_basic_logging(self):\n        self.logger.error(\"foo\")\n        self.assertEqual(self.get_output(), b\"foo\")\n\n    def test_bytes_logging(self):\n        with ignore_bytes_warning():\n            # This will be \"\\xe9\" on python 2 or \"b'\\xe9'\" on python 3\n            self.logger.error(b\"\\xe9\")\n            self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n\n    def test_utf8_logging(self):\n        self.logger.error(u(\"\\u00e9\").encode(\"utf8\"))\n        if issubclass(bytes_type, basestring_type):\n            # on python 2, utf8 byte strings (and by extension ascii byte\n            # strings) are passed through as-is.\n            self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n        else:\n            # on python 3, byte strings always get repr'd even if\n            # they're ascii-only, so this degenerates into another\n            # copy of test_bytes_logging.\n            self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n\n    def test_bytes_exception_logging(self):\n        try:\n            raise Exception(b'\\xe9')\n        except Exception:\n            self.logger.exception('caught exception')\n        # This will be \"Exception: \\xe9\" on python 2 or\n        # \"Exception: b'\\xe9'\" on python 3.\n        output = self.get_output()\n        self.assertRegexpMatches(output, br'Exception.*\\\\xe9')\n        # The traceback contains newlines, which should not have been escaped.\n        self.assertNotIn(br'\\n', output)\n\n\nclass UnicodeLogFormatterTest(LogFormatterTest):\n    def make_handler(self, filename):\n        # Adding an explicit encoding configuration allows non-ascii unicode\n        # strings in both python 2 and 3, without changing the behavior\n        # for byte strings.\n        return logging.FileHandler(filename, encoding=\"utf8\")\n\n    def test_unicode_logging(self):\n        self.logger.error(u(\"\\u00e9\"))\n        self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n\n\nclass EnablePrettyLoggingTest(unittest.TestCase):\n    def setUp(self):\n        super(EnablePrettyLoggingTest, self).setUp()\n        self.options = OptionParser()\n        define_logging_options(self.options)\n        self.logger = logging.Logger('tornado.test.log_test.EnablePrettyLoggingTest')\n        self.logger.propagate = False\n\n    def test_log_file(self):\n        tmpdir = tempfile.mkdtemp()\n        try:\n            self.options.log_file_prefix = tmpdir + '/test_log'\n            enable_pretty_logging(options=self.options, logger=self.logger)\n            self.assertEqual(1, len(self.logger.handlers))\n            self.logger.error('hello')\n            self.logger.handlers[0].flush()\n            filenames = glob.glob(tmpdir + '/test_log*')\n            self.assertEqual(1, len(filenames))\n            with open(filenames[0]) as f:\n                self.assertRegexpMatches(f.read(), r'^\\[E [^]]*\\] hello$')\n        finally:\n            for handler in self.logger.handlers:\n                handler.flush()\n                handler.close()\n            for filename in glob.glob(tmpdir + '/test_log*'):\n                os.unlink(filename)\n            os.rmdir(tmpdir)\n\n\nclass LoggingOptionTest(unittest.TestCase):\n    \"\"\"Test the ability to enable and disable Tornado's logging hooks.\"\"\"\n    def logs_present(self, statement, args=None):\n        # Each test may manipulate and/or parse the options and then logs\n        # a line at the 'info' level.  This level is ignored in the\n        # logging module by default, but Tornado turns it on by default\n        # so it is the easiest way to tell whether tornado's logging hooks\n        # ran.\n        IMPORT = 'from tornado.options import options, parse_command_line'\n        LOG_INFO = 'import logging; logging.info(\"hello\")'\n        program = ';'.join([IMPORT, statement, LOG_INFO])\n        proc = subprocess.Popen(\n            [sys.executable, '-c', program] + (args or []),\n            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n        stdout, stderr = proc.communicate()\n        self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\n        return b'hello' in stdout\n\n    def test_default(self):\n        self.assertFalse(self.logs_present('pass'))\n\n    def test_tornado_default(self):\n        self.assertTrue(self.logs_present('parse_command_line()'))\n\n    def test_disable_command_line(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=none']))\n\n    def test_disable_command_line_case_insensitive(self):\n        self.assertFalse(self.logs_present('parse_command_line()',\n                                           ['--logging=None']))\n\n    def test_disable_code_string(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = \"none\"; parse_command_line()'))\n\n    def test_disable_code_none(self):\n        self.assertFalse(self.logs_present(\n            'options.logging = None; parse_command_line()'))\n\n    def test_disable_override(self):\n        # command line trumps code defaults\n        self.assertTrue(self.logs_present(\n            'options.logging = None; parse_command_line()',\n            ['--logging=info']))\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 989ms\nPrepared 1 package in 1.19s\nInstalled 1 package in 1ms\n + tornado==3.3.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba)\nResolved 29 packages in 14ms\nInstalled 29 packages in 210ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba\n.................\ncollected 17 items\n\n=================================== ERRORS =====================================\n__________ LogFormatterTest.test_basic_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 89, in test_basic_logging\n    self.assertEqual(self.get_output(), b\"foo\")\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:30 test_1:88]\\x02 foo'\n__________ LogFormatterTest.test_bytes_exception_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 116, in test_bytes_exception_logging\n    output = self.get_output()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:30 test_1:113]\\x02 caught exception\\n    Traceback (most recent call last):\\n      File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 111, in test_bytes_exception_logging\\n        raise Exception(b\\'\\\\xe9\\')\\n    Exception: b\\'\\\\xe9\\''\n__________ LogFormatterTest.test_bytes_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 95, in test_bytes_logging\n    self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:30 test_1:94]\\x02 b'\\\\xe9'\"\n__________ LogFormatterTest.test_utf8_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 107, in test_utf8_logging\n    self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:30 test_1:98]\\x02 b'\\\\xc3\\\\xa9'\"\n__________ UnicodeLogFormatterTest.test_basic_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 89, in test_basic_logging\n    self.assertEqual(self.get_output(), b\"foo\")\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:88]\\x02 foo'\n__________ UnicodeLogFormatterTest.test_bytes_exception_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 116, in test_bytes_exception_logging\n    output = self.get_output()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:113]\\x02 caught exception\\n    Traceback (most recent call last):\\n      File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 111, in test_bytes_exception_logging\\n        raise Exception(b\\'\\\\xe9\\')\\n    Exception: b\\'\\\\xe9\\''\n__________ UnicodeLogFormatterTest.test_bytes_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 95, in test_bytes_logging\n    self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:31 test_1:94]\\x02 b'\\\\xe9'\"\n__________ UnicodeLogFormatterTest.test_unicode_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 131, in test_unicode_logging\n    self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:130]\\x02 \\xc3\\xa9'\n__________ UnicodeLogFormatterTest.test_utf8_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 107, in test_utf8_logging\n    self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:31 test_1:98]\\x02 b'\\\\xc3\\\\xa9'\"\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::EnablePrettyLoggingTest::test_log_file\nERROR r2e_tests.test_1::LogFormatterTest::test_basic_logging\nERROR r2e_tests.test_1::LogFormatterTest::test_bytes_exception_logging\nERROR r2e_tests.test_1::LogFormatterTest::test_bytes_logging\nERROR r2e_tests.test_1::LogFormatterTest::test_utf8_logging\nPASSED r2e_tests.test_1::LoggingOptionTest::test_default\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_code_none\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_code_string\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_command_line\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_command_line_case_insensitive\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_override\nPASSED r2e_tests.test_1::LoggingOptionTest::test_tornado_default\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_basic_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_bytes_exception_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_bytes_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_unicode_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_utf8_logging\n=================== 9 errors, 8 passed in 0.47s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba\n.................\ncollected 17 items\n\n=================================== FAILURES ===================================\n__________ LoggingOptionTest.test_disable_code_none __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 200, in test_disable_code_none\n    self.assertFalse(self.logs_present(\nAssertionError: True is not false\n__________ LoggingOptionTest.test_disable_command_line_case_insensitive __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 192, in test_disable_command_line_case_insensitive\n    self.assertFalse(self.logs_present('parse_command_line()',\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 178, in logs_present\n    self.assertEqual(proc.returncode, 0, 'process failed: %r' % stdout)\nAssertionError: 1 != 0 : process failed: b'Traceback (most recent call last):\\n  File \"<string>\", line 1, in <module>\\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/tornado/options.py\", line 511, in parse_command_line\\n    return options.parse_command_line(args, final=final)\\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/tornado/options.py\", line 252, in parse_command_line\\n    self.run_parse_callbacks()\\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/tornado/options.py\", line 313, in run_parse_callbacks\\n    callback()\\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/tornado/stack_context.py\", line 275, in null_wrapper\\n    return fn(*args, **kwargs)\\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/tornado/log.py\", line 191, in enable_pretty_logging\\n    logger.setLevel(getattr(logging, options.logging.upper()))\\nAttributeError: module \\'logging\\' has no attribute \\'NONE\\'\\n'\n\n=================================== ERRORS =====================================\n__________ LogFormatterTest.test_basic_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 89, in test_basic_logging\n    self.assertEqual(self.get_output(), b\"foo\")\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:88]\\x02 foo'\n__________ LogFormatterTest.test_bytes_exception_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 116, in test_bytes_exception_logging\n    output = self.get_output()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:113]\\x02 caught exception\\n    Traceback (most recent call last):\\n      File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 111, in test_bytes_exception_logging\\n        raise Exception(b\\'\\\\xe9\\')\\n    Exception: b\\'\\\\xe9\\''\n__________ LogFormatterTest.test_bytes_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 95, in test_bytes_logging\n    self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:31 test_1:94]\\x02 b'\\\\xe9'\"\n__________ LogFormatterTest.test_utf8_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 107, in test_utf8_logging\n    self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:31 test_1:98]\\x02 b'\\\\xc3\\\\xa9'\"\n__________ UnicodeLogFormatterTest.test_basic_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 89, in test_basic_logging\n    self.assertEqual(self.get_output(), b\"foo\")\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:88]\\x02 foo'\n__________ UnicodeLogFormatterTest.test_bytes_exception_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 116, in test_bytes_exception_logging\n    output = self.get_output()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:113]\\x02 caught exception\\n    Traceback (most recent call last):\\n      File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 111, in test_bytes_exception_logging\\n        raise Exception(b\\'\\\\xe9\\')\\n    Exception: b\\'\\\\xe9\\''\n__________ UnicodeLogFormatterTest.test_bytes_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 95, in test_bytes_logging\n    self.assertEqual(self.get_output(), utf8(repr(b\"\\xe9\")))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:31 test_1:94]\\x02 b'\\\\xe9'\"\n__________ UnicodeLogFormatterTest.test_unicode_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 131, in test_unicode_logging\n    self.assertEqual(self.get_output(), utf8(u(\"\\u00e9\")))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b'\\x01[E 250101 13:53:31 test_1:130]\\x02 \\xc3\\xa9'\n__________ UnicodeLogFormatterTest.test_utf8_logging __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 107, in test_utf8_logging\n    self.assertEqual(self.get_output(), utf8(repr(utf8(u(\"\\u00e9\")))))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2dc57c57b1a4e64e0c10796718f54f0792968dba/r2e_tests/test_1.py\", line 85, in get_output\n    raise Exception(\"output didn't match regex: %r\" % line)\nException: output didn't match regex: b\"\\x01[E 250101 13:53:31 test_1:98]\\x02 b'\\\\xc3\\\\xa9'\"\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::EnablePrettyLoggingTest::test_log_file\nERROR r2e_tests.test_1::LogFormatterTest::test_basic_logging\nERROR r2e_tests.test_1::LogFormatterTest::test_bytes_exception_logging\nERROR r2e_tests.test_1::LogFormatterTest::test_bytes_logging\nERROR r2e_tests.test_1::LogFormatterTest::test_utf8_logging\nPASSED r2e_tests.test_1::LoggingOptionTest::test_default\nFAILED r2e_tests.test_1::LoggingOptionTest::test_disable_code_none\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_code_string\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_command_line\nFAILED r2e_tests.test_1::LoggingOptionTest::test_disable_command_line_case_insensitive\nPASSED r2e_tests.test_1::LoggingOptionTest::test_disable_override\nPASSED r2e_tests.test_1::LoggingOptionTest::test_tornado_default\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_basic_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_bytes_exception_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_bytes_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_unicode_logging\nERROR r2e_tests.test_1::UnicodeLogFormatterTest::test_utf8_logging\n=================== 2 failed, 9 errors, 6 passed in 0.36s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/log.py tornado/options.py tornado/test/log_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:**
Cannot Disable Tornado Logging with `None` or Case-Insensitive Flags

**Description:**
Attempting to disable Tornado's default logging configuration by setting `options.logging` to `None` in code or using a case-insensitive command line flag does not work as expected. This leads to errors when the application tries to set the logging level.

**Example Code:**

_Disabling logging in code:_
```python
from tornado.options import options, parse_command_line
import logging

options.logging = None
parse_command_line()

logging.info("This log should not appear")
```

_Disabling logging via command line:_
```
--logging=None
```

**Expected Behavior:**
Setting `options.logging` to `None` or using a case-insensitive flag like `--logging=None` should disable Tornado's default logging configuration, allowing developers to manage logging manually without encountering errors.

**Actual Behavior:**
The application raises an `AttributeError` because it incorrectly processes the `None` value or case-insensitive flag, attempting to set the logging level to a non-existent attribute `NONE` in the logging module:
```
AttributeError: module 'logging' has no attribute 'NONE'
```

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/log.py
#!/usr/bin/env python
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Logging support for Tornado.

Tornado uses three logger streams:

* ``tornado.access``: Per-request logging for Tornado's HTTP servers (and
  potentially other servers in the future)
* ``tornado.application``: Logging of errors from application code (i.e.
  uncaught exceptions from callbacks)
* ``tornado.general``: General-purpose logging, including any errors
  or warnings from Tornado itself.

These streams may be configured independently using the standard library's
`logging` module.  For example, you may wish to send ``tornado.access`` logs
to a separate file for analysis.
"""
from __future__ import absolute_import, division, print_function, with_statement

import logging
import logging.handlers
import sys

from tornado.escape import _unicode
from tornado.util import unicode_type, basestring_type

try:
    import curses
except ImportError:
    curses = None

# Logger objects for internal tornado use
access_log = logging.getLogger("tornado.access")
app_log = logging.getLogger("tornado.application")
gen_log = logging.getLogger("tornado.general")


def _stderr_supports_color():
    color = False
    if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color


def _safe_unicode(s):
    try:
        return _unicode(s)
    except UnicodeDecodeError:
        return repr(s)


class LogFormatter(logging.Formatter):
    """Log formatter used in Tornado.

    Key features of this formatter are:

    * Color support when logging to a terminal that supports it.
    * Timestamps on every log line.
    * Robust against str/bytes encoding problems.

    This formatter is enabled automatically by
    `tornado.options.parse_command_line` (unless ``--logging=none`` is
    used).
    """
    DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'
    DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'
    DEFAULT_COLORS = {
        logging.DEBUG:      4,  # Blue
        logging.INFO:       2,  # Green
        logging.WARNING:    3,  # Yellow
        logging.ERROR:      1,  # Red
    }

    def __init__(self, color=True, fmt=DEFAULT_FORMAT,
                 datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):
        r"""
        :arg bool color: Enables color support.
        :arg string fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(end_color)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg string datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``fmt`` and ``datefmt`` arguments.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._fmt = fmt

        self._colors = {}
        if color and _stderr_supports_color():
            # The curses module has some str/bytes confusion in
            # python3.  Until version 3.2.3, most methods return
            # bytes, but only accept strings.  In addition, we want to
            # output these strings with the logging module, which
            # works with unicode strings.  The explicit calls to
            # unicode() below are harmless in python2 but will do the
            # right conversion in python 3.
            fg_color = (curses.tigetstr("setaf") or
                        curses.tigetstr("setf") or "")
            if (3, 0) < sys.version_info < (3, 2, 3):
                fg_color = unicode_type(fg_color, "ascii")

            for levelno, code in colors.items():
                self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii")
            self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
        else:
            self._normal = ''

    def format(self, record):
        try:
            message = record.getMessage()
            assert isinstance(message, basestring_type)  # guaranteed by logging
            # Encoding notes:  The logging module prefers to work with character
            # strings, but only enforces that log messages are instances of
            # basestring.  In python 2, non-ascii bytestrings will make
            # their way through the logging framework until they blow up with
            # an unhelpful decoding error (with this formatter it happens
            # when we attach the prefix, but there are other opportunities for
            # exceptions further along in the framework).
            #
            # If a byte string makes it this far, convert it to unicode to
            # ensure it will make it out to the logs.  Use repr() as a fallback
            # to ensure that all byte strings can be converted successfully,
            # but don't do it by default so we don't add extra quotes to ascii
            # bytestrings.  This is a bit of a hacky place to do this, but
            # it's worth it since the encoding errors that would otherwise
            # result are so useless (and tornado is fond of using utf8-encoded
            # byte strings whereever possible).
            record.message = _safe_unicode(message)
        except Exception as e:
            record.message = "Bad message (%r): %r" % (e, record.__dict__)

        record.asctime = self.formatTime(record, self.datefmt)

        if record.levelno in self._colors:
            record.color = self._colors[record.levelno]
            record.end_color = self._normal
        else:
            record.color = record.end_color = ''

        formatted = self._fmt % record.__dict__

        if record.exc_info:
            if not record.exc_text:
                record.exc_text = self.formatException(record.exc_info)
        if record.exc_text:
            # exc_text contains multiple lines.  We need to _safe_unicode
            # each line separately so that non-utf8 bytes don't cause
            # all the newlines to turn into '\n'.
            lines = [formatted.rstrip()]
            lines.extend(_safe_unicode(ln) for ln in record.exc_text.split('\n'))
            formatted = '\n'.join(lines)
        return formatted.replace("\n", "\n    ")


def enable_pretty_logging(options=None, logger=None):
    """Turns on formatted logging output as configured.

    This is called automaticaly by `tornado.options.parse_command_line`
    and `tornado.options.parse_config_file`.
    """
    if options is None:
        from tornado.options import options
    if options.logging == 'none':
        return
    if logger is None:
        logger = logging.getLogger()
    logger.setLevel(getattr(logging, options.logging.upper()))
    if options.log_file_prefix:
        channel = logging.handlers.RotatingFileHandler(
            filename=options.log_file_prefix,
            maxBytes=options.log_file_max_size,
            backupCount=options.log_file_num_backups)
        channel.setFormatter(LogFormatter(color=False))
        logger.addHandler(channel)

    if (options.log_to_stderr or
            (options.log_to_stderr is None and not logger.handlers)):
        # Set up color if we are in a tty and curses is installed
        channel = logging.StreamHandler()
        channel.setFormatter(LogFormatter())
        logger.addHandler(channel)


def define_logging_options(options=None):
    if options is None:
        # late import to prevent cycle
        from tornado.options import options
    options.define("logging", default="info",
                   help=("Set the Python log level. If 'none', tornado won't touch the "
                         "logging configuration."),
                   metavar="debug|info|warning|error|none")
    options.define("log_to_stderr", type=bool, default=None,
                   help=("Send log output to stderr (colorized if possible). "
                         "By default use stderr if --log_file_prefix is not set and "
                         "no other logging is configured."))
    options.define("log_file_prefix", type=str, default=None, metavar="PATH",
                   help=("Path prefix for log files. "
                         "Note that if you are running multiple tornado processes, "
                         "log_file_prefix must be different for each of them (e.g. "
                         "include the port number)"))
    options.define("log_file_max_size", type=int, default=100 * 1000 * 1000,
                   help="max size of log files before rollover")
    options.define("log_file_num_backups", type=int, default=10,
                   help="number of log files to keep")

    options.add_parse_callback(enable_pretty_logging)


### tornado/options.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""A command line parsing module that lets modules define their own options.

Each module defines its own options which are added to the global
option namespace, e.g.::

    from tornado.options import define, options

    define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
    define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
           help="Main user memcache servers")

    def connect():
        db = database.Connection(options.mysql_host)
        ...

The ``main()`` method of your application does not need to be aware of all of
the options used throughout your program; they are all automatically loaded
when the modules are loaded.  However, all modules that define options
must have been imported before the command line is parsed.

Your ``main()`` method can parse the command line or parse a config file with
either::

    tornado.options.parse_command_line()
    # or
    tornado.options.parse_config_file("/etc/server.conf")

Command line formats are what you would expect (``--myoption=myvalue``).
Config files are just Python files. Global names become options, e.g.::

    myoption = "myvalue"
    myotheroption = "myothervalue"

We support `datetimes <datetime.datetime>`, `timedeltas
<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to
`define`). We also accept multi-value options. See the documentation for
`define()` below.

`tornado.options.options` is a singleton instance of `OptionParser`, and
the top-level functions in this module (`define`, `parse_command_line`, etc)
simply call methods on it.  You may create additional `OptionParser`
instances to define isolated sets of options, such as for subcommands.
"""

from __future__ import absolute_import, division, print_function, with_statement

import datetime
import numbers
import re
import sys
import os
import textwrap

from tornado.escape import _unicode
from tornado.log import define_logging_options
from tornado import stack_context
from tornado.util import basestring_type, exec_in


class Error(Exception):
    """Exception raised by errors in the options module."""
    pass


class OptionParser(object):
    """A collection of options, a dictionary with object-like access.

    Normally accessed via static functions in the `tornado.options` module,
    which reference a global instance.
    """
    def __init__(self):
        # we have to use self.__dict__ because we override setattr.
        self.__dict__['_options'] = {}
        self.__dict__['_parse_callbacks'] = []
        self.define("help", type=bool, help="show this help information",
                    callback=self._help_callback)

    def __getattr__(self, name):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].value()
        raise AttributeError("Unrecognized option %r" % name)

    def __setattr__(self, name, value):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].set(value)
        raise AttributeError("Unrecognized option %r" % name)

    def __iter__(self):
        return iter(self._options)

    def __getitem__(self, item):
        return self._options[item].value()

    def items(self):
        """A sequence of (name, value) pairs.

        .. versionadded:: 3.1
        """
        return [(name, opt.value()) for name, opt in self._options.items()]

    def groups(self):
        """The set of option-groups created by ``define``.

        .. versionadded:: 3.1
        """
        return set(opt.group_name for opt in self._options.values())

    def group_dict(self, group):
        """The names and values of options in a group.

        Useful for copying options into Application settings::

            from tornado.options import define, parse_command_line, options

            define('template_path', group='application')
            define('static_path', group='application')

            parse_command_line()

            application = Application(
                handlers, **options.group_dict('application'))

        .. versionadded:: 3.1
        """
        return dict(
            (name, opt.value()) for name, opt in self._options.items()
            if not group or group == opt.group_name)

    def as_dict(self):
        """The names and values of all options.

        .. versionadded:: 3.1
        """
        return dict(
            (name, opt.value()) for name, opt in self._options.items())

    def define(self, name, default=None, type=None, help=None, metavar=None,
               multiple=False, group=None, callback=None):
        """Defines a new command line option.

        If ``type`` is given (one of str, float, int, datetime, or timedelta)
        or can be inferred from the ``default``, we parse the command line
        arguments based on the given type. If ``multiple`` is True, we accept
        comma-separated values, and the option value is always a list.

        For multi-value integers, we also accept the syntax ``x:y``, which
        turns into ``range(x, y)`` - very useful for long integer ranges.

        ``help`` and ``metavar`` are used to construct the
        automatically generated command line help string. The help
        message is formatted like::

           --name=METAVAR      help string

        ``group`` is used to group the defined options in logical
        groups. By default, command line options are grouped by the
        file in which they are defined.

        Command line option names must be unique globally. They can be parsed
        from the command line with `parse_command_line` or parsed from a
        config file with `parse_config_file`.

        If a ``callback`` is given, it will be run with the new value whenever
        the option is changed.  This can be used to combine command-line
        and file-based options::

            define("config", type=str, help="path to config file",
                   callback=lambda path: parse_config_file(path, final=False))

        With this definition, options in the file specified by ``--config`` will
        override options set earlier on the command line, but can be overridden
        by later flags.
        """
        if name in self._options:
            raise Error("Option %r already defined in %s" %
                        (name, self._options[name].file_name))
        frame = sys._getframe(0)
        options_file = frame.f_code.co_filename
        file_name = frame.f_back.f_code.co_filename
        if file_name == options_file:
            file_name = ""
        if type is None:
            if not multiple and default is not None:
                type = default.__class__
            else:
                type = str
        if group:
            group_name = group
        else:
            group_name = file_name
        self._options[name] = _Option(name, file_name=file_name,
                                      default=default, type=type, help=help,
                                      metavar=metavar, multiple=multiple,
                                      group_name=group_name,
                                      callback=callback)

    def parse_command_line(self, args=None, final=True):
        """Parses all options given on the command line (defaults to
        `sys.argv`).

        Note that ``args[0]`` is ignored since it is the program name
        in `sys.argv`.

        We return a list of all arguments that are not parsed as options.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        if args is None:
            args = sys.argv
        remaining = []
        for i in range(1, len(args)):
            # All things after the last option are command line arguments
            if not args[i].startswith("-"):
                remaining = args[i:]
                break
            if args[i] == "--":
                remaining = args[i + 1:]
                break
            arg = args[i].lstrip("-")
            name, equals, value = arg.partition("=")
            name = name.replace('-', '_')
            if not name in self._options:
                self.print_help()
                raise Error('Unrecognized command line option: %r' % name)
            option = self._options[name]
            if not equals:
                if option.type == bool:
                    value = "true"
                else:
                    raise Error('Option %r requires a value' % name)
            option.parse(value)

        if final:
            self.run_parse_callbacks()

        return remaining

    def parse_config_file(self, path, final=True):
        """Parses and loads the Python config file at the given path.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        config = {}
        with open(path) as f:
            exec_in(f.read(), config, config)
        for name in config:
            if name in self._options:
                self._options[name].set(config[name])

        if final:
            self.run_parse_callbacks()

    def print_help(self, file=None):
        """Prints all the command line options to stderr (or another file)."""
        if file is None:
            file = sys.stderr
        print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
        print("\nOptions:\n", file=file)
        by_group = {}
        for option in self._options.values():
            by_group.setdefault(option.group_name, []).append(option)

        for filename, o in sorted(by_group.items()):
            if filename:
                print("\n%s options:\n" % os.path.normpath(filename), file=file)
            o.sort(key=lambda option: option.name)
            for option in o:
                prefix = option.name
                if option.metavar:
                    prefix += "=" + option.metavar
                description = option.help or ""
                if option.default is not None and option.default != '':
                    description += " (default %s)" % option.default
                lines = textwrap.wrap(description, 79 - 35)
                if len(prefix) > 30 or len(lines) == 0:
                    lines.insert(0, '')
                print("  --%-30s %s" % (prefix, lines[0]), file=file)
                for line in lines[1:]:
                    print("%-34s %s" % (' ', line), file=file)
        print(file=file)

    def _help_callback(self, value):
        if value:
            self.print_help()
            sys.exit(0)

    def add_parse_callback(self, callback):
        """Adds a parse callback, to be invoked when option parsing is done."""
        self._parse_callbacks.append(stack_context.wrap(callback))

    def run_parse_callbacks(self):
        for callback in self._parse_callbacks:
            callback()

    def mockable(self):
        """Returns a wrapper around self that is compatible with
        `mock.patch <unittest.mock.patch>`.

        The `mock.patch <unittest.mock.patch>` function (included in
        the standard library `unittest.mock` package since Python 3.3,
        or in the third-party ``mock`` package for older versions of
        Python) is incompatible with objects like ``options`` that
        override ``__getattr__`` and ``__setattr__``.  This function
        returns an object that can be used with `mock.patch.object
        <unittest.mock.patch.object>` to modify option values::

            with mock.patch.object(options.mockable(), 'name', value):
                assert options.name == value
        """
        return _Mockable(self)


class _Mockable(object):
    """`mock.patch` compatible wrapper for `OptionParser`.

    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
    the attribute it set instead of setting a new one (assuming that
    the object does not catpure ``__setattr__``, so the patch
    created a new attribute in ``__dict__``).

    _Mockable's getattr and setattr pass through to the underlying
    OptionParser, and delattr undoes the effect of a previous setattr.
    """
    def __init__(self, options):
        # Modify __dict__ directly to bypass __setattr__
        self.__dict__['_options'] = options
        self.__dict__['_originals'] = {}

    def __getattr__(self, name):
        return getattr(self._options, name)

    def __setattr__(self, name, value):
        assert name not in self._originals, "don't reuse mockable objects"
        self._originals[name] = getattr(self._options, name)
        setattr(self._options, name, value)

    def __delattr__(self, name):
        setattr(self._options, name, self._originals.pop(name))


class _Option(object):
    def __init__(self, name, default=None, type=basestring_type, help=None,
                 metavar=None, multiple=False, file_name=None, group_name=None,
                 callback=None):
        if default is None and multiple:
            default = []
        self.name = name
        self.type = type
        self.help = help
        self.metavar = metavar
        self.multiple = multiple
        self.file_name = file_name
        self.group_name = group_name
        self.callback = callback
        self.default = default
        self._value = None

    def value(self):
        return self.default if self._value is None else self._value

    def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()

    def set(self, value):
        if self.multiple:
            if not isinstance(value, list):
                raise Error("Option %r is required to be a list of %s" %
                            (self.name, self.type.__name__))
            for item in value:
                if item is not None and not isinstance(item, self.type):
                    raise Error("Option %r is required to be a list of %s" %
                                (self.name, self.type.__name__))
        else:
            if value is not None and not isinstance(value, self.type):
                raise Error("Option %r is required to be a %s (%s given)" %
                            (self.name, self.type.__name__, type(value)))
        self._value = value
        if self.callback is not None:
            self.callback(self._value)

    # Supported date/time formats in our options
    _DATETIME_FORMATS = [
        "%a %b %d %H:%M:%S %Y",
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%dT%H:%M",
        "%Y%m%d %H:%M:%S",
        "%Y%m%d %H:%M",
        "%Y-%m-%d",
        "%Y%m%d",
        "%H:%M:%S",
        "%H:%M",
    ]

    def _parse_datetime(self, value):
        for format in self._DATETIME_FORMATS:
            try:
                return datetime.datetime.strptime(value, format)
            except ValueError:
                pass
        raise Error('Unrecognized date/time format: %r' % value)

    _TIMEDELTA_ABBREVS = [
        ('hours', ['h']),
        ('minutes', ['m', 'min']),
        ('seconds', ['s', 'sec']),
        ('milliseconds', ['ms']),
        ('microseconds', ['us']),
        ('days', ['d']),
        ('weeks', ['w']),
    ]

    _TIMEDELTA_ABBREV_DICT = dict(
        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS
        for abbrev in abbrevs)

    _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'

    _TIMEDELTA_PATTERN = re.compile(
        r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE)

    def _parse_timedelta(self, value):
        try:
            sum = datetime.timedelta()
            start = 0
            while start < len(value):
                m = self._TIMEDELTA_PATTERN.match(value, start)
                if not m:
                    raise Exception()
                num = float(m.group(1))
                units = m.group(2) or 'seconds'
                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)
                sum += datetime.timedelta(**{units: num})
                start = m.end()
            return sum
        except Exception:
            raise

    def _parse_bool(self, value):
        return value.lower() not in ("false", "0", "f")

    def _parse_string(self, value):
        return _unicode(value)


options = OptionParser()
"""Global options object.

All defined options are available as attributes on this object.
"""


def define(name, default=None, type=None, help=None, metavar=None,
           multiple=False, group=None, callback=None):
    """Defines an option in the global namespace.

    See `OptionParser.define`.
    """
    return options.define(name, default=default, type=type, help=help,
                          metavar=metavar, multiple=multiple, group=group,
                          callback=callback)


def parse_command_line(args=None, final=True):
    """Parses global options from the command line.

    See `OptionParser.parse_command_line`.
    """
    return options.parse_command_line(args, final=final)


def parse_config_file(path, final=True):
    """Parses global options from a config file.

    See `OptionParser.parse_config_file`.
    """
    return options.parse_config_file(path, final=final)


def print_help(file=None):
    """Prints all the command line options to stderr (or another file).

    See `OptionParser.print_help`.
    """
    return options.print_help(file)


def add_parse_callback(callback):
    """Adds a parse callback, to be invoked when option parsing is done.

    See `OptionParser.add_parse_callback`
    """
    options.add_parse_callback(callback)


# Default options
define_logging_options(options)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]

**Title:**
Cannot Disable Tornado Logging with `None` or Case-Insensitive Flags

**Description:**
Attempting to disable Tornado's default logging configuration by setting `options.logging` to `None` in code or using a case-insensitive command line flag does not work as expected. This leads to errors when the application tries to set the logging level.

**Example Code:**

_Disabling logging in code:_
```python
from tornado.options import options, parse_command_line
import logging

options.logging = None
parse_command_line()

logging.info("This log should not appear")
```

_Disabling logging via command line:_
```
--logging=None
```

**Expected Behavior:**
Setting `options.logging` to `None` or using a case-insensitive flag like `--logging=None` should disable Tornado's default logging configuration, allowing developers to manage logging manually without encountering errors.

**Actual Behavior:**
The application raises an `AttributeError` because it incorrectly processes the `None` value or case-insensitive flag, attempting to set the logging level to a non-existent attribute `NONE` in the logging module:
```
AttributeError: module 'logging' has no attribute 'NONE'
```

[/ISSUE]
{
    "EnablePrettyLoggingTest.test_log_file": "PASSED",
    "LogFormatterTest.test_basic_logging": "ERROR",
    "LogFormatterTest.test_bytes_exception_logging": "ERROR",
    "LogFormatterTest.test_bytes_logging": "ERROR",
    "LogFormatterTest.test_utf8_logging": "ERROR",
    "LoggingOptionTest.test_default": "PASSED",
    "LoggingOptionTest.test_disable_code_none": "PASSED",
    "LoggingOptionTest.test_disable_code_string": "PASSED",
    "LoggingOptionTest.test_disable_command_line": "PASSED",
    "LoggingOptionTest.test_disable_command_line_case_insensitive": "PASSED",
    "LoggingOptionTest.test_disable_override": "PASSED",
    "LoggingOptionTest.test_tornado_default": "PASSED",
    "UnicodeLogFormatterTest.test_basic_logging": "ERROR",
    "UnicodeLogFormatterTest.test_bytes_exception_logging": "ERROR",
    "UnicodeLogFormatterTest.test_bytes_logging": "ERROR",
    "UnicodeLogFormatterTest.test_unicode_logging": "ERROR",
    "UnicodeLogFormatterTest.test_utf8_logging": "ERROR"
}
diff --git a/tornado/log.py b/tornado/log.py
index 36c3dd40..306220cd 100644
--- a/tornado/log.py
+++ b/tornado/log.py
@@ -184,7 +184,7 @@ def enable_pretty_logging(options=None, logger=None):
     """
     if options is None:
         from tornado.options import options
-    if options.logging == 'none':
+    if options.logging is None or options.logging.lower() == 'none':
         return
     if logger is None:
         logger = logging.getLogger()
diff --git a/tornado/options.py b/tornado/options.py
index 1105c0e9..fa9c269e 100644
--- a/tornado/options.py
+++ b/tornado/options.py
@@ -56,6 +56,18 @@ We support `datetimes <datetime.datetime>`, `timedeltas
 the top-level functions in this module (`define`, `parse_command_line`, etc)
 simply call methods on it.  You may create additional `OptionParser`
 instances to define isolated sets of options, such as for subcommands.
+
+.. note::
+
+   By default, several options are defined that will configure the
+   standard `logging` module when `parse_command_line` or `parse_config_file`
+   are called.  If you want Tornado to leave the logging configuration
+   alone so you can manage it yourself, either pass ``--logging=none``
+   on the command line or do the following to disable it in code::
+
+       from tornado.options import options, parse_command_line
+       options.logging = None
+       parse_command_line()
 """
 
 from __future__ import absolute_import, division, print_function, with_statement
@@ -360,6 +372,8 @@ class _Mockable(object):
 
 
 class _Option(object):
+    UNSET = object()
+
     def __init__(self, name, default=None, type=basestring_type, help=None,
                  metavar=None, multiple=False, file_name=None, group_name=None,
                  callback=None):
@@ -374,10 +388,10 @@ class _Option(object):
         self.group_name = group_name
         self.callback = callback
         self.default = default
-        self._value = None
+        self._value = _Option.UNSET
 
     def value(self):
-        return self.default if self._value is None else self._value
+        return self.default if self._value is _Option.UNSET else self._value
 
     def parse(self, value):
         _parse = {

{"tornado/log.py": "#!/usr/bin/env python\n#\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"Logging support for Tornado.\n\nTornado uses three logger streams:\n\n* ``tornado.access``: Per-request logging for Tornado's HTTP servers (and\n  potentially other servers in the future)\n* ``tornado.application``: Logging of errors from application code (i.e.\n  uncaught exceptions from callbacks)\n* ``tornado.general``: General-purpose logging, including any errors\n  or warnings from Tornado itself.\n\nThese streams may be configured independently using the standard library's\n`logging` module.  For example, you may wish to send ``tornado.access`` logs\nto a separate file for analysis.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport logging\nimport logging.handlers\nimport sys\n\nfrom tornado.escape import _unicode\nfrom tornado.util import unicode_type, basestring_type\n\ntry:\n    import curses\nexcept ImportError:\n    curses = None\n\n# Logger objects for internal tornado use\naccess_log = logging.getLogger(\"tornado.access\")\napp_log = logging.getLogger(\"tornado.application\")\ngen_log = logging.getLogger(\"tornado.general\")\n\n\ndef _stderr_supports_color():\n    color = False\n    if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():\n        try:\n            curses.setupterm()\n            if curses.tigetnum(\"colors\") > 0:\n                color = True\n        except Exception:\n            pass\n    return color\n\n\ndef _safe_unicode(s):\n    try:\n        return _unicode(s)\n    except UnicodeDecodeError:\n        return repr(s)\n\n\nclass LogFormatter(logging.Formatter):\n    \"\"\"Log formatter used in Tornado.\n\n    Key features of this formatter are:\n\n    * Color support when logging to a terminal that supports it.\n    * Timestamps on every log line.\n    * Robust against str/bytes encoding problems.\n\n    This formatter is enabled automatically by\n    `tornado.options.parse_command_line` (unless ``--logging=none`` is\n    used).\n    \"\"\"\n    DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'\n    DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'\n    DEFAULT_COLORS = {\n        logging.DEBUG:      4,  # Blue\n        logging.INFO:       2,  # Green\n        logging.WARNING:    3,  # Yellow\n        logging.ERROR:      1,  # Red\n    }\n\n    def __init__(self, color=True, fmt=DEFAULT_FORMAT,\n                 datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):\n        r\"\"\"\n        :arg bool color: Enables color support.\n        :arg string fmt: Log message format.\n          It will be applied to the attributes dict of log records. The\n          text between ``%(color)s`` and ``%(end_color)s`` will be colored\n          depending on the level if color support is on.\n        :arg dict colors: color mappings from logging level to terminal color\n          code\n        :arg string datefmt: Datetime format.\n          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n\n        .. versionchanged:: 3.2\n\n           Added ``fmt`` and ``datefmt`` arguments.\n        \"\"\"\n        logging.Formatter.__init__(self, datefmt=datefmt)\n        self._fmt = fmt\n\n        self._colors = {}\n        if color and _stderr_supports_color():\n            # The curses module has some str/bytes confusion in\n            # python3.  Until version 3.2.3, most methods return\n            # bytes, but only accept strings.  In addition, we want to\n            # output these strings with the logging module, which\n            # works with unicode strings.  The explicit calls to\n            # unicode() below are harmless in python2 but will do the\n            # right conversion in python 3.\n            fg_color = (curses.tigetstr(\"setaf\") or\n                        curses.tigetstr(\"setf\") or \"\")\n            if (3, 0) < sys.version_info < (3, 2, 3):\n                fg_color = unicode_type(fg_color, \"ascii\")\n\n            for levelno, code in colors.items():\n                self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), \"ascii\")\n            self._normal = unicode_type(curses.tigetstr(\"sgr0\"), \"ascii\")\n        else:\n            self._normal = ''\n\n    def format(self, record):\n        try:\n            message = record.getMessage()\n            assert isinstance(message, basestring_type)  # guaranteed by logging\n            # Encoding notes:  The logging module prefers to work with character\n            # strings, but only enforces that log messages are instances of\n            # basestring.  In python 2, non-ascii bytestrings will make\n            # their way through the logging framework until they blow up with\n            # an unhelpful decoding error (with this formatter it happens\n            # when we attach the prefix, but there are other opportunities for\n            # exceptions further along in the framework).\n            #\n            # If a byte string makes it this far, convert it to unicode to\n            # ensure it will make it out to the logs.  Use repr() as a fallback\n            # to ensure that all byte strings can be converted successfully,\n            # but don't do it by default so we don't add extra quotes to ascii\n            # bytestrings.  This is a bit of a hacky place to do this, but\n            # it's worth it since the encoding errors that would otherwise\n            # result are so useless (and tornado is fond of using utf8-encoded\n            # byte strings whereever possible).\n            record.message = _safe_unicode(message)\n        except Exception as e:\n            record.message = \"Bad message (%r): %r\" % (e, record.__dict__)\n\n        record.asctime = self.formatTime(record, self.datefmt)\n\n        if record.levelno in self._colors:\n            record.color = self._colors[record.levelno]\n            record.end_color = self._normal\n        else:\n            record.color = record.end_color = ''\n\n        formatted = self._fmt % record.__dict__\n\n        if record.exc_info:\n            if not record.exc_text:\n                record.exc_text = self.formatException(record.exc_info)\n        if record.exc_text:\n            # exc_text contains multiple lines.  We need to _safe_unicode\n            # each line separately so that non-utf8 bytes don't cause\n            # all the newlines to turn into '\\n'.\n            lines = [formatted.rstrip()]\n            lines.extend(_safe_unicode(ln) for ln in record.exc_text.split('\\n'))\n            formatted = '\\n'.join(lines)\n        return formatted.replace(\"\\n\", \"\\n    \")\n\n\ndef enable_pretty_logging(options=None, logger=None):\n    \"\"\"Turns on formatted logging output as configured.\n\n    This is called automaticaly by `tornado.options.parse_command_line`\n    and `tornado.options.parse_config_file`.\n    \"\"\"\n    if options is None:\n        from tornado.options import options\n    if options.logging == 'none':\n        return\n    if logger is None:\n        logger = logging.getLogger()\n    logger.setLevel(getattr(logging, options.logging.upper()))\n    if options.log_file_prefix:\n        channel = logging.handlers.RotatingFileHandler(\n            filename=options.log_file_prefix,\n            maxBytes=options.log_file_max_size,\n            backupCount=options.log_file_num_backups)\n        channel.setFormatter(LogFormatter(color=False))\n        logger.addHandler(channel)\n\n    if (options.log_to_stderr or\n            (options.log_to_stderr is None and not logger.handlers)):\n        # Set up color if we are in a tty and curses is installed\n        channel = logging.StreamHandler()\n        channel.setFormatter(LogFormatter())\n        logger.addHandler(channel)\n\n\ndef define_logging_options(options=None):\n    if options is None:\n        # late import to prevent cycle\n        from tornado.options import options\n    options.define(\"logging\", default=\"info\",\n                   help=(\"Set the Python log level. If 'none', tornado won't touch the \"\n                         \"logging configuration.\"),\n                   metavar=\"debug|info|warning|error|none\")\n    options.define(\"log_to_stderr\", type=bool, default=None,\n                   help=(\"Send log output to stderr (colorized if possible). \"\n                         \"By default use stderr if --log_file_prefix is not set and \"\n                         \"no other logging is configured.\"))\n    options.define(\"log_file_prefix\", type=str, default=None, metavar=\"PATH\",\n                   help=(\"Path prefix for log files. \"\n                         \"Note that if you are running multiple tornado processes, \"\n                         \"log_file_prefix must be different for each of them (e.g. \"\n                         \"include the port number)\"))\n    options.define(\"log_file_max_size\", type=int, default=100 * 1000 * 1000,\n                   help=\"max size of log files before rollover\")\n    options.define(\"log_file_num_backups\", type=int, default=10,\n                   help=\"number of log files to keep\")\n\n    options.add_parse_callback(enable_pretty_logging)\n", "tornado/options.py": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A command line parsing module that lets modules define their own options.\n\nEach module defines its own options which are added to the global\noption namespace, e.g.::\n\n    from tornado.options import define, options\n\n    define(\"mysql_host\", default=\"127.0.0.1:3306\", help=\"Main user DB\")\n    define(\"memcache_hosts\", default=\"127.0.0.1:11011\", multiple=True,\n           help=\"Main user memcache servers\")\n\n    def connect():\n        db = database.Connection(options.mysql_host)\n        ...\n\nThe ``main()`` method of your application does not need to be aware of all of\nthe options used throughout your program; they are all automatically loaded\nwhen the modules are loaded.  However, all modules that define options\nmust have been imported before the command line is parsed.\n\nYour ``main()`` method can parse the command line or parse a config file with\neither::\n\n    tornado.options.parse_command_line()\n    # or\n    tornado.options.parse_config_file(\"/etc/server.conf\")\n\nCommand line formats are what you would expect (``--myoption=myvalue``).\nConfig files are just Python files. Global names become options, e.g.::\n\n    myoption = \"myvalue\"\n    myotheroption = \"myothervalue\"\n\nWe support `datetimes <datetime.datetime>`, `timedeltas\n<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to\n`define`). We also accept multi-value options. See the documentation for\n`define()` below.\n\n`tornado.options.options` is a singleton instance of `OptionParser`, and\nthe top-level functions in this module (`define`, `parse_command_line`, etc)\nsimply call methods on it.  You may create additional `OptionParser`\ninstances to define isolated sets of options, such as for subcommands.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport datetime\nimport numbers\nimport re\nimport sys\nimport os\nimport textwrap\n\nfrom tornado.escape import _unicode\nfrom tornado.log import define_logging_options\nfrom tornado import stack_context\nfrom tornado.util import basestring_type, exec_in\n\n\nclass Error(Exception):\n    \"\"\"Exception raised by errors in the options module.\"\"\"\n    pass\n\n\nclass OptionParser(object):\n    \"\"\"A collection of options, a dictionary with object-like access.\n\n    Normally accessed via static functions in the `tornado.options` module,\n    which reference a global instance.\n    \"\"\"\n    def __init__(self):\n        # we have to use self.__dict__ because we override setattr.\n        self.__dict__['_options'] = {}\n        self.__dict__['_parse_callbacks'] = []\n        self.define(\"help\", type=bool, help=\"show this help information\",\n                    callback=self._help_callback)\n\n    def __getattr__(self, name):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].value()\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __setattr__(self, name, value):\n        if isinstance(self._options.get(name), _Option):\n            return self._options[name].set(value)\n        raise AttributeError(\"Unrecognized option %r\" % name)\n\n    def __iter__(self):\n        return iter(self._options)\n\n    def __getitem__(self, item):\n        return self._options[item].value()\n\n    def items(self):\n        \"\"\"A sequence of (name, value) pairs.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return [(name, opt.value()) for name, opt in self._options.items()]\n\n    def groups(self):\n        \"\"\"The set of option-groups created by ``define``.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return set(opt.group_name for opt in self._options.values())\n\n    def group_dict(self, group):\n        \"\"\"The names and values of options in a group.\n\n        Useful for copying options into Application settings::\n\n            from tornado.options import define, parse_command_line, options\n\n            define('template_path', group='application')\n            define('static_path', group='application')\n\n            parse_command_line()\n\n            application = Application(\n                handlers, **options.group_dict('application'))\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items()\n            if not group or group == opt.group_name)\n\n    def as_dict(self):\n        \"\"\"The names and values of all options.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        return dict(\n            (name, opt.value()) for name, opt in self._options.items())\n\n    def define(self, name, default=None, type=None, help=None, metavar=None,\n               multiple=False, group=None, callback=None):\n        \"\"\"Defines a new command line option.\n\n        If ``type`` is given (one of str, float, int, datetime, or timedelta)\n        or can be inferred from the ``default``, we parse the command line\n        arguments based on the given type. If ``multiple`` is True, we accept\n        comma-separated values, and the option value is always a list.\n\n        For multi-value integers, we also accept the syntax ``x:y``, which\n        turns into ``range(x, y)`` - very useful for long integer ranges.\n\n        ``help`` and ``metavar`` are used to construct the\n        automatically generated command line help string. The help\n        message is formatted like::\n\n           --name=METAVAR      help string\n\n        ``group`` is used to group the defined options in logical\n        groups. By default, command line options are grouped by the\n        file in which they are defined.\n\n        Command line option names must be unique globally. They can be parsed\n        from the command line with `parse_command_line` or parsed from a\n        config file with `parse_config_file`.\n\n        If a ``callback`` is given, it will be run with the new value whenever\n        the option is changed.  This can be used to combine command-line\n        and file-based options::\n\n            define(\"config\", type=str, help=\"path to config file\",\n                   callback=lambda path: parse_config_file(path, final=False))\n\n        With this definition, options in the file specified by ``--config`` will\n        override options set earlier on the command line, but can be overridden\n        by later flags.\n        \"\"\"\n        if name in self._options:\n            raise Error(\"Option %r already defined in %s\" %\n                        (name, self._options[name].file_name))\n        frame = sys._getframe(0)\n        options_file = frame.f_code.co_filename\n        file_name = frame.f_back.f_code.co_filename\n        if file_name == options_file:\n            file_name = \"\"\n        if type is None:\n            if not multiple and default is not None:\n                type = default.__class__\n            else:\n                type = str\n        if group:\n            group_name = group\n        else:\n            group_name = file_name\n        self._options[name] = _Option(name, file_name=file_name,\n                                      default=default, type=type, help=help,\n                                      metavar=metavar, multiple=multiple,\n                                      group_name=group_name,\n                                      callback=callback)\n\n    def parse_command_line(self, args=None, final=True):\n        \"\"\"Parses all options given on the command line (defaults to\n        `sys.argv`).\n\n        Note that ``args[0]`` is ignored since it is the program name\n        in `sys.argv`.\n\n        We return a list of all arguments that are not parsed as options.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        if args is None:\n            args = sys.argv\n        remaining = []\n        for i in range(1, len(args)):\n            # All things after the last option are command line arguments\n            if not args[i].startswith(\"-\"):\n                remaining = args[i:]\n                break\n            if args[i] == \"--\":\n                remaining = args[i + 1:]\n                break\n            arg = args[i].lstrip(\"-\")\n            name, equals, value = arg.partition(\"=\")\n            name = name.replace('-', '_')\n            if not name in self._options:\n                self.print_help()\n                raise Error('Unrecognized command line option: %r' % name)\n            option = self._options[name]\n            if not equals:\n                if option.type == bool:\n                    value = \"true\"\n                else:\n                    raise Error('Option %r requires a value' % name)\n            option.parse(value)\n\n        if final:\n            self.run_parse_callbacks()\n\n        return remaining\n\n    def parse_config_file(self, path, final=True):\n        \"\"\"Parses and loads the Python config file at the given path.\n\n        If ``final`` is ``False``, parse callbacks will not be run.\n        This is useful for applications that wish to combine configurations\n        from multiple sources.\n        \"\"\"\n        config = {}\n        with open(path) as f:\n            exec_in(f.read(), config, config)\n        for name in config:\n            if name in self._options:\n                self._options[name].set(config[name])\n\n        if final:\n            self.run_parse_callbacks()\n\n    def print_help(self, file=None):\n        \"\"\"Prints all the command line options to stderr (or another file).\"\"\"\n        if file is None:\n            file = sys.stderr\n        print(\"Usage: %s [OPTIONS]\" % sys.argv[0], file=file)\n        print(\"\\nOptions:\\n\", file=file)\n        by_group = {}\n        for option in self._options.values():\n            by_group.setdefault(option.group_name, []).append(option)\n\n        for filename, o in sorted(by_group.items()):\n            if filename:\n                print(\"\\n%s options:\\n\" % os.path.normpath(filename), file=file)\n            o.sort(key=lambda option: option.name)\n            for option in o:\n                prefix = option.name\n                if option.metavar:\n                    prefix += \"=\" + option.metavar\n                description = option.help or \"\"\n                if option.default is not None and option.default != '':\n                    description += \" (default %s)\" % option.default\n                lines = textwrap.wrap(description, 79 - 35)\n                if len(prefix) > 30 or len(lines) == 0:\n                    lines.insert(0, '')\n                print(\"  --%-30s %s\" % (prefix, lines[0]), file=file)\n                for line in lines[1:]:\n                    print(\"%-34s %s\" % (' ', line), file=file)\n        print(file=file)\n\n    def _help_callback(self, value):\n        if value:\n            self.print_help()\n            sys.exit(0)\n\n    def add_parse_callback(self, callback):\n        \"\"\"Adds a parse callback, to be invoked when option parsing is done.\"\"\"\n        self._parse_callbacks.append(stack_context.wrap(callback))\n\n    def run_parse_callbacks(self):\n        for callback in self._parse_callbacks:\n            callback()\n\n    def mockable(self):\n        \"\"\"Returns a wrapper around self that is compatible with\n        `mock.patch <unittest.mock.patch>`.\n\n        The `mock.patch <unittest.mock.patch>` function (included in\n        the standard library `unittest.mock` package since Python 3.3,\n        or in the third-party ``mock`` package for older versions of\n        Python) is incompatible with objects like ``options`` that\n        override ``__getattr__`` and ``__setattr__``.  This function\n        returns an object that can be used with `mock.patch.object\n        <unittest.mock.patch.object>` to modify option values::\n\n            with mock.patch.object(options.mockable(), 'name', value):\n                assert options.name == value\n        \"\"\"\n        return _Mockable(self)\n\n\nclass _Mockable(object):\n    \"\"\"`mock.patch` compatible wrapper for `OptionParser`.\n\n    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``\n    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete\n    the attribute it set instead of setting a new one (assuming that\n    the object does not catpure ``__setattr__``, so the patch\n    created a new attribute in ``__dict__``).\n\n    _Mockable's getattr and setattr pass through to the underlying\n    OptionParser, and delattr undoes the effect of a previous setattr.\n    \"\"\"\n    def __init__(self, options):\n        # Modify __dict__ directly to bypass __setattr__\n        self.__dict__['_options'] = options\n        self.__dict__['_originals'] = {}\n\n    def __getattr__(self, name):\n        return getattr(self._options, name)\n\n    def __setattr__(self, name, value):\n        assert name not in self._originals, \"don't reuse mockable objects\"\n        self._originals[name] = getattr(self._options, name)\n        setattr(self._options, name, value)\n\n    def __delattr__(self, name):\n        setattr(self._options, name, self._originals.pop(name))\n\n\nclass _Option(object):\n    def __init__(self, name, default=None, type=basestring_type, help=None,\n                 metavar=None, multiple=False, file_name=None, group_name=None,\n                 callback=None):\n        if default is None and multiple:\n            default = []\n        self.name = name\n        self.type = type\n        self.help = help\n        self.metavar = metavar\n        self.multiple = multiple\n        self.file_name = file_name\n        self.group_name = group_name\n        self.callback = callback\n        self.default = default\n        self._value = None\n\n    def value(self):\n        return self.default if self._value is None else self._value\n\n    def parse(self, value):\n        _parse = {\n            datetime.datetime: self._parse_datetime,\n            datetime.timedelta: self._parse_timedelta,\n            bool: self._parse_bool,\n            basestring_type: self._parse_string,\n        }.get(self.type, self.type)\n        if self.multiple:\n            self._value = []\n            for part in value.split(\",\"):\n                if issubclass(self.type, numbers.Integral):\n                    # allow ranges of the form X:Y (inclusive at both ends)\n                    lo, _, hi = part.partition(\":\")\n                    lo = _parse(lo)\n                    hi = _parse(hi) if hi else lo\n                    self._value.extend(range(lo, hi + 1))\n                else:\n                    self._value.append(_parse(part))\n        else:\n            self._value = _parse(value)\n        if self.callback is not None:\n            self.callback(self._value)\n        return self.value()\n\n    def set(self, value):\n        if self.multiple:\n            if not isinstance(value, list):\n                raise Error(\"Option %r is required to be a list of %s\" %\n                            (self.name, self.type.__name__))\n            for item in value:\n                if item is not None and not isinstance(item, self.type):\n                    raise Error(\"Option %r is required to be a list of %s\" %\n                                (self.name, self.type.__name__))\n        else:\n            if value is not None and not isinstance(value, self.type):\n                raise Error(\"Option %r is required to be a %s (%s given)\" %\n                            (self.name, self.type.__name__, type(value)))\n        self._value = value\n        if self.callback is not None:\n            self.callback(self._value)\n\n    # Supported date/time formats in our options\n    _DATETIME_FORMATS = [\n        \"%a %b %d %H:%M:%S %Y\",\n        \"%Y-%m-%d %H:%M:%S\",\n        \"%Y-%m-%d %H:%M\",\n        \"%Y-%m-%dT%H:%M\",\n        \"%Y%m%d %H:%M:%S\",\n        \"%Y%m%d %H:%M\",\n        \"%Y-%m-%d\",\n        \"%Y%m%d\",\n        \"%H:%M:%S\",\n        \"%H:%M\",\n    ]\n\n    def _parse_datetime(self, value):\n        for format in self._DATETIME_FORMATS:\n            try:\n                return datetime.datetime.strptime(value, format)\n            except ValueError:\n                pass\n        raise Error('Unrecognized date/time format: %r' % value)\n\n    _TIMEDELTA_ABBREVS = [\n        ('hours', ['h']),\n        ('minutes', ['m', 'min']),\n        ('seconds', ['s', 'sec']),\n        ('milliseconds', ['ms']),\n        ('microseconds', ['us']),\n        ('days', ['d']),\n        ('weeks', ['w']),\n    ]\n\n    _TIMEDELTA_ABBREV_DICT = dict(\n        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS\n        for abbrev in abbrevs)\n\n    _FLOAT_PATTERN = r'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?'\n\n    _TIMEDELTA_PATTERN = re.compile(\n        r'\\s*(%s)\\s*(\\w*)\\s*' % _FLOAT_PATTERN, re.IGNORECASE)\n\n    def _parse_timedelta(self, value):\n        try:\n            sum = datetime.timedelta()\n            start = 0\n            while start < len(value):\n                m = self._TIMEDELTA_PATTERN.match(value, start)\n                if not m:\n                    raise Exception()\n                num = float(m.group(1))\n                units = m.group(2) or 'seconds'\n                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)\n                sum += datetime.timedelta(**{units: num})\n                start = m.end()\n            return sum\n        except Exception:\n            raise\n\n    def _parse_bool(self, value):\n        return value.lower() not in (\"false\", \"0\", \"f\")\n\n    def _parse_string(self, value):\n        return _unicode(value)\n\n\noptions = OptionParser()\n\"\"\"Global options object.\n\nAll defined options are available as attributes on this object.\n\"\"\"\n\n\ndef define(name, default=None, type=None, help=None, metavar=None,\n           multiple=False, group=None, callback=None):\n    \"\"\"Defines an option in the global namespace.\n\n    See `OptionParser.define`.\n    \"\"\"\n    return options.define(name, default=default, type=type, help=help,\n                          metavar=metavar, multiple=multiple, group=group,\n                          callback=callback)\n\n\ndef parse_command_line(args=None, final=True):\n    \"\"\"Parses global options from the command line.\n\n    See `OptionParser.parse_command_line`.\n    \"\"\"\n    return options.parse_command_line(args, final=final)\n\n\ndef parse_config_file(path, final=True):\n    \"\"\"Parses global options from a config file.\n\n    See `OptionParser.parse_config_file`.\n    \"\"\"\n    return options.parse_config_file(path, final=final)\n\n\ndef print_help(file=None):\n    \"\"\"Prints all the command line options to stderr (or another file).\n\n    See `OptionParser.print_help`.\n    \"\"\"\n    return options.print_help(file)\n\n\ndef add_parse_callback(callback):\n    \"\"\"Adds a parse callback, to be invoked when option parsing is done.\n\n    See `OptionParser.add_parse_callback`\n    \"\"\"\n    options.add_parse_callback(callback)\n\n\n# Default options\ndefine_logging_options(options)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:**
Cannot Disable Tornado Logging with `None` or Case-Insensitive Flags

**Description:**
Attempting to disable Tornado's default logging configuration by setting `options.logging` to `None` in code or using a case-insensitive command line flag does not work as expected. This leads to errors when the application tries to set the logging level.

**Example Code:**

_Disabling logging in code:_
```python
from tornado.options import options, parse_command_line
import logging

options.logging = None
parse_command_line()

logging.info("This log should not appear")
```

_Disabling logging via command line:_
```
--logging=None
```

**Expected Behavior:**
Setting `options.logging` to `None` or using a case-insensitive flag like `--logging=None` should disable Tornado's default logging configuration, allowing developers to manage logging manually without encountering errors.

**Actual Behavior:**
The application raises an `AttributeError` because it incorrectly processes the `None` value or case-insensitive flag, attempting to set the logging level to a non-existent attribute `NONE` in the logging module:
```
AttributeError: module 'logging' has no attribute 'NONE'
```

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/log.py
#!/usr/bin/env python
#
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Logging support for Tornado.

Tornado uses three logger streams:

* ``tornado.access``: Per-request logging for Tornado's HTTP servers (and
  potentially other servers in the future)
* ``tornado.application``: Logging of errors from application code (i.e.
  uncaught exceptions from callbacks)
* ``tornado.general``: General-purpose logging, including any errors
  or warnings from Tornado itself.

These streams may be configured independently using the standard library's
`logging` module.  For example, you may wish to send ``tornado.access`` logs
to a separate file for analysis.
"""
from __future__ import absolute_import, division, print_function, with_statement

import logging
import logging.handlers
import sys

from tornado.escape import _unicode
from tornado.util import unicode_type, basestring_type

try:
    import curses
except ImportError:
    curses = None

# Logger objects for internal tornado use
access_log = logging.getLogger("tornado.access")
app_log = logging.getLogger("tornado.application")
gen_log = logging.getLogger("tornado.general")


def _stderr_supports_color():
    color = False
    if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
        try:
            curses.setupterm()
            if curses.tigetnum("colors") > 0:
                color = True
        except Exception:
            pass
    return color


def _safe_unicode(s):
    try:
        return _unicode(s)
    except UnicodeDecodeError:
        return repr(s)


class LogFormatter(logging.Formatter):
    """Log formatter used in Tornado.

    Key features of this formatter are:

    * Color support when logging to a terminal that supports it.
    * Timestamps on every log line.
    * Robust against str/bytes encoding problems.

    This formatter is enabled automatically by
    `tornado.options.parse_command_line` (unless ``--logging=none`` is
    used).
    """
    DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s'
    DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S'
    DEFAULT_COLORS = {
        logging.DEBUG:      4,  # Blue
        logging.INFO:       2,  # Green
        logging.WARNING:    3,  # Yellow
        logging.ERROR:      1,  # Red
    }

    def __init__(self, color=True, fmt=DEFAULT_FORMAT,
                 datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS):
        r"""
        :arg bool color: Enables color support.
        :arg string fmt: Log message format.
          It will be applied to the attributes dict of log records. The
          text between ``%(color)s`` and ``%(end_color)s`` will be colored
          depending on the level if color support is on.
        :arg dict colors: color mappings from logging level to terminal color
          code
        :arg string datefmt: Datetime format.
          Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.

        .. versionchanged:: 3.2

           Added ``fmt`` and ``datefmt`` arguments.
        """
        logging.Formatter.__init__(self, datefmt=datefmt)
        self._fmt = fmt

        self._colors = {}
        if color and _stderr_supports_color():
            # The curses module has some str/bytes confusion in
            # python3.  Until version 3.2.3, most methods return
            # bytes, but only accept strings.  In addition, we want to
            # output these strings with the logging module, which
            # works with unicode strings.  The explicit calls to
            # unicode() below are harmless in python2 but will do the
            # right conversion in python 3.
            fg_color = (curses.tigetstr("setaf") or
                        curses.tigetstr("setf") or "")
            if (3, 0) < sys.version_info < (3, 2, 3):
                fg_color = unicode_type(fg_color, "ascii")

            for levelno, code in colors.items():
                self._colors[levelno] = unicode_type(curses.tparm(fg_color, code), "ascii")
            self._normal = unicode_type(curses.tigetstr("sgr0"), "ascii")
        else:
            self._normal = ''

    def format(self, record):
        try:
            message = record.getMessage()
            assert isinstance(message, basestring_type)  # guaranteed by logging
            # Encoding notes:  The logging module prefers to work with character
            # strings, but only enforces that log messages are instances of
            # basestring.  In python 2, non-ascii bytestrings will make
            # their way through the logging framework until they blow up with
            # an unhelpful decoding error (with this formatter it happens
            # when we attach the prefix, but there are other opportunities for
            # exceptions further along in the framework).
            #
            # If a byte string makes it this far, convert it to unicode to
            # ensure it will make it out to the logs.  Use repr() as a fallback
            # to ensure that all byte strings can be converted successfully,
            # but don't do it by default so we don't add extra quotes to ascii
            # bytestrings.  This is a bit of a hacky place to do this, but
            # it's worth it since the encoding errors that would otherwise
            # result are so useless (and tornado is fond of using utf8-encoded
            # byte strings whereever possible).
            record.message = _safe_unicode(message)
        except Exception as e:
            record.message = "Bad message (%r): %r" % (e, record.__dict__)

        record.asctime = self.formatTime(record, self.datefmt)

        if record.levelno in self._colors:
            record.color = self._colors[record.levelno]
            record.end_color = self._normal
        else:
            record.color = record.end_color = ''

        formatted = self._fmt % record.__dict__

        if record.exc_info:
            if not record.exc_text:
                record.exc_text = self.formatException(record.exc_info)
        if record.exc_text:
            # exc_text contains multiple lines.  We need to _safe_unicode
            # each line separately so that non-utf8 bytes don't cause
            # all the newlines to turn into '\n'.
            lines = [formatted.rstrip()]
            lines.extend(_safe_unicode(ln) for ln in record.exc_text.split('\n'))
            formatted = '\n'.join(lines)
        return formatted.replace("\n", "\n    ")


def enable_pretty_logging(options=None, logger=None):
    """Turns on formatted logging output as configured.

    This is called automaticaly by `tornado.options.parse_command_line`
    and `tornado.options.parse_config_file`.
    """
    if options is None:
        from tornado.options import options
    if options.logging == 'none':
        return
    if logger is None:
        logger = logging.getLogger()
    logger.setLevel(getattr(logging, options.logging.upper()))
    if options.log_file_prefix:
        channel = logging.handlers.RotatingFileHandler(
            filename=options.log_file_prefix,
            maxBytes=options.log_file_max_size,
            backupCount=options.log_file_num_backups)
        channel.setFormatter(LogFormatter(color=False))
        logger.addHandler(channel)

    if (options.log_to_stderr or
            (options.log_to_stderr is None and not logger.handlers)):
        # Set up color if we are in a tty and curses is installed
        channel = logging.StreamHandler()
        channel.setFormatter(LogFormatter())
        logger.addHandler(channel)


def define_logging_options(options=None):
    if options is None:
        # late import to prevent cycle
        from tornado.options import options
    options.define("logging", default="info",
                   help=("Set the Python log level. If 'none', tornado won't touch the "
                         "logging configuration."),
                   metavar="debug|info|warning|error|none")
    options.define("log_to_stderr", type=bool, default=None,
                   help=("Send log output to stderr (colorized if possible). "
                         "By default use stderr if --log_file_prefix is not set and "
                         "no other logging is configured."))
    options.define("log_file_prefix", type=str, default=None, metavar="PATH",
                   help=("Path prefix for log files. "
                         "Note that if you are running multiple tornado processes, "
                         "log_file_prefix must be different for each of them (e.g. "
                         "include the port number)"))
    options.define("log_file_max_size", type=int, default=100 * 1000 * 1000,
                   help="max size of log files before rollover")
    options.define("log_file_num_backups", type=int, default=10,
                   help="number of log files to keep")

    options.add_parse_callback(enable_pretty_logging)


### tornado/options.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""A command line parsing module that lets modules define their own options.

Each module defines its own options which are added to the global
option namespace, e.g.::

    from tornado.options import define, options

    define("mysql_host", default="127.0.0.1:3306", help="Main user DB")
    define("memcache_hosts", default="127.0.0.1:11011", multiple=True,
           help="Main user memcache servers")

    def connect():
        db = database.Connection(options.mysql_host)
        ...

The ``main()`` method of your application does not need to be aware of all of
the options used throughout your program; they are all automatically loaded
when the modules are loaded.  However, all modules that define options
must have been imported before the command line is parsed.

Your ``main()`` method can parse the command line or parse a config file with
either::

    tornado.options.parse_command_line()
    # or
    tornado.options.parse_config_file("/etc/server.conf")

Command line formats are what you would expect (``--myoption=myvalue``).
Config files are just Python files. Global names become options, e.g.::

    myoption = "myvalue"
    myotheroption = "myothervalue"

We support `datetimes <datetime.datetime>`, `timedeltas
<datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to
`define`). We also accept multi-value options. See the documentation for
`define()` below.

`tornado.options.options` is a singleton instance of `OptionParser`, and
the top-level functions in this module (`define`, `parse_command_line`, etc)
simply call methods on it.  You may create additional `OptionParser`
instances to define isolated sets of options, such as for subcommands.
"""

from __future__ import absolute_import, division, print_function, with_statement

import datetime
import numbers
import re
import sys
import os
import textwrap

from tornado.escape import _unicode
from tornado.log import define_logging_options
from tornado import stack_context
from tornado.util import basestring_type, exec_in


class Error(Exception):
    """Exception raised by errors in the options module."""
    pass


class OptionParser(object):
    """A collection of options, a dictionary with object-like access.

    Normally accessed via static functions in the `tornado.options` module,
    which reference a global instance.
    """
    def __init__(self):
        # we have to use self.__dict__ because we override setattr.
        self.__dict__['_options'] = {}
        self.__dict__['_parse_callbacks'] = []
        self.define("help", type=bool, help="show this help information",
                    callback=self._help_callback)

    def __getattr__(self, name):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].value()
        raise AttributeError("Unrecognized option %r" % name)

    def __setattr__(self, name, value):
        if isinstance(self._options.get(name), _Option):
            return self._options[name].set(value)
        raise AttributeError("Unrecognized option %r" % name)

    def __iter__(self):
        return iter(self._options)

    def __getitem__(self, item):
        return self._options[item].value()

    def items(self):
        """A sequence of (name, value) pairs.

        .. versionadded:: 3.1
        """
        return [(name, opt.value()) for name, opt in self._options.items()]

    def groups(self):
        """The set of option-groups created by ``define``.

        .. versionadded:: 3.1
        """
        return set(opt.group_name for opt in self._options.values())

    def group_dict(self, group):
        """The names and values of options in a group.

        Useful for copying options into Application settings::

            from tornado.options import define, parse_command_line, options

            define('template_path', group='application')
            define('static_path', group='application')

            parse_command_line()

            application = Application(
                handlers, **options.group_dict('application'))

        .. versionadded:: 3.1
        """
        return dict(
            (name, opt.value()) for name, opt in self._options.items()
            if not group or group == opt.group_name)

    def as_dict(self):
        """The names and values of all options.

        .. versionadded:: 3.1
        """
        return dict(
            (name, opt.value()) for name, opt in self._options.items())

    def define(self, name, default=None, type=None, help=None, metavar=None,
               multiple=False, group=None, callback=None):
        """Defines a new command line option.

        If ``type`` is given (one of str, float, int, datetime, or timedelta)
        or can be inferred from the ``default``, we parse the command line
        arguments based on the given type. If ``multiple`` is True, we accept
        comma-separated values, and the option value is always a list.

        For multi-value integers, we also accept the syntax ``x:y``, which
        turns into ``range(x, y)`` - very useful for long integer ranges.

        ``help`` and ``metavar`` are used to construct the
        automatically generated command line help string. The help
        message is formatted like::

           --name=METAVAR      help string

        ``group`` is used to group the defined options in logical
        groups. By default, command line options are grouped by the
        file in which they are defined.

        Command line option names must be unique globally. They can be parsed
        from the command line with `parse_command_line` or parsed from a
        config file with `parse_config_file`.

        If a ``callback`` is given, it will be run with the new value whenever
        the option is changed.  This can be used to combine command-line
        and file-based options::

            define("config", type=str, help="path to config file",
                   callback=lambda path: parse_config_file(path, final=False))

        With this definition, options in the file specified by ``--config`` will
        override options set earlier on the command line, but can be overridden
        by later flags.
        """
        if name in self._options:
            raise Error("Option %r already defined in %s" %
                        (name, self._options[name].file_name))
        frame = sys._getframe(0)
        options_file = frame.f_code.co_filename
        file_name = frame.f_back.f_code.co_filename
        if file_name == options_file:
            file_name = ""
        if type is None:
            if not multiple and default is not None:
                type = default.__class__
            else:
                type = str
        if group:
            group_name = group
        else:
            group_name = file_name
        self._options[name] = _Option(name, file_name=file_name,
                                      default=default, type=type, help=help,
                                      metavar=metavar, multiple=multiple,
                                      group_name=group_name,
                                      callback=callback)

    def parse_command_line(self, args=None, final=True):
        """Parses all options given on the command line (defaults to
        `sys.argv`).

        Note that ``args[0]`` is ignored since it is the program name
        in `sys.argv`.

        We return a list of all arguments that are not parsed as options.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        if args is None:
            args = sys.argv
        remaining = []
        for i in range(1, len(args)):
            # All things after the last option are command line arguments
            if not args[i].startswith("-"):
                remaining = args[i:]
                break
            if args[i] == "--":
                remaining = args[i + 1:]
                break
            arg = args[i].lstrip("-")
            name, equals, value = arg.partition("=")
            name = name.replace('-', '_')
            if not name in self._options:
                self.print_help()
                raise Error('Unrecognized command line option: %r' % name)
            option = self._options[name]
            if not equals:
                if option.type == bool:
                    value = "true"
                else:
                    raise Error('Option %r requires a value' % name)
            option.parse(value)

        if final:
            self.run_parse_callbacks()

        return remaining

    def parse_config_file(self, path, final=True):
        """Parses and loads the Python config file at the given path.

        If ``final`` is ``False``, parse callbacks will not be run.
        This is useful for applications that wish to combine configurations
        from multiple sources.
        """
        config = {}
        with open(path) as f:
            exec_in(f.read(), config, config)
        for name in config:
            if name in self._options:
                self._options[name].set(config[name])

        if final:
            self.run_parse_callbacks()

    def print_help(self, file=None):
        """Prints all the command line options to stderr (or another file)."""
        if file is None:
            file = sys.stderr
        print("Usage: %s [OPTIONS]" % sys.argv[0], file=file)
        print("\nOptions:\n", file=file)
        by_group = {}
        for option in self._options.values():
            by_group.setdefault(option.group_name, []).append(option)

        for filename, o in sorted(by_group.items()):
            if filename:
                print("\n%s options:\n" % os.path.normpath(filename), file=file)
            o.sort(key=lambda option: option.name)
            for option in o:
                prefix = option.name
                if option.metavar:
                    prefix += "=" + option.metavar
                description = option.help or ""
                if option.default is not None and option.default != '':
                    description += " (default %s)" % option.default
                lines = textwrap.wrap(description, 79 - 35)
                if len(prefix) > 30 or len(lines) == 0:
                    lines.insert(0, '')
                print("  --%-30s %s" % (prefix, lines[0]), file=file)
                for line in lines[1:]:
                    print("%-34s %s" % (' ', line), file=file)
        print(file=file)

    def _help_callback(self, value):
        if value:
            self.print_help()
            sys.exit(0)

    def add_parse_callback(self, callback):
        """Adds a parse callback, to be invoked when option parsing is done."""
        self._parse_callbacks.append(stack_context.wrap(callback))

    def run_parse_callbacks(self):
        for callback in self._parse_callbacks:
            callback()

    def mockable(self):
        """Returns a wrapper around self that is compatible with
        `mock.patch <unittest.mock.patch>`.

        The `mock.patch <unittest.mock.patch>` function (included in
        the standard library `unittest.mock` package since Python 3.3,
        or in the third-party ``mock`` package for older versions of
        Python) is incompatible with objects like ``options`` that
        override ``__getattr__`` and ``__setattr__``.  This function
        returns an object that can be used with `mock.patch.object
        <unittest.mock.patch.object>` to modify option values::

            with mock.patch.object(options.mockable(), 'name', value):
                assert options.name == value
        """
        return _Mockable(self)


class _Mockable(object):
    """`mock.patch` compatible wrapper for `OptionParser`.

    As of ``mock`` version 1.0.1, when an object uses ``__getattr__``
    hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete
    the attribute it set instead of setting a new one (assuming that
    the object does not catpure ``__setattr__``, so the patch
    created a new attribute in ``__dict__``).

    _Mockable's getattr and setattr pass through to the underlying
    OptionParser, and delattr undoes the effect of a previous setattr.
    """
    def __init__(self, options):
        # Modify __dict__ directly to bypass __setattr__
        self.__dict__['_options'] = options
        self.__dict__['_originals'] = {}

    def __getattr__(self, name):
        return getattr(self._options, name)

    def __setattr__(self, name, value):
        assert name not in self._originals, "don't reuse mockable objects"
        self._originals[name] = getattr(self._options, name)
        setattr(self._options, name, value)

    def __delattr__(self, name):
        setattr(self._options, name, self._originals.pop(name))


class _Option(object):
    def __init__(self, name, default=None, type=basestring_type, help=None,
                 metavar=None, multiple=False, file_name=None, group_name=None,
                 callback=None):
        if default is None and multiple:
            default = []
        self.name = name
        self.type = type
        self.help = help
        self.metavar = metavar
        self.multiple = multiple
        self.file_name = file_name
        self.group_name = group_name
        self.callback = callback
        self.default = default
        self._value = None

    def value(self):
        return self.default if self._value is None else self._value

    def parse(self, value):
        _parse = {
            datetime.datetime: self._parse_datetime,
            datetime.timedelta: self._parse_timedelta,
            bool: self._parse_bool,
            basestring_type: self._parse_string,
        }.get(self.type, self.type)
        if self.multiple:
            self._value = []
            for part in value.split(","):
                if issubclass(self.type, numbers.Integral):
                    # allow ranges of the form X:Y (inclusive at both ends)
                    lo, _, hi = part.partition(":")
                    lo = _parse(lo)
                    hi = _parse(hi) if hi else lo
                    self._value.extend(range(lo, hi + 1))
                else:
                    self._value.append(_parse(part))
        else:
            self._value = _parse(value)
        if self.callback is not None:
            self.callback(self._value)
        return self.value()

    def set(self, value):
        if self.multiple:
            if not isinstance(value, list):
                raise Error("Option %r is required to be a list of %s" %
                            (self.name, self.type.__name__))
            for item in value:
                if item is not None and not isinstance(item, self.type):
                    raise Error("Option %r is required to be a list of %s" %
                                (self.name, self.type.__name__))
        else:
            if value is not None and not isinstance(value, self.type):
                raise Error("Option %r is required to be a %s (%s given)" %
                            (self.name, self.type.__name__, type(value)))
        self._value = value
        if self.callback is not None:
            self.callback(self._value)

    # Supported date/time formats in our options
    _DATETIME_FORMATS = [
        "%a %b %d %H:%M:%S %Y",
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d %H:%M",
        "%Y-%m-%dT%H:%M",
        "%Y%m%d %H:%M:%S",
        "%Y%m%d %H:%M",
        "%Y-%m-%d",
        "%Y%m%d",
        "%H:%M:%S",
        "%H:%M",
    ]

    def _parse_datetime(self, value):
        for format in self._DATETIME_FORMATS:
            try:
                return datetime.datetime.strptime(value, format)
            except ValueError:
                pass
        raise Error('Unrecognized date/time format: %r' % value)

    _TIMEDELTA_ABBREVS = [
        ('hours', ['h']),
        ('minutes', ['m', 'min']),
        ('seconds', ['s', 'sec']),
        ('milliseconds', ['ms']),
        ('microseconds', ['us']),
        ('days', ['d']),
        ('weeks', ['w']),
    ]

    _TIMEDELTA_ABBREV_DICT = dict(
        (abbrev, full) for full, abbrevs in _TIMEDELTA_ABBREVS
        for abbrev in abbrevs)

    _FLOAT_PATTERN = r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'

    _TIMEDELTA_PATTERN = re.compile(
        r'\s*(%s)\s*(\w*)\s*' % _FLOAT_PATTERN, re.IGNORECASE)

    def _parse_timedelta(self, value):
        try:
            sum = datetime.timedelta()
            start = 0
            while start < len(value):
                m = self._TIMEDELTA_PATTERN.match(value, start)
                if not m:
                    raise Exception()
                num = float(m.group(1))
                units = m.group(2) or 'seconds'
                units = self._TIMEDELTA_ABBREV_DICT.get(units, units)
                sum += datetime.timedelta(**{units: num})
                start = m.end()
            return sum
        except Exception:
            raise

    def _parse_bool(self, value):
        return value.lower() not in ("false", "0", "f")

    def _parse_string(self, value):
        return _unicode(value)


options = OptionParser()
"""Global options object.

All defined options are available as attributes on this object.
"""


def define(name, default=None, type=None, help=None, metavar=None,
           multiple=False, group=None, callback=None):
    """Defines an option in the global namespace.

    See `OptionParser.define`.
    """
    return options.define(name, default=default, type=type, help=help,
                          metavar=metavar, multiple=multiple, group=group,
                          callback=callback)


def parse_command_line(args=None, final=True):
    """Parses global options from the command line.

    See `OptionParser.parse_command_line`.
    """
    return options.parse_command_line(args, final=final)


def parse_config_file(path, final=True):
    """Parses global options from a config file.

    See `OptionParser.parse_config_file`.
    """
    return options.parse_config_file(path, final=final)


def print_help(file=None):
    """Prints all the command line options to stderr (or another file).

    See `OptionParser.print_help`.
    """
    return options.print_help(file)


def add_parse_callback(callback):
    """Adds a parse callback, to be invoked when option parsing is done.

    See `OptionParser.add_parse_callback`
    """
    options.add_parse_callback(callback)


# Default options
define_logging_options(options)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user