",
+ loader: Optional["BaseLoader"] = None,
+ compress_whitespace: Union[bool, _UnsetMarker] = _UNSET,
+ autoescape: Optional[Union[str, _UnsetMarker]] = _UNSET,
+ whitespace: Optional[str] = None,
+ ) -> None:
+ """Construct a Template.
+
+ :arg str template_string: the contents of the template file.
+ :arg str name: the filename from which the template was loaded
+ (used for error message).
+ :arg tornado.template.BaseLoader loader: the `~tornado.template.BaseLoader` responsible
+ for this template, used to resolve ``{% include %}`` and ``{% extend %}`` directives.
+ :arg bool compress_whitespace: Deprecated since Tornado 4.3.
+ Equivalent to ``whitespace="single"`` if true and
+ ``whitespace="all"`` if false.
+ :arg str autoescape: The name of a function in the template
+ namespace, or ``None`` to disable escaping by default.
+ :arg str whitespace: A string specifying treatment of whitespace;
+ see `filter_whitespace` for options.
+
+ .. versionchanged:: 4.3
+ Added ``whitespace`` parameter; deprecated ``compress_whitespace``.
+ """
+ self.name = escape.native_str(name)
+
+ if compress_whitespace is not _UNSET:
+ # Convert deprecated compress_whitespace (bool) to whitespace (str).
+ if whitespace is not None:
+ raise Exception("cannot set both whitespace and compress_whitespace")
+ whitespace = "single" if compress_whitespace else "all"
+ if whitespace is None:
+ if loader and loader.whitespace:
+ whitespace = loader.whitespace
+ else:
+ # Whitespace defaults by filename.
+ if name.endswith(".html") or name.endswith(".js"):
+ whitespace = "single"
+ else:
+ whitespace = "all"
+ # Validate the whitespace setting.
+ assert whitespace is not None
+ filter_whitespace(whitespace, "")
+
+ if not isinstance(autoescape, _UnsetMarker):
+ self.autoescape = autoescape # type: Optional[str]
+ elif loader:
+ self.autoescape = loader.autoescape
+ else:
+ self.autoescape = _DEFAULT_AUTOESCAPE
+
+ self.namespace = loader.namespace if loader else {}
+ reader = _TemplateReader(name, escape.native_str(template_string), whitespace)
+ self.file = _File(self, _parse(reader, self))
+ self.code = self._generate_python(loader)
+ self.loader = loader
+ try:
+ # Under python2.5, the fake filename used here must match
+ # the module name used in __name__ below.
+ # The dont_inherit flag prevents template.py's future imports
+ # from being applied to the generated code.
+ self.compiled = compile(
+ escape.to_unicode(self.code),
+ "%s.generated.py" % self.name.replace(".", "_"),
+ "exec",
+ dont_inherit=True,
+ )
+ except Exception:
+ formatted_code = _format_code(self.code).rstrip()
+ app_log.error("%s code:\n%s", self.name, formatted_code)
+ raise
+
+ def generate(self, **kwargs: Any) -> bytes:
+ """Generate this template with the given arguments."""
+ namespace = {
+ "escape": escape.xhtml_escape,
+ "xhtml_escape": escape.xhtml_escape,
+ "url_escape": escape.url_escape,
+ "json_encode": escape.json_encode,
+ "squeeze": escape.squeeze,
+ "linkify": escape.linkify,
+ "datetime": datetime,
+ "_tt_utf8": escape.utf8, # for internal use
+ "_tt_string_types": (unicode_type, bytes),
+ # __name__ and __loader__ allow the traceback mechanism to find
+ # the generated source code.
+ "__name__": self.name.replace(".", "_"),
+ "__loader__": ObjectDict(get_source=lambda name: self.code),
+ }
+ namespace.update(self.namespace)
+ namespace.update(kwargs)
+ exec_in(self.compiled, namespace)
+ execute = typing.cast(Callable[[], bytes], namespace["_tt_execute"])
+ # Clear the traceback module's cache of source data now that
+ # we've generated a new template (mainly for this module's
+ # unittests, where different tests reuse the same name).
+ linecache.clearcache()
+ return execute()
+
+ def _generate_python(self, loader: Optional["BaseLoader"]) -> str:
+ buffer = StringIO()
+ try:
+ # named_blocks maps from names to _NamedBlock objects
+ named_blocks = {} # type: Dict[str, _NamedBlock]
+ ancestors = self._get_ancestors(loader)
+ ancestors.reverse()
+ for ancestor in ancestors:
+ ancestor.find_named_blocks(loader, named_blocks)
+ writer = _CodeWriter(buffer, named_blocks, loader, ancestors[0].template)
+ ancestors[0].generate(writer)
+ return buffer.getvalue()
+ finally:
+ buffer.close()
+
+ def _get_ancestors(self, loader: Optional["BaseLoader"]) -> List["_File"]:
+ ancestors = [self.file]
+ for chunk in self.file.body.chunks:
+ if isinstance(chunk, _ExtendsBlock):
+ if not loader:
+ raise ParseError(
+ "{% extends %} block found, but no " "template loader"
+ )
+ template = loader.load(chunk.name, self.name)
+ ancestors.extend(template._get_ancestors(loader))
+ return ancestors
+
+
+class BaseLoader:
+ """Base class for template loaders.
+
+ You must use a template loader to use template constructs like
+ ``{% extends %}`` and ``{% include %}``. The loader caches all
+ templates after they are loaded the first time.
+ """
+
+ def __init__(
+ self,
+ autoescape: Optional[str] = _DEFAULT_AUTOESCAPE,
+ namespace: Optional[Dict[str, Any]] = None,
+ whitespace: Optional[str] = None,
+ ) -> None:
+ """Construct a template loader.
+
+ :arg str autoescape: The name of a function in the template
+ namespace, such as "xhtml_escape", or ``None`` to disable
+ autoescaping by default.
+ :arg dict namespace: A dictionary to be added to the default template
+ namespace, or ``None``.
+ :arg str whitespace: A string specifying default behavior for
+ whitespace in templates; see `filter_whitespace` for options.
+ Default is "single" for files ending in ".html" and ".js" and
+ "all" for other files.
+
+ .. versionchanged:: 4.3
+ Added ``whitespace`` parameter.
+ """
+ self.autoescape = autoescape
+ self.namespace = namespace or {}
+ self.whitespace = whitespace
+ self.templates = {} # type: Dict[str, Template]
+ # self.lock protects self.templates. It's a reentrant lock
+ # because templates may load other templates via `include` or
+ # `extends`. Note that thanks to the GIL this code would be safe
+ # even without the lock, but could lead to wasted work as multiple
+ # threads tried to compile the same template simultaneously.
+ self.lock = threading.RLock()
+
+ def reset(self) -> None:
+ """Resets the cache of compiled templates."""
+ with self.lock:
+ self.templates = {}
+
+ def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str:
+ """Converts a possibly-relative path to absolute (used internally)."""
+ raise NotImplementedError()
+
+ def load(self, name: str, parent_path: Optional[str] = None) -> Template:
+ """Loads a template."""
+ name = self.resolve_path(name, parent_path=parent_path)
+ with self.lock:
+ if name not in self.templates:
+ self.templates[name] = self._create_template(name)
+ return self.templates[name]
+
+ def _create_template(self, name: str) -> Template:
+ raise NotImplementedError()
+
+
+class Loader(BaseLoader):
+ """A template loader that loads from a single root directory."""
+
+ def __init__(self, root_directory: str, **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ self.root = os.path.abspath(root_directory)
+
+ def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str:
+ if (
+ parent_path
+ and not parent_path.startswith("<")
+ and not parent_path.startswith("/")
+ and not name.startswith("/")
+ ):
+ current_path = os.path.join(self.root, parent_path)
+ file_dir = os.path.dirname(os.path.abspath(current_path))
+ relative_path = os.path.abspath(os.path.join(file_dir, name))
+ if relative_path.startswith(self.root):
+ name = relative_path[len(self.root) + 1 :]
+ return name
+
+ def _create_template(self, name: str) -> Template:
+ path = os.path.join(self.root, name)
+ with open(path, "rb") as f:
+ template = Template(f.read(), name=name, loader=self)
+ return template
+
+
+class DictLoader(BaseLoader):
+ """A template loader that loads from a dictionary."""
+
+ def __init__(self, dict: Dict[str, str], **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ self.dict = dict
+
+ def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str:
+ if (
+ parent_path
+ and not parent_path.startswith("<")
+ and not parent_path.startswith("/")
+ and not name.startswith("/")
+ ):
+ file_dir = posixpath.dirname(parent_path)
+ name = posixpath.normpath(posixpath.join(file_dir, name))
+ return name
+
+ def _create_template(self, name: str) -> Template:
+ return Template(self.dict[name], name=name, loader=self)
+
+
+class _Node:
+ def each_child(self) -> Iterable["_Node"]:
+ return ()
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ raise NotImplementedError()
+
+ def find_named_blocks(
+ self, loader: Optional[BaseLoader], named_blocks: Dict[str, "_NamedBlock"]
+ ) -> None:
+ for child in self.each_child():
+ child.find_named_blocks(loader, named_blocks)
+
+
+class _File(_Node):
+ def __init__(self, template: Template, body: "_ChunkList") -> None:
+ self.template = template
+ self.body = body
+ self.line = 0
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ writer.write_line("def _tt_execute():", self.line)
+ with writer.indent():
+ writer.write_line("_tt_buffer = []", self.line)
+ writer.write_line("_tt_append = _tt_buffer.append", self.line)
+ self.body.generate(writer)
+ writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
+
+ def each_child(self) -> Iterable["_Node"]:
+ return (self.body,)
+
+
+class _ChunkList(_Node):
+ def __init__(self, chunks: List[_Node]) -> None:
+ self.chunks = chunks
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ for chunk in self.chunks:
+ chunk.generate(writer)
+
+ def each_child(self) -> Iterable["_Node"]:
+ return self.chunks
+
+
+class _NamedBlock(_Node):
+ def __init__(self, name: str, body: _Node, template: Template, line: int) -> None:
+ self.name = name
+ self.body = body
+ self.template = template
+ self.line = line
+
+ def each_child(self) -> Iterable["_Node"]:
+ return (self.body,)
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ block = writer.named_blocks[self.name]
+ with writer.include(block.template, self.line):
+ block.body.generate(writer)
+
+ def find_named_blocks(
+ self, loader: Optional[BaseLoader], named_blocks: Dict[str, "_NamedBlock"]
+ ) -> None:
+ named_blocks[self.name] = self
+ _Node.find_named_blocks(self, loader, named_blocks)
+
+
+class _ExtendsBlock(_Node):
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+class _IncludeBlock(_Node):
+ def __init__(self, name: str, reader: "_TemplateReader", line: int) -> None:
+ self.name = name
+ self.template_name = reader.name
+ self.line = line
+
+ def find_named_blocks(
+ self, loader: Optional[BaseLoader], named_blocks: Dict[str, _NamedBlock]
+ ) -> None:
+ assert loader is not None
+ included = loader.load(self.name, self.template_name)
+ included.file.find_named_blocks(loader, named_blocks)
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ assert writer.loader is not None
+ included = writer.loader.load(self.name, self.template_name)
+ with writer.include(included, self.line):
+ included.file.body.generate(writer)
+
+
+class _ApplyBlock(_Node):
+ def __init__(self, method: str, line: int, body: _Node) -> None:
+ self.method = method
+ self.line = line
+ self.body = body
+
+ def each_child(self) -> Iterable["_Node"]:
+ return (self.body,)
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ method_name = "_tt_apply%d" % writer.apply_counter
+ writer.apply_counter += 1
+ writer.write_line("def %s():" % method_name, self.line)
+ with writer.indent():
+ writer.write_line("_tt_buffer = []", self.line)
+ writer.write_line("_tt_append = _tt_buffer.append", self.line)
+ self.body.generate(writer)
+ writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
+ writer.write_line(
+ f"_tt_append(_tt_utf8({self.method}({method_name}())))", self.line
+ )
+
+
+class _ControlBlock(_Node):
+ def __init__(self, statement: str, line: int, body: _Node) -> None:
+ self.statement = statement
+ self.line = line
+ self.body = body
+
+ def each_child(self) -> Iterable[_Node]:
+ return (self.body,)
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ writer.write_line("%s:" % self.statement, self.line)
+ with writer.indent():
+ self.body.generate(writer)
+ # Just in case the body was empty
+ writer.write_line("pass", self.line)
+
+
+class _IntermediateControlBlock(_Node):
+ def __init__(self, statement: str, line: int) -> None:
+ self.statement = statement
+ self.line = line
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ # In case the previous block was empty
+ writer.write_line("pass", self.line)
+ writer.write_line("%s:" % self.statement, self.line, writer.indent_size() - 1)
+
+
+class _Statement(_Node):
+ def __init__(self, statement: str, line: int) -> None:
+ self.statement = statement
+ self.line = line
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ writer.write_line(self.statement, self.line)
+
+
+class _Expression(_Node):
+ def __init__(self, expression: str, line: int, raw: bool = False) -> None:
+ self.expression = expression
+ self.line = line
+ self.raw = raw
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ writer.write_line("_tt_tmp = %s" % self.expression, self.line)
+ writer.write_line(
+ "if isinstance(_tt_tmp, _tt_string_types):" " _tt_tmp = _tt_utf8(_tt_tmp)",
+ self.line,
+ )
+ writer.write_line("else: _tt_tmp = _tt_utf8(str(_tt_tmp))", self.line)
+ if not self.raw and writer.current_template.autoescape is not None:
+ # In python3 functions like xhtml_escape return unicode,
+ # so we have to convert to utf8 again.
+ writer.write_line(
+ "_tt_tmp = _tt_utf8(%s(_tt_tmp))" % writer.current_template.autoescape,
+ self.line,
+ )
+ writer.write_line("_tt_append(_tt_tmp)", self.line)
+
+
+class _Module(_Expression):
+ def __init__(self, expression: str, line: int) -> None:
+ super().__init__("_tt_modules." + expression, line, raw=True)
+
+
+class _Text(_Node):
+ def __init__(self, value: str, line: int, whitespace: str) -> None:
+ self.value = value
+ self.line = line
+ self.whitespace = whitespace
+
+ def generate(self, writer: "_CodeWriter") -> None:
+ value = self.value
+
+ # Compress whitespace if requested, with a crude heuristic to avoid
+ # altering preformatted whitespace.
+ if "" not in value:
+ value = filter_whitespace(self.whitespace, value)
+
+ if value:
+ writer.write_line("_tt_append(%r)" % escape.utf8(value), self.line)
+
+
+class ParseError(Exception):
+ """Raised for template syntax errors.
+
+ ``ParseError`` instances have ``filename`` and ``lineno`` attributes
+ indicating the position of the error.
+
+ .. versionchanged:: 4.3
+ Added ``filename`` and ``lineno`` attributes.
+ """
+
+ def __init__(
+ self, message: str, filename: Optional[str] = None, lineno: int = 0
+ ) -> None:
+ self.message = message
+ # The names "filename" and "lineno" are chosen for consistency
+ # with python SyntaxError.
+ self.filename = filename
+ self.lineno = lineno
+
+ def __str__(self) -> str:
+ return "%s at %s:%d" % (self.message, self.filename, self.lineno)
+
+
+class _CodeWriter:
+ def __init__(
+ self,
+ file: TextIO,
+ named_blocks: Dict[str, _NamedBlock],
+ loader: Optional[BaseLoader],
+ current_template: Template,
+ ) -> None:
+ self.file = file
+ self.named_blocks = named_blocks
+ self.loader = loader
+ self.current_template = current_template
+ self.apply_counter = 0
+ self.include_stack = [] # type: List[Tuple[Template, int]]
+ self._indent = 0
+
+ def indent_size(self) -> int:
+ return self._indent
+
+ def indent(self) -> "ContextManager":
+ class Indenter:
+ def __enter__(_) -> "_CodeWriter":
+ self._indent += 1
+ return self
+
+ def __exit__(_, *args: Any) -> None:
+ assert self._indent > 0
+ self._indent -= 1
+
+ return Indenter()
+
+ def include(self, template: Template, line: int) -> "ContextManager":
+ self.include_stack.append((self.current_template, line))
+ self.current_template = template
+
+ class IncludeTemplate:
+ def __enter__(_) -> "_CodeWriter":
+ return self
+
+ def __exit__(_, *args: Any) -> None:
+ self.current_template = self.include_stack.pop()[0]
+
+ return IncludeTemplate()
+
+ def write_line(
+ self, line: str, line_number: int, indent: Optional[int] = None
+ ) -> None:
+ if indent is None:
+ indent = self._indent
+ line_comment = " # %s:%d" % (self.current_template.name, line_number)
+ if self.include_stack:
+ ancestors = [
+ "%s:%d" % (tmpl.name, lineno) for (tmpl, lineno) in self.include_stack
+ ]
+ line_comment += " (via %s)" % ", ".join(reversed(ancestors))
+ print(" " * indent + line + line_comment, file=self.file)
+
+
+class _TemplateReader:
+ def __init__(self, name: str, text: str, whitespace: str) -> None:
+ self.name = name
+ self.text = text
+ self.whitespace = whitespace
+ self.line = 1
+ self.pos = 0
+
+ def find(self, needle: str, start: int = 0, end: Optional[int] = None) -> int:
+ assert start >= 0, start
+ pos = self.pos
+ start += pos
+ if end is None:
+ index = self.text.find(needle, start)
+ else:
+ end += pos
+ assert end >= start
+ index = self.text.find(needle, start, end)
+ if index != -1:
+ index -= pos
+ return index
+
+ def consume(self, count: Optional[int] = None) -> str:
+ if count is None:
+ count = len(self.text) - self.pos
+ newpos = self.pos + count
+ self.line += self.text.count("\n", self.pos, newpos)
+ s = self.text[self.pos : newpos]
+ self.pos = newpos
+ return s
+
+ def remaining(self) -> int:
+ return len(self.text) - self.pos
+
+ def __len__(self) -> int:
+ return self.remaining()
+
+ def __getitem__(self, key: Union[int, slice]) -> str:
+ if isinstance(key, slice):
+ size = len(self)
+ start, stop, step = key.indices(size)
+ if start is None:
+ start = self.pos
+ else:
+ start += self.pos
+ if stop is not None:
+ stop += self.pos
+ return self.text[slice(start, stop, step)]
+ elif key < 0:
+ return self.text[key]
+ else:
+ return self.text[self.pos + key]
+
+ def __str__(self) -> str:
+ return self.text[self.pos :]
+
+ def raise_parse_error(self, msg: str) -> None:
+ raise ParseError(msg, self.name, self.line)
+
+
+def _format_code(code: str) -> str:
+ lines = code.splitlines()
+ format = "%%%dd %%s\n" % len(repr(len(lines) + 1))
+ return "".join([format % (i + 1, line) for (i, line) in enumerate(lines)])
+
+
+def _parse(
+ reader: _TemplateReader,
+ template: Template,
+ in_block: Optional[str] = None,
+ in_loop: Optional[str] = None,
+) -> _ChunkList:
+ body = _ChunkList([])
+ while True:
+ # Find next template directive
+ curly = 0
+ while True:
+ curly = reader.find("{", curly)
+ if curly == -1 or curly + 1 == reader.remaining():
+ # EOF
+ if in_block:
+ reader.raise_parse_error(
+ "Missing {%% end %%} block for %s" % in_block
+ )
+ body.chunks.append(
+ _Text(reader.consume(), reader.line, reader.whitespace)
+ )
+ return body
+ # If the first curly brace is not the start of a special token,
+ # start searching from the character after it
+ if reader[curly + 1] not in ("{", "%", "#"):
+ curly += 1
+ continue
+ # When there are more than 2 curlies in a row, use the
+ # innermost ones. This is useful when generating languages
+ # like latex where curlies are also meaningful
+ if (
+ curly + 2 < reader.remaining()
+ and reader[curly + 1] == "{"
+ and reader[curly + 2] == "{"
+ ):
+ curly += 1
+ continue
+ break
+
+ # Append any text before the special token
+ if curly > 0:
+ cons = reader.consume(curly)
+ body.chunks.append(_Text(cons, reader.line, reader.whitespace))
+
+ start_brace = reader.consume(2)
+ line = reader.line
+
+ # Template directives may be escaped as "{{!" or "{%!".
+ # In this case output the braces and consume the "!".
+ # This is especially useful in conjunction with jquery templates,
+ # which also use double braces.
+ if reader.remaining() and reader[0] == "!":
+ reader.consume(1)
+ body.chunks.append(_Text(start_brace, line, reader.whitespace))
+ continue
+
+ # Comment
+ if start_brace == "{#":
+ end = reader.find("#}")
+ if end == -1:
+ reader.raise_parse_error("Missing end comment #}")
+ contents = reader.consume(end).strip()
+ reader.consume(2)
+ continue
+
+ # Expression
+ if start_brace == "{{":
+ end = reader.find("}}")
+ if end == -1:
+ reader.raise_parse_error("Missing end expression }}")
+ contents = reader.consume(end).strip()
+ reader.consume(2)
+ if not contents:
+ reader.raise_parse_error("Empty expression")
+ body.chunks.append(_Expression(contents, line))
+ continue
+
+ # Block
+ assert start_brace == "{%", start_brace
+ end = reader.find("%}")
+ if end == -1:
+ reader.raise_parse_error("Missing end block %}")
+ contents = reader.consume(end).strip()
+ reader.consume(2)
+ if not contents:
+ reader.raise_parse_error("Empty block tag ({% %})")
+
+ operator, space, suffix = contents.partition(" ")
+ suffix = suffix.strip()
+
+ # Intermediate ("else", "elif", etc) blocks
+ intermediate_blocks = {
+ "else": {"if", "for", "while", "try"},
+ "elif": {"if"},
+ "except": {"try"},
+ "finally": {"try"},
+ }
+ allowed_parents = intermediate_blocks.get(operator)
+ if allowed_parents is not None:
+ if not in_block:
+ reader.raise_parse_error(f"{operator} outside {allowed_parents} block")
+ if in_block not in allowed_parents:
+ reader.raise_parse_error(
+ f"{operator} block cannot be attached to {in_block} block"
+ )
+ body.chunks.append(_IntermediateControlBlock(contents, line))
+ continue
+
+ # End tag
+ elif operator == "end":
+ if not in_block:
+ reader.raise_parse_error("Extra {% end %} block")
+ return body
+
+ elif operator in (
+ "extends",
+ "include",
+ "set",
+ "import",
+ "from",
+ "comment",
+ "autoescape",
+ "whitespace",
+ "raw",
+ "module",
+ ):
+ if operator == "comment":
+ continue
+ if operator == "extends":
+ suffix = suffix.strip('"').strip("'")
+ if not suffix:
+ reader.raise_parse_error("extends missing file path")
+ block = _ExtendsBlock(suffix) # type: _Node
+ elif operator in ("import", "from"):
+ if not suffix:
+ reader.raise_parse_error("import missing statement")
+ block = _Statement(contents, line)
+ elif operator == "include":
+ suffix = suffix.strip('"').strip("'")
+ if not suffix:
+ reader.raise_parse_error("include missing file path")
+ block = _IncludeBlock(suffix, reader, line)
+ elif operator == "set":
+ if not suffix:
+ reader.raise_parse_error("set missing statement")
+ block = _Statement(suffix, line)
+ elif operator == "autoescape":
+ fn = suffix.strip() # type: Optional[str]
+ if fn == "None":
+ fn = None
+ template.autoescape = fn
+ continue
+ elif operator == "whitespace":
+ mode = suffix.strip()
+ # Validate the selected mode
+ filter_whitespace(mode, "")
+ reader.whitespace = mode
+ continue
+ elif operator == "raw":
+ block = _Expression(suffix, line, raw=True)
+ elif operator == "module":
+ block = _Module(suffix, line)
+ body.chunks.append(block)
+ continue
+
+ elif operator in ("apply", "block", "try", "if", "for", "while"):
+ # parse inner body recursively
+ if operator in ("for", "while"):
+ block_body = _parse(reader, template, operator, operator)
+ elif operator == "apply":
+ # apply creates a nested function so syntactically it's not
+ # in the loop.
+ block_body = _parse(reader, template, operator, None)
+ else:
+ block_body = _parse(reader, template, operator, in_loop)
+
+ if operator == "apply":
+ if not suffix:
+ reader.raise_parse_error("apply missing method name")
+ block = _ApplyBlock(suffix, line, block_body)
+ elif operator == "block":
+ if not suffix:
+ reader.raise_parse_error("block missing name")
+ block = _NamedBlock(suffix, block_body, template, line)
+ else:
+ block = _ControlBlock(contents, line, block_body)
+ body.chunks.append(block)
+ continue
+
+ elif operator in ("break", "continue"):
+ if not in_loop:
+ reader.raise_parse_error(
+ "{} outside {} block".format(operator, {"for", "while"})
+ )
+ body.chunks.append(_Statement(contents, line))
+ continue
+
+ else:
+ reader.raise_parse_error("unknown operator: %r" % operator)
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/__main__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..65b794d9beafd5662679fff18ca510abaf4d5cdc
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/__main__.py
@@ -0,0 +1,11 @@
+"""Shim to allow python -m tornado.test.
+"""
+
+from tornado.test.runtests import all, main
+
+# tornado.testing.main autodiscovery relies on 'all' being present in
+# the main module, so import it here even though it is not used directly.
+# The following line prevents a pyflakes warning.
+all = all
+
+main()
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/asyncio_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/asyncio_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..f33c5f53c301deebd22f4a0d90c12890c36f9f45
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/asyncio_test.py
@@ -0,0 +1,298 @@
+# 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.
+
+import asyncio
+import contextvars
+import threading
+import time
+import unittest
+import warnings
+
+from concurrent.futures import ThreadPoolExecutor
+import tornado.platform.asyncio
+from tornado import gen
+from tornado.ioloop import IOLoop
+from tornado.platform.asyncio import (
+ AsyncIOLoop,
+ to_asyncio_future,
+ AddThreadSelectorEventLoop,
+)
+from tornado.testing import (
+ AsyncTestCase,
+ gen_test,
+ setup_with_context_manager,
+ AsyncHTTPTestCase,
+)
+from tornado.test.util import ignore_deprecation
+from tornado.web import Application, RequestHandler
+
+
+class AsyncIOLoopTest(AsyncTestCase):
+ @property
+ def asyncio_loop(self):
+ return self.io_loop.asyncio_loop # type: ignore
+
+ def test_asyncio_callback(self):
+ # Basic test that the asyncio loop is set up correctly.
+ async def add_callback():
+ asyncio.get_event_loop().call_soon(self.stop)
+
+ self.asyncio_loop.run_until_complete(add_callback())
+ self.wait()
+
+ @gen_test
+ def test_asyncio_future(self):
+ # Test that we can yield an asyncio future from a tornado coroutine.
+ # Without 'yield from', we must wrap coroutines in ensure_future.
+ x = yield asyncio.ensure_future(
+ asyncio.get_event_loop().run_in_executor(None, lambda: 42)
+ )
+ self.assertEqual(x, 42)
+
+ @gen_test
+ def test_asyncio_yield_from(self):
+ @gen.coroutine
+ def f():
+ event_loop = asyncio.get_event_loop()
+ x = yield from event_loop.run_in_executor(None, lambda: 42)
+ return x
+
+ result = yield f()
+ self.assertEqual(result, 42)
+
+ def test_asyncio_adapter(self):
+ # This test demonstrates that when using the asyncio coroutine
+ # runner (i.e. run_until_complete), the to_asyncio_future
+ # adapter is needed. No adapter is needed in the other direction,
+ # as demonstrated by other tests in the package.
+ @gen.coroutine
+ def tornado_coroutine():
+ yield gen.moment
+ raise gen.Return(42)
+
+ async def native_coroutine_without_adapter():
+ return await tornado_coroutine()
+
+ async def native_coroutine_with_adapter():
+ return await to_asyncio_future(tornado_coroutine())
+
+ # Use the adapter, but two degrees from the tornado coroutine.
+ async def native_coroutine_with_adapter2():
+ return await to_asyncio_future(native_coroutine_without_adapter())
+
+ # Tornado supports native coroutines both with and without adapters
+ self.assertEqual(self.io_loop.run_sync(native_coroutine_without_adapter), 42)
+ self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter), 42)
+ self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter2), 42)
+
+ # Asyncio only supports coroutines that yield asyncio-compatible
+ # Futures (which our Future is since 5.0).
+ self.assertEqual(
+ self.asyncio_loop.run_until_complete(native_coroutine_without_adapter()),
+ 42,
+ )
+ self.assertEqual(
+ self.asyncio_loop.run_until_complete(native_coroutine_with_adapter()),
+ 42,
+ )
+ self.assertEqual(
+ self.asyncio_loop.run_until_complete(native_coroutine_with_adapter2()),
+ 42,
+ )
+
+ def test_add_thread_close_idempotent(self):
+ loop = AddThreadSelectorEventLoop(asyncio.get_event_loop()) # type: ignore
+ loop.close()
+ loop.close()
+
+
+class LeakTest(unittest.TestCase):
+ def setUp(self):
+ # Trigger a cleanup of the mapping so we start with a clean slate.
+ AsyncIOLoop(make_current=False).close()
+
+ def tearDown(self):
+ try:
+ loop = asyncio.get_event_loop_policy().get_event_loop()
+ except Exception:
+ # We may not have a current event loop at this point.
+ pass
+ else:
+ loop.close()
+
+ def test_ioloop_close_leak(self):
+ orig_count = len(IOLoop._ioloop_for_asyncio)
+ for i in range(10):
+ # Create and close an AsyncIOLoop using Tornado interfaces.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ loop = AsyncIOLoop()
+ loop.close()
+ new_count = len(IOLoop._ioloop_for_asyncio) - orig_count
+ self.assertEqual(new_count, 0)
+
+ def test_asyncio_close_leak(self):
+ orig_count = len(IOLoop._ioloop_for_asyncio)
+ for i in range(10):
+ # Create and close an AsyncIOMainLoop using asyncio interfaces.
+ loop = asyncio.new_event_loop()
+ loop.call_soon(IOLoop.current)
+ loop.call_soon(loop.stop)
+ loop.run_forever()
+ loop.close()
+ new_count = len(IOLoop._ioloop_for_asyncio) - orig_count
+ # Because the cleanup is run on new loop creation, we have one
+ # dangling entry in the map (but only one).
+ self.assertEqual(new_count, 1)
+
+
+class SelectorThreadLeakTest(unittest.TestCase):
+ # These tests are only relevant on windows, but they should pass anywhere.
+ def setUp(self):
+ # As a precaution, ensure that we've run an event loop at least once
+ # so if it spins up any singleton threads they're already there.
+ asyncio.run(self.dummy_tornado_coroutine())
+ self.orig_thread_count = threading.active_count()
+
+ def assert_no_thread_leak(self):
+ # For some reason we see transient failures here, but I haven't been able
+ # to catch it to identify which thread is causing it. Whatever thread it
+ # is, it appears to quickly clean up on its own, so just retry a few times.
+ # At least some of the time the errant thread was running at the time we
+ # captured self.orig_thread_count, so use inequalities.
+ deadline = time.time() + 1
+ while time.time() < deadline:
+ threads = list(threading.enumerate())
+ if len(threads) <= self.orig_thread_count:
+ break
+ time.sleep(0.1)
+ self.assertLessEqual(len(threads), self.orig_thread_count, threads)
+
+ async def dummy_tornado_coroutine(self):
+ # Just access the IOLoop to initialize the selector thread.
+ IOLoop.current()
+
+ def test_asyncio_run(self):
+ for i in range(10):
+ # asyncio.run calls shutdown_asyncgens for us.
+ asyncio.run(self.dummy_tornado_coroutine())
+ self.assert_no_thread_leak()
+
+ def test_asyncio_manual(self):
+ for i in range(10):
+ loop = asyncio.new_event_loop()
+ loop.run_until_complete(self.dummy_tornado_coroutine())
+ # Without this step, we'd leak the thread.
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ loop.close()
+ self.assert_no_thread_leak()
+
+ def test_tornado(self):
+ for i in range(10):
+ # The IOLoop interfaces are aware of the selector thread and
+ # (synchronously) shut it down.
+ loop = IOLoop(make_current=False)
+ loop.run_sync(self.dummy_tornado_coroutine)
+ loop.close()
+ self.assert_no_thread_leak()
+
+
+class AnyThreadEventLoopPolicyTest(unittest.TestCase):
+ def setUp(self):
+ setup_with_context_manager(self, ignore_deprecation())
+ # Referencing the event loop policy attributes raises deprecation warnings,
+ # so instead of importing this at the top of the file we capture it here.
+ self.AnyThreadEventLoopPolicy = (
+ tornado.platform.asyncio.AnyThreadEventLoopPolicy
+ )
+ self.orig_policy = asyncio.get_event_loop_policy()
+ self.executor = ThreadPoolExecutor(1)
+
+ def tearDown(self):
+ asyncio.set_event_loop_policy(self.orig_policy)
+ self.executor.shutdown()
+
+ def get_event_loop_on_thread(self):
+ def get_and_close_event_loop():
+ """Get the event loop. Close it if one is returned.
+
+ Returns the (closed) event loop. This is a silly thing
+ to do and leaves the thread in a broken state, but it's
+ enough for this test. Closing the loop avoids resource
+ leak warnings.
+ """
+ loop = asyncio.get_event_loop()
+ loop.close()
+ return loop
+
+ future = self.executor.submit(get_and_close_event_loop)
+ return future.result()
+
+ def test_asyncio_accessor(self):
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ # With the default policy, non-main threads don't get an event
+ # loop.
+ self.assertRaises(
+ RuntimeError, self.executor.submit(asyncio.get_event_loop).result
+ )
+ # Set the policy and we can get a loop.
+ asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy())
+ self.assertIsInstance(
+ self.executor.submit(asyncio.get_event_loop).result(),
+ asyncio.AbstractEventLoop,
+ )
+ # Clean up to silence leak warnings. Always use asyncio since
+ # IOLoop doesn't (currently) close the underlying loop.
+ self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
+
+ def test_tornado_accessor(self):
+ # Tornado's IOLoop.current() API can create a loop for any thread,
+ # regardless of this event loop policy.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop)
+ # Clean up to silence leak warnings. Always use asyncio since
+ # IOLoop doesn't (currently) close the underlying loop.
+ self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
+
+ asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy())
+ self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop)
+ self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
+
+
+class SelectorThreadContextvarsTest(AsyncHTTPTestCase):
+ ctx_value = "foo"
+ test_endpoint = "/"
+ tornado_test_ctx = contextvars.ContextVar("tornado_test_ctx", default="default")
+ tornado_test_ctx.set(ctx_value)
+
+ def get_app(self) -> Application:
+ tornado_test_ctx = self.tornado_test_ctx
+
+ class Handler(RequestHandler):
+ async def get(self):
+ # On the Windows platform,
+ # when a asyncio.events.Handle is created
+ # in the SelectorThread without providing a context,
+ # it will copy the current thread's context,
+ # which can lead to the loss of the main thread's context
+ # when executing the handle.
+ # Therefore, it is necessary to
+ # save a copy of the main thread's context in the SelectorThread
+ # for creating the handle.
+ self.write(tornado_test_ctx.get())
+
+ return Application([(self.test_endpoint, Handler)])
+
+ def test_context_vars(self):
+ self.assertEqual(self.ctx_value, self.fetch(self.test_endpoint).body.decode())
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/auth_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/auth_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..834f04ea309bdda995c22e7aefb557fee9861c22
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/auth_test.py
@@ -0,0 +1,608 @@
+# These tests do not currently do much to verify the correct implementation
+# of the openid/oauth protocols, they just exercise the major code paths
+# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in
+# python 3)
+
+import unittest
+
+from tornado.auth import (
+ OpenIdMixin,
+ OAuthMixin,
+ OAuth2Mixin,
+ GoogleOAuth2Mixin,
+ FacebookGraphMixin,
+ TwitterMixin,
+)
+from tornado.escape import json_decode
+from tornado import gen
+from tornado.httpclient import HTTPClientError
+from tornado.httputil import url_concat
+from tornado.log import app_log
+from tornado.testing import AsyncHTTPTestCase, ExpectLog
+from tornado.web import RequestHandler, Application, HTTPError
+
+try:
+ from unittest import mock
+except ImportError:
+ mock = None # type: ignore
+
+
+class OpenIdClientLoginHandler(RequestHandler, OpenIdMixin):
+ def initialize(self, test):
+ self._OPENID_ENDPOINT = test.get_url("/openid/server/authenticate")
+
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("openid.mode", None):
+ user = yield self.get_authenticated_user(
+ http_client=self.settings["http_client"]
+ )
+ if user is None:
+ raise Exception("user is None")
+ self.finish(user)
+ return
+ res = self.authenticate_redirect() # type: ignore
+ assert res is None
+
+
+class OpenIdServerAuthenticateHandler(RequestHandler):
+ def post(self):
+ if self.get_argument("openid.mode") != "check_authentication":
+ raise Exception("incorrect openid.mode %r")
+ self.write("is_valid:true")
+
+
+class OAuth1ClientLoginHandler(RequestHandler, OAuthMixin):
+ def initialize(self, test, version):
+ self._OAUTH_VERSION = version
+ self._OAUTH_REQUEST_TOKEN_URL = test.get_url("/oauth1/server/request_token")
+ self._OAUTH_AUTHORIZE_URL = test.get_url("/oauth1/server/authorize")
+ self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/oauth1/server/access_token")
+
+ def _oauth_consumer_token(self):
+ return dict(key="asdf", secret="qwer")
+
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("oauth_token", None):
+ user = yield self.get_authenticated_user(
+ http_client=self.settings["http_client"]
+ )
+ if user is None:
+ raise Exception("user is None")
+ self.finish(user)
+ return
+ yield self.authorize_redirect(http_client=self.settings["http_client"])
+
+ @gen.coroutine
+ def _oauth_get_user_future(self, access_token):
+ if self.get_argument("fail_in_get_user", None):
+ raise Exception("failing in get_user")
+ if access_token != dict(key="uiop", secret="5678"):
+ raise Exception("incorrect access token %r" % access_token)
+ return dict(email="foo@example.com")
+
+
+class OAuth1ClientLoginCoroutineHandler(OAuth1ClientLoginHandler):
+ """Replaces OAuth1ClientLoginCoroutineHandler's get() with a coroutine."""
+
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("oauth_token", None):
+ # Ensure that any exceptions are set on the returned Future,
+ # not simply thrown into the surrounding StackContext.
+ try:
+ yield self.get_authenticated_user()
+ except Exception as e:
+ self.set_status(503)
+ self.write("got exception: %s" % e)
+ else:
+ yield self.authorize_redirect()
+
+
+class OAuth1ClientRequestParametersHandler(RequestHandler, OAuthMixin):
+ def initialize(self, version):
+ self._OAUTH_VERSION = version
+
+ def _oauth_consumer_token(self):
+ return dict(key="asdf", secret="qwer")
+
+ def get(self):
+ params = self._oauth_request_parameters(
+ "http://www.example.com/api/asdf",
+ dict(key="uiop", secret="5678"),
+ parameters=dict(foo="bar"),
+ )
+ self.write(params)
+
+
+class OAuth1ServerRequestTokenHandler(RequestHandler):
+ def get(self):
+ self.write("oauth_token=zxcv&oauth_token_secret=1234")
+
+
+class OAuth1ServerAccessTokenHandler(RequestHandler):
+ def get(self):
+ self.write("oauth_token=uiop&oauth_token_secret=5678")
+
+
+class OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin):
+ def initialize(self, test):
+ self._OAUTH_AUTHORIZE_URL = test.get_url("/oauth2/server/authorize")
+
+ def get(self):
+ res = self.authorize_redirect() # type: ignore
+ assert res is None
+
+
+class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):
+ def initialize(self, test):
+ self._OAUTH_AUTHORIZE_URL = test.get_url("/facebook/server/authorize")
+ self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/facebook/server/access_token")
+ self._FACEBOOK_BASE_URL = test.get_url("/facebook/server")
+
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("code", None):
+ user = yield self.get_authenticated_user(
+ redirect_uri=self.request.full_url(),
+ client_id=self.settings["facebook_api_key"],
+ client_secret=self.settings["facebook_secret"],
+ code=self.get_argument("code"),
+ )
+ self.write(user)
+ else:
+ self.authorize_redirect(
+ redirect_uri=self.request.full_url(),
+ client_id=self.settings["facebook_api_key"],
+ extra_params={"scope": "read_stream,offline_access"},
+ )
+
+
+class FacebookServerAccessTokenHandler(RequestHandler):
+ def get(self):
+ self.write(dict(access_token="asdf", expires_in=3600))
+
+
+class FacebookServerMeHandler(RequestHandler):
+ def get(self):
+ self.write("{}")
+
+
+class TwitterClientHandler(RequestHandler, TwitterMixin):
+ def initialize(self, test):
+ self._OAUTH_REQUEST_TOKEN_URL = test.get_url("/oauth1/server/request_token")
+ self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/twitter/server/access_token")
+ self._OAUTH_AUTHORIZE_URL = test.get_url("/oauth1/server/authorize")
+ self._OAUTH_AUTHENTICATE_URL = test.get_url("/twitter/server/authenticate")
+ self._TWITTER_BASE_URL = test.get_url("/twitter/api")
+
+ def get_auth_http_client(self):
+ return self.settings["http_client"]
+
+
+class TwitterClientLoginHandler(TwitterClientHandler):
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("oauth_token", None):
+ user = yield self.get_authenticated_user()
+ if user is None:
+ raise Exception("user is None")
+ self.finish(user)
+ return
+ yield self.authorize_redirect()
+
+
+class TwitterClientAuthenticateHandler(TwitterClientHandler):
+ # Like TwitterClientLoginHandler, but uses authenticate_redirect
+ # instead of authorize_redirect.
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("oauth_token", None):
+ user = yield self.get_authenticated_user()
+ if user is None:
+ raise Exception("user is None")
+ self.finish(user)
+ return
+ yield self.authenticate_redirect()
+
+
+class TwitterClientLoginGenCoroutineHandler(TwitterClientHandler):
+ @gen.coroutine
+ def get(self):
+ if self.get_argument("oauth_token", None):
+ user = yield self.get_authenticated_user()
+ self.finish(user)
+ else:
+ # New style: with @gen.coroutine the result must be yielded
+ # or else the request will be auto-finished too soon.
+ yield self.authorize_redirect()
+
+
+class TwitterClientShowUserHandler(TwitterClientHandler):
+ @gen.coroutine
+ def get(self):
+ # TODO: would be nice to go through the login flow instead of
+ # cheating with a hard-coded access token.
+ try:
+ response = yield self.twitter_request(
+ "/users/show/%s" % self.get_argument("name"),
+ access_token=dict(key="hjkl", secret="vbnm"),
+ )
+ except HTTPClientError:
+ # TODO(bdarnell): Should we catch HTTP errors and
+ # transform some of them (like 403s) into AuthError?
+ self.set_status(500)
+ self.finish("error from twitter request")
+ else:
+ self.finish(response)
+
+
+class TwitterServerAccessTokenHandler(RequestHandler):
+ def get(self):
+ self.write("oauth_token=hjkl&oauth_token_secret=vbnm&screen_name=foo")
+
+
+class TwitterServerShowUserHandler(RequestHandler):
+ def get(self, screen_name):
+ if screen_name == "error":
+ raise HTTPError(500)
+ assert "oauth_nonce" in self.request.arguments
+ assert "oauth_timestamp" in self.request.arguments
+ assert "oauth_signature" in self.request.arguments
+ assert self.get_argument("oauth_consumer_key") == "test_twitter_consumer_key"
+ assert self.get_argument("oauth_signature_method") == "HMAC-SHA1"
+ assert self.get_argument("oauth_version") == "1.0"
+ assert self.get_argument("oauth_token") == "hjkl"
+ self.write(dict(screen_name=screen_name, name=screen_name.capitalize()))
+
+
+class TwitterServerVerifyCredentialsHandler(RequestHandler):
+ def get(self):
+ assert "oauth_nonce" in self.request.arguments
+ assert "oauth_timestamp" in self.request.arguments
+ assert "oauth_signature" in self.request.arguments
+ assert self.get_argument("oauth_consumer_key") == "test_twitter_consumer_key"
+ assert self.get_argument("oauth_signature_method") == "HMAC-SHA1"
+ assert self.get_argument("oauth_version") == "1.0"
+ assert self.get_argument("oauth_token") == "hjkl"
+ self.write(dict(screen_name="foo", name="Foo"))
+
+
+class AuthTest(AsyncHTTPTestCase):
+ def get_app(self):
+ return Application(
+ [
+ # test endpoints
+ ("/openid/client/login", OpenIdClientLoginHandler, dict(test=self)),
+ (
+ "/oauth10/client/login",
+ OAuth1ClientLoginHandler,
+ dict(test=self, version="1.0"),
+ ),
+ (
+ "/oauth10/client/request_params",
+ OAuth1ClientRequestParametersHandler,
+ dict(version="1.0"),
+ ),
+ (
+ "/oauth10a/client/login",
+ OAuth1ClientLoginHandler,
+ dict(test=self, version="1.0a"),
+ ),
+ (
+ "/oauth10a/client/login_coroutine",
+ OAuth1ClientLoginCoroutineHandler,
+ dict(test=self, version="1.0a"),
+ ),
+ (
+ "/oauth10a/client/request_params",
+ OAuth1ClientRequestParametersHandler,
+ dict(version="1.0a"),
+ ),
+ ("/oauth2/client/login", OAuth2ClientLoginHandler, dict(test=self)),
+ ("/facebook/client/login", FacebookClientLoginHandler, dict(test=self)),
+ ("/twitter/client/login", TwitterClientLoginHandler, dict(test=self)),
+ (
+ "/twitter/client/authenticate",
+ TwitterClientAuthenticateHandler,
+ dict(test=self),
+ ),
+ (
+ "/twitter/client/login_gen_coroutine",
+ TwitterClientLoginGenCoroutineHandler,
+ dict(test=self),
+ ),
+ (
+ "/twitter/client/show_user",
+ TwitterClientShowUserHandler,
+ dict(test=self),
+ ),
+ # simulated servers
+ ("/openid/server/authenticate", OpenIdServerAuthenticateHandler),
+ ("/oauth1/server/request_token", OAuth1ServerRequestTokenHandler),
+ ("/oauth1/server/access_token", OAuth1ServerAccessTokenHandler),
+ ("/facebook/server/access_token", FacebookServerAccessTokenHandler),
+ ("/facebook/server/me", FacebookServerMeHandler),
+ ("/twitter/server/access_token", TwitterServerAccessTokenHandler),
+ (r"/twitter/api/users/show/(.*)\.json", TwitterServerShowUserHandler),
+ (
+ r"/twitter/api/account/verify_credentials\.json",
+ TwitterServerVerifyCredentialsHandler,
+ ),
+ ],
+ http_client=self.http_client,
+ twitter_consumer_key="test_twitter_consumer_key",
+ twitter_consumer_secret="test_twitter_consumer_secret",
+ facebook_api_key="test_facebook_api_key",
+ facebook_secret="test_facebook_secret",
+ )
+
+ def test_openid_redirect(self):
+ response = self.fetch("/openid/client/login", follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertIn("/openid/server/authenticate?", response.headers["Location"])
+
+ def test_openid_get_user(self):
+ response = self.fetch(
+ "/openid/client/login?openid.mode=blah"
+ "&openid.ns.ax=http://openid.net/srv/ax/1.0"
+ "&openid.ax.type.email=http://axschema.org/contact/email"
+ "&openid.ax.value.email=foo@example.com"
+ )
+ response.rethrow()
+ parsed = json_decode(response.body)
+ self.assertEqual(parsed["email"], "foo@example.com")
+
+ def test_oauth10_redirect(self):
+ response = self.fetch("/oauth10/client/login", follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertTrue(
+ response.headers["Location"].endswith(
+ "/oauth1/server/authorize?oauth_token=zxcv"
+ )
+ )
+ # the cookie is base64('zxcv')|base64('1234')
+ self.assertIn(
+ '_oauth_request_token="enhjdg==|MTIzNA=="',
+ response.headers["Set-Cookie"],
+ response.headers["Set-Cookie"],
+ )
+
+ def test_oauth10_get_user(self):
+ response = self.fetch(
+ "/oauth10/client/login?oauth_token=zxcv",
+ headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="},
+ )
+ response.rethrow()
+ parsed = json_decode(response.body)
+ self.assertEqual(parsed["email"], "foo@example.com")
+ self.assertEqual(parsed["access_token"], dict(key="uiop", secret="5678"))
+
+ def test_oauth10_request_parameters(self):
+ response = self.fetch("/oauth10/client/request_params")
+ response.rethrow()
+ parsed = json_decode(response.body)
+ self.assertEqual(parsed["oauth_consumer_key"], "asdf")
+ self.assertEqual(parsed["oauth_token"], "uiop")
+ self.assertIn("oauth_nonce", parsed)
+ self.assertIn("oauth_signature", parsed)
+
+ def test_oauth10a_redirect(self):
+ response = self.fetch("/oauth10a/client/login", follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertTrue(
+ response.headers["Location"].endswith(
+ "/oauth1/server/authorize?oauth_token=zxcv"
+ )
+ )
+ # the cookie is base64('zxcv')|base64('1234')
+ self.assertTrue(
+ '_oauth_request_token="enhjdg==|MTIzNA=="'
+ in response.headers["Set-Cookie"],
+ response.headers["Set-Cookie"],
+ )
+
+ @unittest.skipIf(mock is None, "mock package not present")
+ def test_oauth10a_redirect_error(self):
+ with mock.patch.object(OAuth1ServerRequestTokenHandler, "get") as get:
+ get.side_effect = Exception("boom")
+ with ExpectLog(app_log, "Uncaught exception"):
+ response = self.fetch("/oauth10a/client/login", follow_redirects=False)
+ self.assertEqual(response.code, 500)
+
+ def test_oauth10a_get_user(self):
+ response = self.fetch(
+ "/oauth10a/client/login?oauth_token=zxcv",
+ headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="},
+ )
+ response.rethrow()
+ parsed = json_decode(response.body)
+ self.assertEqual(parsed["email"], "foo@example.com")
+ self.assertEqual(parsed["access_token"], dict(key="uiop", secret="5678"))
+
+ def test_oauth10a_request_parameters(self):
+ response = self.fetch("/oauth10a/client/request_params")
+ response.rethrow()
+ parsed = json_decode(response.body)
+ self.assertEqual(parsed["oauth_consumer_key"], "asdf")
+ self.assertEqual(parsed["oauth_token"], "uiop")
+ self.assertIn("oauth_nonce", parsed)
+ self.assertIn("oauth_signature", parsed)
+
+ def test_oauth10a_get_user_coroutine_exception(self):
+ response = self.fetch(
+ "/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true",
+ headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="},
+ )
+ self.assertEqual(response.code, 503)
+
+ def test_oauth2_redirect(self):
+ response = self.fetch("/oauth2/client/login", follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertIn("/oauth2/server/authorize?", response.headers["Location"])
+
+ def test_facebook_login(self):
+ response = self.fetch("/facebook/client/login", follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertTrue("/facebook/server/authorize?" in response.headers["Location"])
+ response = self.fetch(
+ "/facebook/client/login?code=1234", follow_redirects=False
+ )
+ self.assertEqual(response.code, 200)
+ user = json_decode(response.body)
+ self.assertEqual(user["access_token"], "asdf")
+ self.assertEqual(user["session_expires"], "3600")
+
+ def base_twitter_redirect(self, url):
+ # Same as test_oauth10a_redirect
+ response = self.fetch(url, follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertTrue(
+ response.headers["Location"].endswith(
+ "/oauth1/server/authorize?oauth_token=zxcv"
+ )
+ )
+ # the cookie is base64('zxcv')|base64('1234')
+ self.assertIn(
+ '_oauth_request_token="enhjdg==|MTIzNA=="',
+ response.headers["Set-Cookie"],
+ response.headers["Set-Cookie"],
+ )
+
+ def test_twitter_redirect(self):
+ self.base_twitter_redirect("/twitter/client/login")
+
+ def test_twitter_redirect_gen_coroutine(self):
+ self.base_twitter_redirect("/twitter/client/login_gen_coroutine")
+
+ def test_twitter_authenticate_redirect(self):
+ response = self.fetch("/twitter/client/authenticate", follow_redirects=False)
+ self.assertEqual(response.code, 302)
+ self.assertTrue(
+ response.headers["Location"].endswith(
+ "/twitter/server/authenticate?oauth_token=zxcv"
+ ),
+ response.headers["Location"],
+ )
+ # the cookie is base64('zxcv')|base64('1234')
+ self.assertIn(
+ '_oauth_request_token="enhjdg==|MTIzNA=="',
+ response.headers["Set-Cookie"],
+ response.headers["Set-Cookie"],
+ )
+
+ def test_twitter_get_user(self):
+ response = self.fetch(
+ "/twitter/client/login?oauth_token=zxcv",
+ headers={"Cookie": "_oauth_request_token=enhjdg==|MTIzNA=="},
+ )
+ response.rethrow()
+ parsed = json_decode(response.body)
+ self.assertEqual(
+ parsed,
+ {
+ "access_token": {
+ "key": "hjkl",
+ "screen_name": "foo",
+ "secret": "vbnm",
+ },
+ "name": "Foo",
+ "screen_name": "foo",
+ "username": "foo",
+ },
+ )
+
+ def test_twitter_show_user(self):
+ response = self.fetch("/twitter/client/show_user?name=somebody")
+ response.rethrow()
+ self.assertEqual(
+ json_decode(response.body), {"name": "Somebody", "screen_name": "somebody"}
+ )
+
+ def test_twitter_show_user_error(self):
+ response = self.fetch("/twitter/client/show_user?name=error")
+ self.assertEqual(response.code, 500)
+ self.assertEqual(response.body, b"error from twitter request")
+
+
+class GoogleLoginHandler(RequestHandler, GoogleOAuth2Mixin):
+ def initialize(self, test):
+ self.test = test
+ self._OAUTH_REDIRECT_URI = test.get_url("/client/login")
+ self._OAUTH_AUTHORIZE_URL = test.get_url("/google/oauth2/authorize")
+ self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/google/oauth2/token")
+
+ @gen.coroutine
+ def get(self):
+ code = self.get_argument("code", None)
+ if code is not None:
+ # retrieve authenticate google user
+ access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI, code)
+ user = yield self.oauth2_request(
+ self.test.get_url("/google/oauth2/userinfo"),
+ access_token=access["access_token"],
+ )
+ # return the user and access token as json
+ user["access_token"] = access["access_token"]
+ self.write(user)
+ else:
+ self.authorize_redirect(
+ redirect_uri=self._OAUTH_REDIRECT_URI,
+ client_id=self.settings["google_oauth"]["key"],
+ scope=["profile", "email"],
+ response_type="code",
+ extra_params={"prompt": "select_account"},
+ )
+
+
+class GoogleOAuth2AuthorizeHandler(RequestHandler):
+ def get(self):
+ # issue a fake auth code and redirect to redirect_uri
+ code = "fake-authorization-code"
+ self.redirect(url_concat(self.get_argument("redirect_uri"), dict(code=code)))
+
+
+class GoogleOAuth2TokenHandler(RequestHandler):
+ def post(self):
+ assert self.get_argument("code") == "fake-authorization-code"
+ # issue a fake token
+ self.finish(
+ {"access_token": "fake-access-token", "expires_in": "never-expires"}
+ )
+
+
+class GoogleOAuth2UserinfoHandler(RequestHandler):
+ def get(self):
+ assert self.get_argument("access_token") == "fake-access-token"
+ # return a fake user
+ self.finish({"name": "Foo", "email": "foo@example.com"})
+
+
+class GoogleOAuth2Test(AsyncHTTPTestCase):
+ def get_app(self):
+ return Application(
+ [
+ # test endpoints
+ ("/client/login", GoogleLoginHandler, dict(test=self)),
+ # simulated google authorization server endpoints
+ ("/google/oauth2/authorize", GoogleOAuth2AuthorizeHandler),
+ ("/google/oauth2/token", GoogleOAuth2TokenHandler),
+ ("/google/oauth2/userinfo", GoogleOAuth2UserinfoHandler),
+ ],
+ google_oauth={
+ "key": "fake_google_client_id",
+ "secret": "fake_google_client_secret",
+ },
+ )
+
+ def test_google_login(self):
+ response = self.fetch("/client/login")
+ self.assertDictEqual(
+ {
+ "name": "Foo",
+ "email": "foo@example.com",
+ "access_token": "fake-access-token",
+ },
+ json_decode(response.body),
+ )
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/autoreload_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/autoreload_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..60fb30c61f9af067779faab19e0096dd8c168ba3
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/autoreload_test.py
@@ -0,0 +1,268 @@
+import os
+import shutil
+import subprocess
+from subprocess import Popen
+import sys
+from tempfile import mkdtemp
+import textwrap
+import time
+import unittest
+
+
+class AutoreloadTest(unittest.TestCase):
+ def setUp(self):
+ # When these tests fail the output sometimes exceeds the default maxDiff.
+ self.maxDiff = 1024
+
+ self.path = mkdtemp()
+
+ # Most test apps run themselves twice via autoreload. The first time it manually triggers
+ # a reload (could also do this by touching a file but this is faster since filesystem
+ # timestamps are not necessarily high resolution). The second time it exits directly
+ # so that the autoreload wrapper (if it is used) doesn't catch it.
+ #
+ # The last line of each such test's "main" program should be
+ # exec(open("run_twice_magic.py").read())
+ self.write_files(
+ {
+ "run_twice_magic.py": """
+ import os
+ import sys
+
+ import tornado.autoreload
+
+ sys.stdout.flush()
+
+ if "TESTAPP_STARTED" not in os.environ:
+ os.environ["TESTAPP_STARTED"] = "1"
+ tornado.autoreload._reload()
+ else:
+ os._exit(0)
+ """
+ }
+ )
+
+ def tearDown(self):
+ try:
+ shutil.rmtree(self.path)
+ except OSError:
+ # Windows disallows deleting files that are in use by
+ # another process, and even though we've waited for our
+ # child process below, it appears that its lock on these
+ # files is not guaranteed to be released by this point.
+ # Sleep and try again (once).
+ time.sleep(1)
+ shutil.rmtree(self.path)
+
+ def write_files(self, tree, base_path=None):
+ """Write a directory tree to self.path.
+
+ tree is a dictionary mapping file names to contents, or
+ sub-dictionaries representing subdirectories.
+ """
+ if base_path is None:
+ base_path = self.path
+ for name, contents in tree.items():
+ if isinstance(contents, dict):
+ os.mkdir(os.path.join(base_path, name))
+ self.write_files(contents, os.path.join(base_path, name))
+ else:
+ with open(os.path.join(base_path, name), "w", encoding="utf-8") as f:
+ f.write(textwrap.dedent(contents))
+
+ def run_subprocess(self, args):
+ # Make sure the tornado module under test is available to the test
+ # application
+ parts = [os.getcwd()]
+ if "PYTHONPATH" in os.environ:
+ parts += [
+ os.path.join(os.getcwd(), part)
+ for part in os.environ["PYTHONPATH"].split(os.pathsep)
+ ]
+ pythonpath = os.pathsep.join(parts)
+
+ p = Popen(
+ args,
+ stdout=subprocess.PIPE,
+ env=dict(os.environ, PYTHONPATH=pythonpath),
+ cwd=self.path,
+ universal_newlines=True,
+ encoding="utf-8",
+ )
+
+ # This timeout needs to be fairly generous for pypy due to jit
+ # warmup costs.
+ for i in range(40):
+ if p.poll() is not None:
+ break
+ time.sleep(0.1)
+ else:
+ p.kill()
+ raise Exception("subprocess failed to terminate")
+
+ out = p.communicate()[0]
+ self.assertEqual(p.returncode, 0)
+ return out
+
+ def test_reload(self):
+ main = """\
+import sys
+
+# In module mode, the path is set to the parent directory and we can import testapp.
+try:
+ import testapp
+except ImportError:
+ print("import testapp failed")
+else:
+ print("import testapp succeeded")
+
+spec = getattr(sys.modules[__name__], '__spec__', None)
+print(f"Starting {__name__=}, __spec__.name={getattr(spec, 'name', None)}")
+exec(open("run_twice_magic.py", encoding="utf-8").read())
+"""
+
+ # Create temporary test application
+ self.write_files(
+ {
+ "testapp": {
+ "__init__.py": "",
+ "__main__.py": main,
+ },
+ }
+ )
+
+ # The autoreload wrapper should support all the same modes as the python interpreter.
+ # The wrapper itself should have no effect on this test so we try all modes with and
+ # without it.
+ for wrapper in [False, True]:
+ with self.subTest(wrapper=wrapper):
+ with self.subTest(mode="module"):
+ if wrapper:
+ base_args = [sys.executable, "-m", "tornado.autoreload"]
+ else:
+ base_args = [sys.executable]
+ # In module mode, the path is set to the parent directory and we can import
+ # testapp. Also, the __spec__.name is set to the fully qualified module name.
+ out = self.run_subprocess(base_args + ["-m", "testapp"])
+ self.assertEqual(
+ out,
+ (
+ "import testapp succeeded\n"
+ + "Starting __name__='__main__', __spec__.name=testapp.__main__\n"
+ )
+ * 2,
+ )
+
+ with self.subTest(mode="file"):
+ out = self.run_subprocess(base_args + ["testapp/__main__.py"])
+ # In file mode, we do not expect the path to be set so we can import testapp,
+ # but when the wrapper is used the -m argument to the python interpreter
+ # does this for us.
+ expect_import = (
+ "import testapp succeeded"
+ if wrapper
+ else "import testapp failed"
+ )
+ # In file mode there is no qualified module spec.
+ self.assertEqual(
+ out,
+ f"{expect_import}\nStarting __name__='__main__', __spec__.name=None\n"
+ * 2,
+ )
+
+ with self.subTest(mode="directory"):
+ # Running as a directory finds __main__.py like a module. It does not manipulate
+ # sys.path but it does set a spec with a name of exactly __main__.
+ out = self.run_subprocess(base_args + ["testapp"])
+ expect_import = (
+ "import testapp succeeded"
+ if wrapper
+ else "import testapp failed"
+ )
+ self.assertEqual(
+ out,
+ f"{expect_import}\nStarting __name__='__main__', __spec__.name=__main__\n"
+ * 2,
+ )
+
+ def test_reload_wrapper_preservation(self):
+ # This test verifies that when `python -m tornado.autoreload`
+ # is used on an application that also has an internal
+ # autoreload, the reload wrapper is preserved on restart.
+ main = """\
+import sys
+
+# This import will fail if path is not set up correctly
+import testapp
+
+if 'tornado.autoreload' not in sys.modules:
+ raise Exception('started without autoreload wrapper')
+
+print('Starting')
+exec(open("run_twice_magic.py", encoding="utf-8").read())
+"""
+
+ self.write_files(
+ {
+ "testapp": {
+ "__init__.py": "",
+ "__main__.py": main,
+ },
+ }
+ )
+
+ out = self.run_subprocess(
+ [sys.executable, "-m", "tornado.autoreload", "-m", "testapp"]
+ )
+ self.assertEqual(out, "Starting\n" * 2)
+
+ def test_reload_wrapper_args(self):
+ main = """\
+import os
+import sys
+
+print(os.path.basename(sys.argv[0]))
+print(f'argv={sys.argv[1:]}')
+exec(open("run_twice_magic.py", encoding="utf-8").read())
+"""
+ # Create temporary test application
+ self.write_files({"main.py": main})
+
+ # Make sure the tornado module under test is available to the test
+ # application
+ out = self.run_subprocess(
+ [
+ sys.executable,
+ "-m",
+ "tornado.autoreload",
+ "main.py",
+ "arg1",
+ "--arg2",
+ "-m",
+ "arg3",
+ ],
+ )
+
+ self.assertEqual(out, "main.py\nargv=['arg1', '--arg2', '-m', 'arg3']\n" * 2)
+
+ def test_reload_wrapper_until_success(self):
+ main = """\
+import os
+import sys
+
+if "TESTAPP_STARTED" in os.environ:
+ print("exiting cleanly")
+ sys.exit(0)
+else:
+ print("reloading")
+ exec(open("run_twice_magic.py", encoding="utf-8").read())
+"""
+
+ # Create temporary test application
+ self.write_files({"main.py": main})
+
+ out = self.run_subprocess(
+ [sys.executable, "-m", "tornado.autoreload", "--until-success", "main.py"]
+ )
+
+ self.assertEqual(out, "reloading\nexiting cleanly\n")
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/circlerefs_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/circlerefs_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5f7e9692bd43bf6d2e1e7bc8fb8e5d754c87fdc
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/circlerefs_test.py
@@ -0,0 +1,217 @@
+"""Test script to find circular references.
+
+Circular references are not leaks per se, because they will eventually
+be GC'd. However, on CPython, they prevent the reference-counting fast
+path from being used and instead rely on the slower full GC. This
+increases memory footprint and CPU overhead, so we try to eliminate
+circular references created by normal operation.
+"""
+
+import asyncio
+import contextlib
+import gc
+import io
+import sys
+import traceback
+import types
+import typing
+import unittest
+
+import tornado
+from tornado import web, gen, httpclient
+from tornado.test.util import skipNotCPython
+
+
+def find_circular_references(garbage):
+ """Find circular references in a list of objects.
+
+ The garbage list contains objects that participate in a cycle,
+ but also the larger set of objects kept alive by that cycle.
+ This function finds subsets of those objects that make up
+ the cycle(s).
+ """
+
+ def inner(level):
+ for item in level:
+ item_id = id(item)
+ if item_id not in garbage_ids:
+ continue
+ if item_id in visited_ids:
+ continue
+ if item_id in stack_ids:
+ candidate = stack[stack.index(item) :]
+ candidate.append(item)
+ found.append(candidate)
+ continue
+
+ stack.append(item)
+ stack_ids.add(item_id)
+ inner(gc.get_referents(item))
+ stack.pop()
+ stack_ids.remove(item_id)
+ visited_ids.add(item_id)
+
+ found: typing.List[object] = []
+ stack = []
+ stack_ids = set()
+ garbage_ids = set(map(id, garbage))
+ visited_ids = set()
+
+ inner(garbage)
+ return found
+
+
+@contextlib.contextmanager
+def assert_no_cycle_garbage():
+ """Raise AssertionError if the wrapped code creates garbage with cycles."""
+ gc.disable()
+ gc.collect()
+ gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_SAVEALL)
+ yield
+ try:
+ # We have DEBUG_STATS on which causes gc.collect to write to stderr.
+ # Capture the output instead of spamming the logs on passing runs.
+ f = io.StringIO()
+ old_stderr = sys.stderr
+ sys.stderr = f
+ try:
+ gc.collect()
+ finally:
+ sys.stderr = old_stderr
+ garbage = gc.garbage[:]
+ # Must clear gc.garbage (the same object, not just replacing it with a
+ # new list) to avoid warnings at shutdown.
+ gc.garbage[:] = []
+ if len(garbage) == 0:
+ return
+ for circular in find_circular_references(garbage):
+ f.write("\n==========\n Circular \n==========")
+ for item in circular:
+ f.write(f"\n {repr(item)}")
+ for item in circular:
+ if isinstance(item, types.FrameType):
+ f.write(f"\nLocals: {item.f_locals}")
+ f.write(f"\nTraceback: {repr(item)}")
+ traceback.print_stack(item)
+ del garbage
+ raise AssertionError(f.getvalue())
+ finally:
+ gc.set_debug(0)
+ gc.enable()
+
+
+# GC behavior is cpython-specific
+@skipNotCPython
+class CircleRefsTest(unittest.TestCase):
+ def test_known_leak(self):
+ # Construct a known leak scenario to make sure the test harness works.
+ class C:
+ def __init__(self, name):
+ self.name = name
+ self.a: typing.Optional[C] = None
+ self.b: typing.Optional[C] = None
+ self.c: typing.Optional[C] = None
+
+ def __repr__(self):
+ return f"name={self.name}"
+
+ with self.assertRaises(AssertionError) as cm:
+ with assert_no_cycle_garbage():
+ # a and b form a reference cycle. c is not part of the cycle,
+ # but it cannot be GC'd while a and b are alive.
+ a = C("a")
+ b = C("b")
+ c = C("c")
+ a.b = b
+ a.c = c
+ b.a = a
+ b.c = c
+ del a, b
+ self.assertIn("Circular", str(cm.exception))
+ # Leading spaces ensure we only catch these at the beginning of a line, meaning they are a
+ # cycle participant and not simply the contents of a locals dict or similar container. (This
+ # depends on the formatting above which isn't ideal but this test evolved from a
+ # command-line script) Note that the behavior here changed in python 3.11; in newer pythons
+ # locals are handled a bit differently and the test passes without the spaces.
+ self.assertIn(" name=a", str(cm.exception))
+ self.assertIn(" name=b", str(cm.exception))
+ self.assertNotIn(" name=c", str(cm.exception))
+
+ async def run_handler(self, handler_class):
+ app = web.Application(
+ [
+ (r"/", handler_class),
+ ]
+ )
+ socket, port = tornado.testing.bind_unused_port()
+ server = tornado.httpserver.HTTPServer(app)
+ server.add_socket(socket)
+
+ client = httpclient.AsyncHTTPClient()
+ with assert_no_cycle_garbage():
+ # Only the fetch (and the corresponding server-side handler)
+ # are being tested for cycles. In particular, the Application
+ # object has internal cycles (as of this writing) which we don't
+ # care to fix since in real world usage the Application object
+ # is effectively a global singleton.
+ await client.fetch(f"http://127.0.0.1:{port}/")
+ client.close()
+ server.stop()
+ socket.close()
+
+ def test_sync_handler(self):
+ class Handler(web.RequestHandler):
+ def get(self):
+ self.write("ok\n")
+
+ asyncio.run(self.run_handler(Handler))
+
+ def test_finish_exception_handler(self):
+ class Handler(web.RequestHandler):
+ def get(self):
+ raise web.Finish("ok\n")
+
+ asyncio.run(self.run_handler(Handler))
+
+ def test_coro_handler(self):
+ class Handler(web.RequestHandler):
+ @gen.coroutine
+ def get(self):
+ yield asyncio.sleep(0.01)
+ self.write("ok\n")
+
+ asyncio.run(self.run_handler(Handler))
+
+ def test_async_handler(self):
+ class Handler(web.RequestHandler):
+ async def get(self):
+ await asyncio.sleep(0.01)
+ self.write("ok\n")
+
+ asyncio.run(self.run_handler(Handler))
+
+ def test_run_on_executor(self):
+ # From https://github.com/tornadoweb/tornado/issues/2620
+ #
+ # When this test was introduced it found cycles in IOLoop.add_future
+ # and tornado.concurrent.chain_future.
+ import concurrent.futures
+
+ with concurrent.futures.ThreadPoolExecutor(1) as thread_pool:
+
+ class Factory:
+ executor = thread_pool
+
+ @tornado.concurrent.run_on_executor
+ def run(self):
+ return None
+
+ factory = Factory()
+
+ async def main():
+ # The cycle is not reported on the first call. It's not clear why.
+ for i in range(2):
+ await factory.run()
+
+ with assert_no_cycle_garbage():
+ asyncio.run(main())
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/concurrent_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/concurrent_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..90fbcb12975b53571e7feea687126d7d9dbf39b5
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/concurrent_test.py
@@ -0,0 +1,231 @@
+#
+# 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.
+from concurrent import futures
+import logging
+import re
+import socket
+import unittest
+
+from tornado.concurrent import (
+ Future,
+ chain_future,
+ run_on_executor,
+ future_set_result_unless_cancelled,
+)
+from tornado.escape import utf8, to_unicode
+from tornado import gen
+from tornado.iostream import IOStream
+from tornado.tcpserver import TCPServer
+from tornado.testing import AsyncTestCase, bind_unused_port, gen_test
+
+
+class MiscFutureTest(AsyncTestCase):
+ def test_future_set_result_unless_cancelled(self):
+ fut = Future() # type: Future[int]
+ future_set_result_unless_cancelled(fut, 42)
+ self.assertEqual(fut.result(), 42)
+ self.assertFalse(fut.cancelled())
+
+ fut = Future()
+ fut.cancel()
+ is_cancelled = fut.cancelled()
+ future_set_result_unless_cancelled(fut, 42)
+ self.assertEqual(fut.cancelled(), is_cancelled)
+ if not is_cancelled:
+ self.assertEqual(fut.result(), 42)
+
+
+class ChainFutureTest(AsyncTestCase):
+ @gen_test
+ async def test_asyncio_futures(self):
+ fut: Future[int] = Future()
+ fut2: Future[int] = Future()
+ chain_future(fut, fut2)
+ fut.set_result(42)
+ result = await fut2
+ self.assertEqual(result, 42)
+
+ @gen_test
+ async def test_concurrent_futures(self):
+ # A three-step chain: two concurrent futures (showing that both arguments to chain_future
+ # can be concurrent futures), and then one from a concurrent future to an asyncio future so
+ # we can use it in await.
+ fut: futures.Future[int] = futures.Future()
+ fut2: futures.Future[int] = futures.Future()
+ fut3: Future[int] = Future()
+ chain_future(fut, fut2)
+ chain_future(fut2, fut3)
+ fut.set_result(42)
+ result = await fut3
+ self.assertEqual(result, 42)
+
+
+# The following series of classes demonstrate and test various styles
+# of use, with and without generators and futures.
+
+
+class CapServer(TCPServer):
+ @gen.coroutine
+ def handle_stream(self, stream, address):
+ data = yield stream.read_until(b"\n")
+ data = to_unicode(data)
+ if data == data.upper():
+ stream.write(b"error\talready capitalized\n")
+ else:
+ # data already has \n
+ stream.write(utf8("ok\t%s" % data.upper()))
+ stream.close()
+
+
+class CapError(Exception):
+ pass
+
+
+class BaseCapClient:
+ def __init__(self, port):
+ self.port = port
+
+ def process_response(self, data):
+ m = re.match("(.*)\t(.*)\n", to_unicode(data))
+ if m is None:
+ raise Exception("did not match")
+ status, message = m.groups()
+ if status == "ok":
+ return message
+ else:
+ raise CapError(message)
+
+
+class GeneratorCapClient(BaseCapClient):
+ @gen.coroutine
+ def capitalize(self, request_data):
+ logging.debug("capitalize")
+ stream = IOStream(socket.socket())
+ logging.debug("connecting")
+ yield stream.connect(("127.0.0.1", self.port))
+ stream.write(utf8(request_data + "\n"))
+ logging.debug("reading")
+ data = yield stream.read_until(b"\n")
+ logging.debug("returning")
+ stream.close()
+ raise gen.Return(self.process_response(data))
+
+
+class GeneratorCapClientTest(AsyncTestCase):
+ def setUp(self):
+ super().setUp()
+ self.server = CapServer()
+ sock, port = bind_unused_port()
+ self.server.add_sockets([sock])
+ self.client = GeneratorCapClient(port=port)
+
+ def tearDown(self):
+ self.server.stop()
+ super().tearDown()
+
+ def test_future(self):
+ future = self.client.capitalize("hello")
+ self.io_loop.add_future(future, self.stop)
+ self.wait()
+ self.assertEqual(future.result(), "HELLO")
+
+ def test_future_error(self):
+ future = self.client.capitalize("HELLO")
+ self.io_loop.add_future(future, self.stop)
+ self.wait()
+ self.assertRaisesRegex(CapError, "already capitalized", future.result)
+
+ def test_generator(self):
+ @gen.coroutine
+ def f():
+ result = yield self.client.capitalize("hello")
+ self.assertEqual(result, "HELLO")
+
+ self.io_loop.run_sync(f)
+
+ def test_generator_error(self):
+ @gen.coroutine
+ def f():
+ with self.assertRaisesRegex(CapError, "already capitalized"):
+ yield self.client.capitalize("HELLO")
+
+ self.io_loop.run_sync(f)
+
+
+class RunOnExecutorTest(AsyncTestCase):
+ @gen_test
+ def test_no_calling(self):
+ class Object:
+ def __init__(self):
+ self.executor = futures.thread.ThreadPoolExecutor(1)
+
+ @run_on_executor
+ def f(self):
+ return 42
+
+ o = Object()
+ answer = yield o.f()
+ self.assertEqual(answer, 42)
+
+ @gen_test
+ def test_call_with_no_args(self):
+ class Object:
+ def __init__(self):
+ self.executor = futures.thread.ThreadPoolExecutor(1)
+
+ @run_on_executor()
+ def f(self):
+ return 42
+
+ o = Object()
+ answer = yield o.f()
+ self.assertEqual(answer, 42)
+
+ @gen_test
+ def test_call_with_executor(self):
+ class Object:
+ def __init__(self):
+ self.__executor = futures.thread.ThreadPoolExecutor(1)
+
+ @run_on_executor(executor="_Object__executor")
+ def f(self):
+ return 42
+
+ o = Object()
+ answer = yield o.f()
+ self.assertEqual(answer, 42)
+
+ @gen_test
+ def test_async_await(self):
+ class Object:
+ def __init__(self):
+ self.executor = futures.thread.ThreadPoolExecutor(1)
+
+ @run_on_executor()
+ def f(self):
+ return 42
+
+ o = Object()
+
+ async def f():
+ answer = await o.f()
+ return answer
+
+ result = yield f()
+ self.assertEqual(result, 42)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/csv_translations/fr_FR.csv b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/csv_translations/fr_FR.csv
new file mode 100644
index 0000000000000000000000000000000000000000..6321b6e7c0864f629137ab7694f8987b98f71fab
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/csv_translations/fr_FR.csv
@@ -0,0 +1 @@
+"school","école"
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/curl_httpclient_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/curl_httpclient_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce3f68d7f779ea227aa4f590d37874d6f9dc1a16
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/curl_httpclient_test.py
@@ -0,0 +1,125 @@
+from hashlib import md5
+import unittest
+
+from tornado.escape import utf8
+from tornado.testing import AsyncHTTPTestCase
+from tornado.test import httpclient_test
+from tornado.web import Application, RequestHandler
+
+
+try:
+ import pycurl
+except ImportError:
+ pycurl = None # type: ignore
+
+if pycurl is not None:
+ from tornado.curl_httpclient import CurlAsyncHTTPClient
+
+
+@unittest.skipIf(pycurl is None, "pycurl module not present")
+class CurlHTTPClientCommonTestCase(httpclient_test.HTTPClientCommonTestCase):
+ def get_http_client(self):
+ client = CurlAsyncHTTPClient(defaults=dict(allow_ipv6=False))
+ # make sure AsyncHTTPClient magic doesn't give us the wrong class
+ self.assertTrue(isinstance(client, CurlAsyncHTTPClient))
+ return client
+
+
+class DigestAuthHandler(RequestHandler):
+ def initialize(self, username, password):
+ self.username = username
+ self.password = password
+
+ def get(self):
+ realm = "test"
+ opaque = "asdf"
+ # Real implementations would use a random nonce.
+ nonce = "1234"
+
+ auth_header = self.request.headers.get("Authorization", None)
+ if auth_header is not None:
+ auth_mode, params = auth_header.split(" ", 1)
+ assert auth_mode == "Digest"
+ param_dict = {}
+ for pair in params.split(","):
+ k, v = pair.strip().split("=", 1)
+ if v[0] == '"' and v[-1] == '"':
+ v = v[1:-1]
+ param_dict[k] = v
+ assert param_dict["realm"] == realm
+ assert param_dict["opaque"] == opaque
+ assert param_dict["nonce"] == nonce
+ assert param_dict["username"] == self.username
+ assert param_dict["uri"] == self.request.path
+ h1 = md5(utf8(f"{self.username}:{realm}:{self.password}")).hexdigest()
+ h2 = md5(utf8(f"{self.request.method}:{self.request.path}")).hexdigest()
+ digest = md5(utf8(f"{h1}:{nonce}:{h2}")).hexdigest()
+ if digest == param_dict["response"]:
+ self.write("ok")
+ else:
+ self.write("fail")
+ else:
+ self.set_status(401)
+ self.set_header(
+ "WWW-Authenticate",
+ f'Digest realm="{realm}", nonce="{nonce}", opaque="{opaque}"',
+ )
+
+
+class CustomReasonHandler(RequestHandler):
+ def get(self):
+ self.set_status(200, "Custom reason")
+
+
+class CustomFailReasonHandler(RequestHandler):
+ def get(self):
+ self.set_status(400, "Custom reason")
+
+
+@unittest.skipIf(pycurl is None, "pycurl module not present")
+class CurlHTTPClientTestCase(AsyncHTTPTestCase):
+ def setUp(self):
+ super().setUp()
+ self.http_client = self.create_client()
+
+ def get_app(self):
+ return Application(
+ [
+ ("/digest", DigestAuthHandler, {"username": "foo", "password": "bar"}),
+ (
+ "/digest_non_ascii",
+ DigestAuthHandler,
+ {"username": "foo", "password": "barユ£"},
+ ),
+ ("/custom_reason", CustomReasonHandler),
+ ("/custom_fail_reason", CustomFailReasonHandler),
+ ]
+ )
+
+ def create_client(self, **kwargs):
+ return CurlAsyncHTTPClient(
+ force_instance=True, defaults=dict(allow_ipv6=False), **kwargs
+ )
+
+ def test_digest_auth(self):
+ response = self.fetch(
+ "/digest", auth_mode="digest", auth_username="foo", auth_password="bar"
+ )
+ self.assertEqual(response.body, b"ok")
+
+ def test_custom_reason(self):
+ response = self.fetch("/custom_reason")
+ self.assertEqual(response.reason, "Custom reason")
+
+ def test_fail_custom_reason(self):
+ response = self.fetch("/custom_fail_reason")
+ self.assertEqual(str(response.error), "HTTP 400: Custom reason")
+
+ def test_digest_auth_non_ascii(self):
+ response = self.fetch(
+ "/digest_non_ascii",
+ auth_mode="digest",
+ auth_username="foo",
+ auth_password="barユ£",
+ )
+ self.assertEqual(response.body, b"ok")
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/escape_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/escape_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9614dcb7a8d248f75558001df21cb9462fe396e
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/escape_test.py
@@ -0,0 +1,324 @@
+import unittest
+
+import tornado
+from tornado.escape import (
+ utf8,
+ xhtml_escape,
+ xhtml_unescape,
+ url_escape,
+ url_unescape,
+ to_unicode,
+ json_decode,
+ json_encode,
+ squeeze,
+ recursive_unicode,
+)
+from tornado.util import unicode_type
+
+from typing import List, Tuple, Union, Dict, Any # noqa: F401
+
+linkify_tests = [
+ # (input, linkify_kwargs, expected_output)
+ (
+ "hello http://world.com/!",
+ {},
+ 'hello http://world.com/!',
+ ),
+ (
+ "hello http://world.com/with?param=true&stuff=yes",
+ {},
+ 'hello http://world.com/with?param=true&stuff=yes', # noqa: E501
+ ),
+ # an opened paren followed by many chars killed Gruber's regex
+ (
+ "http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ {},
+ 'http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', # noqa: E501
+ ),
+ # as did too many dots at the end
+ (
+ "http://url.com/withmany.......................................",
+ {},
+ 'http://url.com/withmany.......................................', # noqa: E501
+ ),
+ (
+ "http://url.com/withmany((((((((((((((((((((((((((((((((((a)",
+ {},
+ 'http://url.com/withmany((((((((((((((((((((((((((((((((((a)', # noqa: E501
+ ),
+ # some examples from http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
+ # plus a fex extras (such as multiple parentheses).
+ (
+ "http://foo.com/blah_blah",
+ {},
+ 'http://foo.com/blah_blah',
+ ),
+ (
+ "http://foo.com/blah_blah/",
+ {},
+ 'http://foo.com/blah_blah/',
+ ),
+ (
+ "(Something like http://foo.com/blah_blah)",
+ {},
+ '(Something like http://foo.com/blah_blah)',
+ ),
+ (
+ "http://foo.com/blah_blah_(wikipedia)",
+ {},
+ 'http://foo.com/blah_blah_(wikipedia)',
+ ),
+ (
+ "http://foo.com/blah_(blah)_(wikipedia)_blah",
+ {},
+ 'http://foo.com/blah_(blah)_(wikipedia)_blah', # noqa: E501
+ ),
+ (
+ "(Something like http://foo.com/blah_blah_(wikipedia))",
+ {},
+ '(Something like http://foo.com/blah_blah_(wikipedia))', # noqa: E501
+ ),
+ (
+ "http://foo.com/blah_blah.",
+ {},
+ 'http://foo.com/blah_blah.',
+ ),
+ (
+ "http://foo.com/blah_blah/.",
+ {},
+ 'http://foo.com/blah_blah/.',
+ ),
+ (
+ "",
+ {},
+ '<http://foo.com/blah_blah>',
+ ),
+ (
+ "",
+ {},
+ '<http://foo.com/blah_blah/>',
+ ),
+ (
+ "http://foo.com/blah_blah,",
+ {},
+ 'http://foo.com/blah_blah,',
+ ),
+ (
+ "http://www.example.com/wpstyle/?p=364.",
+ {},
+ 'http://www.example.com/wpstyle/?p=364.', # noqa: E501
+ ),
+ (
+ "rdar://1234",
+ {"permitted_protocols": ["http", "rdar"]},
+ 'rdar://1234',
+ ),
+ (
+ "rdar:/1234",
+ {"permitted_protocols": ["rdar"]},
+ 'rdar:/1234',
+ ),
+ (
+ "http://userid:password@example.com:8080",
+ {},
+ 'http://userid:password@example.com:8080', # noqa: E501
+ ),
+ (
+ "http://userid@example.com",
+ {},
+ 'http://userid@example.com',
+ ),
+ (
+ "http://userid@example.com:8080",
+ {},
+ 'http://userid@example.com:8080',
+ ),
+ (
+ "http://userid:password@example.com",
+ {},
+ 'http://userid:password@example.com',
+ ),
+ (
+ "message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e",
+ {"permitted_protocols": ["http", "message"]},
+ ''
+ "message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e",
+ ),
+ (
+ "http://\u27a1.ws/\u4a39",
+ {},
+ 'http://\u27a1.ws/\u4a39',
+ ),
+ (
+ "http://example.com",
+ {},
+ '<tag>http://example.com</tag>',
+ ),
+ (
+ "Just a www.example.com link.",
+ {},
+ 'Just a www.example.com link.',
+ ),
+ (
+ "Just a www.example.com link.",
+ {"require_protocol": True},
+ "Just a www.example.com link.",
+ ),
+ (
+ "A http://reallylong.com/link/that/exceedsthelenglimit.html",
+ {"require_protocol": True, "shorten": True},
+ 'A http://reallylong.com/link...', # noqa: E501
+ ),
+ (
+ "A http://reallylongdomainnamethatwillbetoolong.com/hi!",
+ {"shorten": True},
+ 'A http://reallylongdomainnametha...!', # noqa: E501
+ ),
+ (
+ "A file:///passwords.txt and http://web.com link",
+ {},
+ 'A file:///passwords.txt and http://web.com link',
+ ),
+ (
+ "A file:///passwords.txt and http://web.com link",
+ {"permitted_protocols": ["file"]},
+ 'A file:///passwords.txt and http://web.com link',
+ ),
+ (
+ "www.external-link.com",
+ {"extra_params": 'rel="nofollow" class="external"'},
+ 'www.external-link.com', # noqa: E501
+ ),
+ (
+ "www.external-link.com and www.internal-link.com/blogs extra",
+ {
+ "extra_params": lambda href: (
+ 'class="internal"'
+ if href.startswith("http://www.internal-link.com")
+ else 'rel="nofollow" class="external"'
+ )
+ },
+ 'www.external-link.com' # noqa: E501
+ ' and www.internal-link.com/blogs extra', # noqa: E501
+ ),
+ (
+ "www.external-link.com",
+ {"extra_params": lambda href: ' rel="nofollow" class="external" '},
+ 'www.external-link.com', # noqa: E501
+ ),
+] # type: List[Tuple[Union[str, bytes], Dict[str, Any], str]]
+
+
+class EscapeTestCase(unittest.TestCase):
+ def test_linkify(self):
+ for text, kwargs, html in linkify_tests:
+ linked = tornado.escape.linkify(text, **kwargs)
+ self.assertEqual(linked, html)
+
+ def test_xhtml_escape(self):
+ tests = [
+ ("", "<foo>"),
+ ("", "<foo>"),
+ (b"", b"<foo>"),
+ ("<>&\"'", "<>&"'"),
+ ("&", "&"),
+ ("<\u00e9>", "<\u00e9>"),
+ (b"<\xc3\xa9>", b"<\xc3\xa9>"),
+ ] # type: List[Tuple[Union[str, bytes], Union[str, bytes]]]
+ for unescaped, escaped in tests:
+ self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped))
+ self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped)))
+
+ def test_xhtml_unescape_numeric(self):
+ tests = [
+ ("foo bar", "foo bar"),
+ ("foo bar", "foo bar"),
+ ("foo bar", "foo bar"),
+ ("foo઼bar", "foo\u0abcbar"),
+ ("fooyz;bar", "fooyz;bar"), # invalid encoding
+ ("foobar", "foobar"), # invalid encoding
+ ("foobar", "foobar"), # invalid encoding
+ ]
+ for escaped, unescaped in tests:
+ self.assertEqual(unescaped, xhtml_unescape(escaped))
+
+ def test_url_escape_unicode(self):
+ tests = [
+ # byte strings are passed through as-is
+ ("\u00e9".encode(), "%C3%A9"),
+ ("\u00e9".encode("latin1"), "%E9"),
+ # unicode strings become utf8
+ ("\u00e9", "%C3%A9"),
+ ] # type: List[Tuple[Union[str, bytes], str]]
+ for unescaped, escaped in tests:
+ self.assertEqual(url_escape(unescaped), escaped)
+
+ def test_url_unescape_unicode(self):
+ tests = [
+ ("%C3%A9", "\u00e9", "utf8"),
+ ("%C3%A9", "\u00c3\u00a9", "latin1"),
+ ("%C3%A9", utf8("\u00e9"), None),
+ ]
+ for escaped, unescaped, encoding in tests:
+ # input strings to url_unescape should only contain ascii
+ # characters, but make sure the function accepts both byte
+ # and unicode strings.
+ self.assertEqual(url_unescape(to_unicode(escaped), encoding), unescaped)
+ self.assertEqual(url_unescape(utf8(escaped), encoding), unescaped)
+
+ def test_url_escape_quote_plus(self):
+ unescaped = "+ #%"
+ plus_escaped = "%2B+%23%25"
+ escaped = "%2B%20%23%25"
+ self.assertEqual(url_escape(unescaped), plus_escaped)
+ self.assertEqual(url_escape(unescaped, plus=False), escaped)
+ self.assertEqual(url_unescape(plus_escaped), unescaped)
+ self.assertEqual(url_unescape(escaped, plus=False), unescaped)
+ self.assertEqual(url_unescape(plus_escaped, encoding=None), utf8(unescaped))
+ self.assertEqual(
+ url_unescape(escaped, encoding=None, plus=False), utf8(unescaped)
+ )
+
+ def test_escape_return_types(self):
+ # On python2 the escape methods should generally return the same
+ # type as their argument
+ self.assertEqual(type(xhtml_escape("foo")), str)
+ self.assertEqual(type(xhtml_escape("foo")), unicode_type)
+
+ def test_json_decode(self):
+ # json_decode accepts both bytes and unicode, but strings it returns
+ # are always unicode.
+ self.assertEqual(json_decode(b'"foo"'), "foo")
+ self.assertEqual(json_decode('"foo"'), "foo")
+
+ # Non-ascii bytes are interpreted as utf8
+ self.assertEqual(json_decode(utf8('"\u00e9"')), "\u00e9")
+
+ def test_json_encode(self):
+ # json deals with strings, not bytes. On python 2 byte strings will
+ # convert automatically if they are utf8; on python 3 byte strings
+ # are not allowed.
+ self.assertEqual(json_decode(json_encode("\u00e9")), "\u00e9")
+ if bytes is str:
+ self.assertEqual(json_decode(json_encode(utf8("\u00e9"))), "\u00e9")
+ self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9")
+
+ def test_squeeze(self):
+ self.assertEqual(
+ squeeze("sequences of whitespace chars"),
+ "sequences of whitespace chars",
+ )
+
+ def test_recursive_unicode(self):
+ tests = {
+ "dict": {b"foo": b"bar"},
+ "list": [b"foo", b"bar"],
+ "tuple": (b"foo", b"bar"),
+ "bytes": b"foo",
+ }
+ self.assertEqual(recursive_unicode(tests["dict"]), {"foo": "bar"})
+ self.assertEqual(recursive_unicode(tests["list"]), ["foo", "bar"])
+ self.assertEqual(recursive_unicode(tests["tuple"]), ("foo", "bar"))
+ self.assertEqual(recursive_unicode(tests["bytes"]), "foo")
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gen_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gen_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..71fdceb1c9726d302aed5f55b38f895ef7c07223
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gen_test.py
@@ -0,0 +1,1123 @@
+import asyncio
+from concurrent import futures
+import gc
+import datetime
+import platform
+import sys
+import time
+import weakref
+import unittest
+
+from tornado.concurrent import Future
+from tornado.log import app_log
+from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test
+from tornado.test.util import skipNotCPython
+from tornado.web import Application, RequestHandler, HTTPError
+
+from tornado import gen
+
+try:
+ import contextvars
+except ImportError:
+ contextvars = None # type: ignore
+
+import typing
+
+if typing.TYPE_CHECKING:
+ from typing import List, Optional # noqa: F401
+
+
+class GenBasicTest(AsyncTestCase):
+ @gen.coroutine
+ def delay(self, iterations, arg):
+ """Returns arg after a number of IOLoop iterations."""
+ for i in range(iterations):
+ yield gen.moment
+ raise gen.Return(arg)
+
+ @gen.coroutine
+ def async_future(self, result):
+ yield gen.moment
+ return result
+
+ @gen.coroutine
+ def async_exception(self, e):
+ yield gen.moment
+ raise e
+
+ @gen.coroutine
+ def add_one_async(self, x):
+ yield gen.moment
+ raise gen.Return(x + 1)
+
+ def test_no_yield(self):
+ @gen.coroutine
+ def f():
+ pass
+
+ self.io_loop.run_sync(f)
+
+ def test_exception_phase1(self):
+ @gen.coroutine
+ def f():
+ 1 / 0
+
+ self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)
+
+ def test_exception_phase2(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ 1 / 0
+
+ self.assertRaises(ZeroDivisionError, self.io_loop.run_sync, f)
+
+ def test_bogus_yield(self):
+ @gen.coroutine
+ def f():
+ yield 42
+
+ self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)
+
+ def test_bogus_yield_tuple(self):
+ @gen.coroutine
+ def f():
+ yield (1, 2)
+
+ self.assertRaises(gen.BadYieldError, self.io_loop.run_sync, f)
+
+ def test_reuse(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+
+ self.io_loop.run_sync(f)
+ self.io_loop.run_sync(f)
+
+ def test_none(self):
+ @gen.coroutine
+ def f():
+ yield None
+
+ self.io_loop.run_sync(f)
+
+ def test_multi(self):
+ @gen.coroutine
+ def f():
+ results = yield [self.add_one_async(1), self.add_one_async(2)]
+ self.assertEqual(results, [2, 3])
+
+ self.io_loop.run_sync(f)
+
+ def test_multi_dict(self):
+ @gen.coroutine
+ def f():
+ results = yield dict(foo=self.add_one_async(1), bar=self.add_one_async(2))
+ self.assertEqual(results, dict(foo=2, bar=3))
+
+ self.io_loop.run_sync(f)
+
+ def test_multi_delayed(self):
+ @gen.coroutine
+ def f():
+ # callbacks run at different times
+ responses = yield gen.multi_future(
+ [self.delay(3, "v1"), self.delay(1, "v2")]
+ )
+ self.assertEqual(responses, ["v1", "v2"])
+
+ self.io_loop.run_sync(f)
+
+ def test_multi_dict_delayed(self):
+ @gen.coroutine
+ def f():
+ # callbacks run at different times
+ responses = yield gen.multi_future(
+ dict(foo=self.delay(3, "v1"), bar=self.delay(1, "v2"))
+ )
+ self.assertEqual(responses, dict(foo="v1", bar="v2"))
+
+ self.io_loop.run_sync(f)
+
+ @gen_test
+ def test_multi_performance(self):
+ # Yielding a list used to have quadratic performance; make
+ # sure a large list stays reasonable. On my laptop a list of
+ # 2000 used to take 1.8s, now it takes 0.12.
+ start = time.time()
+ yield [gen.moment for i in range(2000)]
+ end = time.time()
+ self.assertLess(end - start, 1.0)
+
+ @gen_test
+ def test_multi_empty(self):
+ # Empty lists or dicts should return the same type.
+ x = yield []
+ self.assertTrue(isinstance(x, list))
+ y = yield {}
+ self.assertTrue(isinstance(y, dict))
+
+ @gen_test
+ def test_future(self):
+ result = yield self.async_future(1)
+ self.assertEqual(result, 1)
+
+ @gen_test
+ def test_multi_future(self):
+ results = yield [self.async_future(1), self.async_future(2)]
+ self.assertEqual(results, [1, 2])
+
+ @gen_test
+ def test_multi_future_duplicate(self):
+ # Note that this doesn't work with native corotines, only with
+ # decorated coroutines.
+ f = self.async_future(2)
+ results = yield [self.async_future(1), f, self.async_future(3), f]
+ self.assertEqual(results, [1, 2, 3, 2])
+
+ @gen_test
+ def test_multi_dict_future(self):
+ results = yield dict(foo=self.async_future(1), bar=self.async_future(2))
+ self.assertEqual(results, dict(foo=1, bar=2))
+
+ @gen_test
+ def test_multi_exceptions(self):
+ with ExpectLog(app_log, "Multiple exceptions in yield list"):
+ with self.assertRaises(RuntimeError) as cm:
+ yield gen.Multi(
+ [
+ self.async_exception(RuntimeError("error 1")),
+ self.async_exception(RuntimeError("error 2")),
+ ]
+ )
+ self.assertEqual(str(cm.exception), "error 1")
+
+ # With only one exception, no error is logged.
+ with self.assertRaises(RuntimeError):
+ yield gen.Multi(
+ [self.async_exception(RuntimeError("error 1")), self.async_future(2)]
+ )
+
+ # Exception logging may be explicitly quieted.
+ with self.assertRaises(RuntimeError):
+ yield gen.Multi(
+ [
+ self.async_exception(RuntimeError("error 1")),
+ self.async_exception(RuntimeError("error 2")),
+ ],
+ quiet_exceptions=RuntimeError,
+ )
+
+ @gen_test
+ def test_multi_future_exceptions(self):
+ with ExpectLog(app_log, "Multiple exceptions in yield list"):
+ with self.assertRaises(RuntimeError) as cm:
+ yield [
+ self.async_exception(RuntimeError("error 1")),
+ self.async_exception(RuntimeError("error 2")),
+ ]
+ self.assertEqual(str(cm.exception), "error 1")
+
+ # With only one exception, no error is logged.
+ with self.assertRaises(RuntimeError):
+ yield [self.async_exception(RuntimeError("error 1")), self.async_future(2)]
+
+ # Exception logging may be explicitly quieted.
+ with self.assertRaises(RuntimeError):
+ yield gen.multi_future(
+ [
+ self.async_exception(RuntimeError("error 1")),
+ self.async_exception(RuntimeError("error 2")),
+ ],
+ quiet_exceptions=RuntimeError,
+ )
+
+ def test_sync_raise_return(self):
+ @gen.coroutine
+ def f():
+ raise gen.Return()
+
+ self.io_loop.run_sync(f)
+
+ def test_async_raise_return(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ raise gen.Return()
+
+ self.io_loop.run_sync(f)
+
+ def test_sync_raise_return_value(self):
+ @gen.coroutine
+ def f():
+ raise gen.Return(42)
+
+ self.assertEqual(42, self.io_loop.run_sync(f))
+
+ def test_sync_raise_return_value_tuple(self):
+ @gen.coroutine
+ def f():
+ raise gen.Return((1, 2))
+
+ self.assertEqual((1, 2), self.io_loop.run_sync(f))
+
+ def test_async_raise_return_value(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ raise gen.Return(42)
+
+ self.assertEqual(42, self.io_loop.run_sync(f))
+
+ def test_async_raise_return_value_tuple(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ raise gen.Return((1, 2))
+
+ self.assertEqual((1, 2), self.io_loop.run_sync(f))
+
+
+class GenCoroutineTest(AsyncTestCase):
+ def setUp(self):
+ # Stray StopIteration exceptions can lead to tests exiting prematurely,
+ # so we need explicit checks here to make sure the tests run all
+ # the way through.
+ self.finished = False
+ super().setUp()
+
+ def tearDown(self):
+ super().tearDown()
+ assert self.finished
+
+ def test_attributes(self):
+ self.finished = True
+
+ def f():
+ yield gen.moment
+
+ coro = gen.coroutine(f)
+ self.assertEqual(coro.__name__, f.__name__)
+ self.assertEqual(coro.__module__, f.__module__)
+ self.assertIs(coro.__wrapped__, f) # type: ignore
+
+ def test_is_coroutine_function(self):
+ self.finished = True
+
+ def f():
+ yield gen.moment
+
+ coro = gen.coroutine(f)
+ self.assertFalse(gen.is_coroutine_function(f))
+ self.assertTrue(gen.is_coroutine_function(coro))
+ self.assertFalse(gen.is_coroutine_function(coro()))
+
+ @gen_test
+ def test_sync_gen_return(self):
+ @gen.coroutine
+ def f():
+ raise gen.Return(42)
+
+ result = yield f()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_async_gen_return(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ raise gen.Return(42)
+
+ result = yield f()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_sync_return(self):
+ @gen.coroutine
+ def f():
+ return 42
+
+ result = yield f()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_async_return(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ return 42
+
+ result = yield f()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_async_early_return(self):
+ # A yield statement exists but is not executed, which means
+ # this function "returns" via an exception. This exception
+ # doesn't happen before the exception handling is set up.
+ @gen.coroutine
+ def f():
+ if True:
+ return 42
+ yield gen.Task(self.io_loop.add_callback)
+
+ result = yield f()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_async_await(self):
+ @gen.coroutine
+ def f1():
+ yield gen.moment
+ raise gen.Return(42)
+
+ # This test verifies that an async function can await a
+ # yield-based gen.coroutine, and that a gen.coroutine
+ # (the test method itself) can yield an async function.
+ async def f2():
+ result = await f1()
+ return result
+
+ result = yield f2()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_asyncio_sleep_zero(self):
+ # asyncio.sleep(0) turns into a special case (equivalent to
+ # `yield None`)
+ async def f():
+ import asyncio
+
+ await asyncio.sleep(0)
+ return 42
+
+ result = yield f()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_async_await_mixed_multi_native_future(self):
+ @gen.coroutine
+ def f1():
+ yield gen.moment
+
+ async def f2():
+ await f1()
+ return 42
+
+ @gen.coroutine
+ def f3():
+ yield gen.moment
+ raise gen.Return(43)
+
+ results = yield [f2(), f3()]
+ self.assertEqual(results, [42, 43])
+ self.finished = True
+
+ @gen_test
+ def test_async_with_timeout(self):
+ async def f1():
+ return 42
+
+ result = yield gen.with_timeout(datetime.timedelta(hours=1), f1())
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_sync_return_no_value(self):
+ @gen.coroutine
+ def f():
+ return
+
+ result = yield f()
+ self.assertIsNone(result)
+ self.finished = True
+
+ @gen_test
+ def test_async_return_no_value(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ return
+
+ result = yield f()
+ self.assertIsNone(result)
+ self.finished = True
+
+ @gen_test
+ def test_sync_raise(self):
+ @gen.coroutine
+ def f():
+ 1 / 0
+
+ # The exception is raised when the future is yielded
+ # (or equivalently when its result method is called),
+ # not when the function itself is called).
+ future = f()
+ with self.assertRaises(ZeroDivisionError):
+ yield future
+ self.finished = True
+
+ @gen_test
+ def test_async_raise(self):
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ 1 / 0
+
+ future = f()
+ with self.assertRaises(ZeroDivisionError):
+ yield future
+ self.finished = True
+
+ @gen_test
+ def test_replace_yieldpoint_exception(self):
+ # Test exception handling: a coroutine can catch one exception
+ # raised by a yield point and raise a different one.
+ @gen.coroutine
+ def f1():
+ 1 / 0
+
+ @gen.coroutine
+ def f2():
+ try:
+ yield f1()
+ except ZeroDivisionError:
+ raise KeyError()
+
+ future = f2()
+ with self.assertRaises(KeyError):
+ yield future
+ self.finished = True
+
+ @gen_test
+ def test_swallow_yieldpoint_exception(self):
+ # Test exception handling: a coroutine can catch an exception
+ # raised by a yield point and not raise a different one.
+ @gen.coroutine
+ def f1():
+ 1 / 0
+
+ @gen.coroutine
+ def f2():
+ try:
+ yield f1()
+ except ZeroDivisionError:
+ raise gen.Return(42)
+
+ result = yield f2()
+ self.assertEqual(result, 42)
+ self.finished = True
+
+ @gen_test
+ def test_moment(self):
+ calls = []
+
+ @gen.coroutine
+ def f(name, yieldable):
+ for i in range(5):
+ calls.append(name)
+ yield yieldable
+
+ # First, confirm the behavior without moment: each coroutine
+ # monopolizes the event loop until it finishes.
+ immediate = Future() # type: Future[None]
+ immediate.set_result(None)
+ yield [f("a", immediate), f("b", immediate)]
+ self.assertEqual("".join(calls), "aaaaabbbbb")
+
+ # With moment, they take turns.
+ calls = []
+ yield [f("a", gen.moment), f("b", gen.moment)]
+ self.assertEqual("".join(calls), "ababababab")
+ self.finished = True
+
+ calls = []
+ yield [f("a", gen.moment), f("b", immediate)]
+ self.assertEqual("".join(calls), "abbbbbaaaa")
+
+ @gen_test
+ def test_sleep(self):
+ yield gen.sleep(0.01)
+ self.finished = True
+
+ @gen_test
+ def test_py3_leak_exception_context(self):
+ class LeakedException(Exception):
+ pass
+
+ @gen.coroutine
+ def inner(iteration):
+ raise LeakedException(iteration)
+
+ try:
+ yield inner(1)
+ except LeakedException as e:
+ self.assertEqual(str(e), "1")
+ self.assertIsNone(e.__context__)
+
+ try:
+ yield inner(2)
+ except LeakedException as e:
+ self.assertEqual(str(e), "2")
+ self.assertIsNone(e.__context__)
+
+ self.finished = True
+
+ @skipNotCPython
+ def test_coroutine_refcounting(self):
+ # On CPython, tasks and their arguments should be released immediately
+ # without waiting for garbage collection.
+ @gen.coroutine
+ def inner():
+ class Foo:
+ pass
+
+ local_var = Foo()
+ self.local_ref = weakref.ref(local_var)
+
+ def dummy():
+ pass
+
+ yield gen.coroutine(dummy)()
+ raise ValueError("Some error")
+
+ @gen.coroutine
+ def inner2():
+ try:
+ yield inner()
+ except ValueError:
+ pass
+
+ self.io_loop.run_sync(inner2, timeout=3)
+
+ self.assertIsNone(self.local_ref())
+ self.finished = True
+
+ def test_asyncio_future_debug_info(self):
+ self.finished = True
+ # Enable debug mode
+ asyncio_loop = asyncio.get_event_loop()
+ self.addCleanup(asyncio_loop.set_debug, asyncio_loop.get_debug())
+ asyncio_loop.set_debug(True)
+
+ def f():
+ yield gen.moment
+
+ coro = gen.coroutine(f)()
+ self.assertIsInstance(coro, asyncio.Future)
+ # We expect the coroutine repr() to show the place where
+ # it was instantiated
+ expected = "created at %s:%d" % (__file__, f.__code__.co_firstlineno + 3)
+ actual = repr(coro)
+ self.assertIn(expected, actual)
+
+ @gen_test
+ def test_asyncio_gather(self):
+ # This demonstrates that tornado coroutines can be understood
+ # by asyncio (This failed prior to Tornado 5.0).
+ @gen.coroutine
+ def f():
+ yield gen.moment
+ raise gen.Return(1)
+
+ ret = yield asyncio.gather(f(), f())
+ self.assertEqual(ret, [1, 1])
+ self.finished = True
+
+
+class GenCoroutineSequenceHandler(RequestHandler):
+ @gen.coroutine
+ def get(self):
+ yield gen.moment
+ self.write("1")
+ yield gen.moment
+ self.write("2")
+ yield gen.moment
+ self.finish("3")
+
+
+class GenCoroutineUnfinishedSequenceHandler(RequestHandler):
+ @gen.coroutine
+ def get(self):
+ yield gen.moment
+ self.write("1")
+ yield gen.moment
+ self.write("2")
+ yield gen.moment
+ # just write, don't finish
+ self.write("3")
+
+
+# "Undecorated" here refers to the absence of @asynchronous.
+class UndecoratedCoroutinesHandler(RequestHandler):
+ @gen.coroutine
+ def prepare(self):
+ self.chunks = [] # type: List[str]
+ yield gen.moment
+ self.chunks.append("1")
+
+ @gen.coroutine
+ def get(self):
+ self.chunks.append("2")
+ yield gen.moment
+ self.chunks.append("3")
+ yield gen.moment
+ self.write("".join(self.chunks))
+
+
+class AsyncPrepareErrorHandler(RequestHandler):
+ @gen.coroutine
+ def prepare(self):
+ yield gen.moment
+ raise HTTPError(403)
+
+ def get(self):
+ self.finish("ok")
+
+
+class NativeCoroutineHandler(RequestHandler):
+ async def get(self):
+ await asyncio.sleep(0)
+ self.write("ok")
+
+
+class GenWebTest(AsyncHTTPTestCase):
+ def get_app(self):
+ return Application(
+ [
+ ("/coroutine_sequence", GenCoroutineSequenceHandler),
+ (
+ "/coroutine_unfinished_sequence",
+ GenCoroutineUnfinishedSequenceHandler,
+ ),
+ ("/undecorated_coroutine", UndecoratedCoroutinesHandler),
+ ("/async_prepare_error", AsyncPrepareErrorHandler),
+ ("/native_coroutine", NativeCoroutineHandler),
+ ]
+ )
+
+ def test_coroutine_sequence_handler(self):
+ response = self.fetch("/coroutine_sequence")
+ self.assertEqual(response.body, b"123")
+
+ def test_coroutine_unfinished_sequence_handler(self):
+ response = self.fetch("/coroutine_unfinished_sequence")
+ self.assertEqual(response.body, b"123")
+
+ def test_undecorated_coroutines(self):
+ response = self.fetch("/undecorated_coroutine")
+ self.assertEqual(response.body, b"123")
+
+ def test_async_prepare_error_handler(self):
+ response = self.fetch("/async_prepare_error")
+ self.assertEqual(response.code, 403)
+
+ def test_native_coroutine_handler(self):
+ response = self.fetch("/native_coroutine")
+ self.assertEqual(response.code, 200)
+ self.assertEqual(response.body, b"ok")
+
+
+class WithTimeoutTest(AsyncTestCase):
+ @gen_test
+ def test_timeout(self):
+ with self.assertRaises(gen.TimeoutError):
+ yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future())
+
+ @gen_test
+ def test_completes_before_timeout(self):
+ future = Future() # type: Future[str]
+ self.io_loop.add_timeout(
+ datetime.timedelta(seconds=0.1), lambda: future.set_result("asdf")
+ )
+ result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)
+ self.assertEqual(result, "asdf")
+
+ @gen_test
+ def test_fails_before_timeout(self):
+ future = Future() # type: Future[str]
+ self.io_loop.add_timeout(
+ datetime.timedelta(seconds=0.1),
+ lambda: future.set_exception(ZeroDivisionError()),
+ )
+ with self.assertRaises(ZeroDivisionError):
+ yield gen.with_timeout(datetime.timedelta(seconds=3600), future)
+
+ @gen_test
+ def test_already_resolved(self):
+ future = Future() # type: Future[str]
+ future.set_result("asdf")
+ result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future)
+ self.assertEqual(result, "asdf")
+
+ @gen_test
+ def test_timeout_concurrent_future(self):
+ # A concurrent future that does not resolve before the timeout.
+ with futures.ThreadPoolExecutor(1) as executor:
+ with self.assertRaises(gen.TimeoutError):
+ yield gen.with_timeout(
+ self.io_loop.time(), executor.submit(time.sleep, 0.1)
+ )
+
+ @gen_test
+ def test_completed_concurrent_future(self):
+ # A concurrent future that is resolved before we even submit it
+ # to with_timeout.
+ with futures.ThreadPoolExecutor(1) as executor:
+
+ def dummy():
+ pass
+
+ f = executor.submit(dummy)
+ f.result() # wait for completion
+ yield gen.with_timeout(datetime.timedelta(seconds=3600), f)
+
+ @gen_test
+ def test_normal_concurrent_future(self):
+ # A conccurrent future that resolves while waiting for the timeout.
+ with futures.ThreadPoolExecutor(1) as executor:
+ yield gen.with_timeout(
+ datetime.timedelta(seconds=3600),
+ executor.submit(lambda: time.sleep(0.01)),
+ )
+
+
+class WaitIteratorTest(AsyncTestCase):
+ @gen_test
+ def test_empty_iterator(self):
+ g = gen.WaitIterator()
+ self.assertTrue(g.done(), "empty generator iterated")
+
+ with self.assertRaises(ValueError):
+ g = gen.WaitIterator(Future(), bar=Future())
+
+ self.assertIsNone(g.current_index, "bad nil current index")
+ self.assertIsNone(g.current_future, "bad nil current future")
+
+ @gen_test
+ def test_already_done(self):
+ f1 = Future() # type: Future[int]
+ f2 = Future() # type: Future[int]
+ f3 = Future() # type: Future[int]
+ f1.set_result(24)
+ f2.set_result(42)
+ f3.set_result(84)
+
+ g = gen.WaitIterator(f1, f2, f3)
+ i = 0
+ while not g.done():
+ r = yield g.next()
+ # Order is not guaranteed, but the current implementation
+ # preserves ordering of already-done Futures.
+ if i == 0:
+ self.assertEqual(g.current_index, 0)
+ self.assertIs(g.current_future, f1)
+ self.assertEqual(r, 24)
+ elif i == 1:
+ self.assertEqual(g.current_index, 1)
+ self.assertIs(g.current_future, f2)
+ self.assertEqual(r, 42)
+ elif i == 2:
+ self.assertEqual(g.current_index, 2)
+ self.assertIs(g.current_future, f3)
+ self.assertEqual(r, 84)
+ i += 1
+
+ self.assertIsNone(g.current_index, "bad nil current index")
+ self.assertIsNone(g.current_future, "bad nil current future")
+
+ dg = gen.WaitIterator(f1=f1, f2=f2)
+
+ while not dg.done():
+ dr = yield dg.next()
+ if dg.current_index == "f1":
+ self.assertTrue(
+ dg.current_future == f1 and dr == 24,
+ "WaitIterator dict status incorrect",
+ )
+ elif dg.current_index == "f2":
+ self.assertTrue(
+ dg.current_future == f2 and dr == 42,
+ "WaitIterator dict status incorrect",
+ )
+ else:
+ self.fail(f"got bad WaitIterator index {dg.current_index}")
+
+ i += 1
+ self.assertIsNone(g.current_index, "bad nil current index")
+ self.assertIsNone(g.current_future, "bad nil current future")
+
+ def finish_coroutines(self, iteration, futures):
+ if iteration == 3:
+ futures[2].set_result(24)
+ elif iteration == 5:
+ futures[0].set_exception(ZeroDivisionError())
+ elif iteration == 8:
+ futures[1].set_result(42)
+ futures[3].set_result(84)
+
+ if iteration < 8:
+ self.io_loop.add_callback(self.finish_coroutines, iteration + 1, futures)
+
+ @gen_test
+ def test_iterator(self):
+ futures = [Future(), Future(), Future(), Future()] # type: List[Future[int]]
+
+ self.finish_coroutines(0, futures)
+
+ g = gen.WaitIterator(*futures)
+
+ i = 0
+ while not g.done():
+ try:
+ r = yield g.next()
+ except ZeroDivisionError:
+ self.assertIs(g.current_future, futures[0], "exception future invalid")
+ else:
+ if i == 0:
+ self.assertEqual(r, 24, "iterator value incorrect")
+ self.assertEqual(g.current_index, 2, "wrong index")
+ elif i == 2:
+ self.assertEqual(r, 42, "iterator value incorrect")
+ self.assertEqual(g.current_index, 1, "wrong index")
+ elif i == 3:
+ self.assertEqual(r, 84, "iterator value incorrect")
+ self.assertEqual(g.current_index, 3, "wrong index")
+ i += 1
+
+ @gen_test
+ def test_iterator_async_await(self):
+ # Recreate the previous test with py35 syntax. It's a little clunky
+ # because of the way the previous test handles an exception on
+ # a single iteration.
+ futures = [Future(), Future(), Future(), Future()] # type: List[Future[int]]
+ self.finish_coroutines(0, futures)
+ self.finished = False
+
+ async def f():
+ i = 0
+ g = gen.WaitIterator(*futures)
+ try:
+ async for r in g:
+ if i == 0:
+ self.assertEqual(r, 24, "iterator value incorrect")
+ self.assertEqual(g.current_index, 2, "wrong index")
+ else:
+ raise Exception("expected exception on iteration 1")
+ i += 1
+ except ZeroDivisionError:
+ i += 1
+ async for r in g:
+ if i == 2:
+ self.assertEqual(r, 42, "iterator value incorrect")
+ self.assertEqual(g.current_index, 1, "wrong index")
+ elif i == 3:
+ self.assertEqual(r, 84, "iterator value incorrect")
+ self.assertEqual(g.current_index, 3, "wrong index")
+ else:
+ raise Exception("didn't expect iteration %d" % i)
+ i += 1
+ self.finished = True
+
+ yield f()
+ self.assertTrue(self.finished)
+
+ @gen_test
+ def test_no_ref(self):
+ # In this usage, there is no direct hard reference to the
+ # WaitIterator itself, only the Future it returns. Since
+ # WaitIterator uses weak references internally to improve GC
+ # performance, this used to cause problems.
+ yield gen.with_timeout(
+ datetime.timedelta(seconds=0.1), gen.WaitIterator(gen.sleep(0)).next()
+ )
+
+
+class RunnerGCTest(AsyncTestCase):
+ def is_pypy3(self):
+ return platform.python_implementation() == "PyPy" and sys.version_info > (3,)
+
+ @gen_test
+ def test_gc(self):
+ # GitHub issue 1769: Runner objects can get GCed unexpectedly
+ # while their future is alive.
+ weakref_scope = [None] # type: List[Optional[weakref.ReferenceType]]
+
+ def callback():
+ gc.collect(2)
+ weakref_scope[0]().set_result(123) # type: ignore
+
+ @gen.coroutine
+ def tester():
+ fut = Future() # type: Future[int]
+ weakref_scope[0] = weakref.ref(fut)
+ self.io_loop.add_callback(callback)
+ yield fut
+
+ yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())
+
+ def test_gc_infinite_coro(self):
+ # GitHub issue 2229: suspended coroutines should be GCed when
+ # their loop is closed, even if they're involved in a reference
+ # cycle.
+ loop = self.get_new_ioloop()
+ result = [] # type: List[Optional[bool]]
+ wfut = []
+
+ @gen.coroutine
+ def infinite_coro():
+ try:
+ while True:
+ yield gen.sleep(1e-3)
+ result.append(True)
+ finally:
+ # coroutine finalizer
+ result.append(None)
+
+ @gen.coroutine
+ def do_something():
+ fut = infinite_coro()
+ fut._refcycle = fut # type: ignore
+ wfut.append(weakref.ref(fut))
+ yield gen.sleep(0.2)
+
+ loop.run_sync(do_something)
+ loop.close()
+ gc.collect()
+ # Future was collected
+ self.assertIsNone(wfut[0]())
+ # At least one wakeup
+ self.assertGreaterEqual(len(result), 2)
+ if not self.is_pypy3():
+ # coroutine finalizer was called (not on PyPy3 apparently)
+ self.assertIsNone(result[-1])
+
+ def test_gc_infinite_async_await(self):
+ # Same as test_gc_infinite_coro, but with a `async def` function
+ import asyncio
+
+ async def infinite_coro(result):
+ try:
+ while True:
+ await gen.sleep(1e-3)
+ result.append(True)
+ finally:
+ # coroutine finalizer
+ result.append(None)
+
+ loop = self.get_new_ioloop()
+ result = [] # type: List[Optional[bool]]
+ wfut = []
+
+ @gen.coroutine
+ def do_something():
+ fut = asyncio.get_event_loop().create_task(infinite_coro(result))
+ fut._refcycle = fut # type: ignore
+ wfut.append(weakref.ref(fut))
+ yield gen.sleep(0.2)
+
+ loop.run_sync(do_something)
+ with ExpectLog("asyncio", "Task was destroyed but it is pending"):
+ loop.close()
+ gc.collect()
+ # Future was collected
+ self.assertIsNone(wfut[0]())
+ # At least one wakeup and one finally
+ self.assertGreaterEqual(len(result), 2)
+ if not self.is_pypy3():
+ # coroutine finalizer was called (not on PyPy3 apparently)
+ self.assertIsNone(result[-1])
+
+ def test_multi_moment(self):
+ # Test gen.multi with moment
+ # now that it's not a real Future
+ @gen.coroutine
+ def wait_a_moment():
+ result = yield gen.multi([gen.moment, gen.moment])
+ raise gen.Return(result)
+
+ loop = self.get_new_ioloop()
+ result = loop.run_sync(wait_a_moment)
+ self.assertEqual(result, [None, None])
+
+
+if contextvars is not None:
+ ctx_var = contextvars.ContextVar("ctx_var") # type: contextvars.ContextVar[int]
+
+
+@unittest.skipIf(contextvars is None, "contextvars module not present")
+class ContextVarsTest(AsyncTestCase):
+ async def native_root(self, x):
+ ctx_var.set(x)
+ await self.inner(x)
+
+ @gen.coroutine
+ def gen_root(self, x):
+ ctx_var.set(x)
+ yield
+ yield self.inner(x)
+
+ async def inner(self, x):
+ self.assertEqual(ctx_var.get(), x)
+ await self.gen_inner(x)
+ self.assertEqual(ctx_var.get(), x)
+
+ # IOLoop.run_in_executor doesn't automatically copy context
+ ctx = contextvars.copy_context()
+ await self.io_loop.run_in_executor(None, lambda: ctx.run(self.thread_inner, x))
+ self.assertEqual(ctx_var.get(), x)
+
+ # Neither does asyncio's run_in_executor.
+ await asyncio.get_event_loop().run_in_executor(
+ None, lambda: ctx.run(self.thread_inner, x)
+ )
+ self.assertEqual(ctx_var.get(), x)
+
+ @gen.coroutine
+ def gen_inner(self, x):
+ self.assertEqual(ctx_var.get(), x)
+ yield
+ self.assertEqual(ctx_var.get(), x)
+
+ def thread_inner(self, x):
+ self.assertEqual(ctx_var.get(), x)
+
+ @gen_test
+ def test_propagate(self):
+ # Verify that context vars get propagated across various
+ # combinations of native and decorated coroutines.
+ yield [
+ self.native_root(1),
+ self.native_root(2),
+ self.gen_root(3),
+ self.gen_root(4),
+ ]
+
+ @gen_test
+ def test_reset(self):
+ token = ctx_var.set(1)
+ yield
+ # reset asserts that we are still at the same level of the context tree,
+ # so we must make sure that we maintain that property across yield.
+ ctx_var.reset(token)
+
+ @gen_test
+ def test_propagate_to_first_yield_with_native_async_function(self):
+ x = 10
+
+ async def native_async_function():
+ self.assertEqual(ctx_var.get(), x)
+
+ ctx_var.set(x)
+ yield native_async_function()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.mo b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.mo
new file mode 100644
index 0000000000000000000000000000000000000000..a97bf9c57460ecfc27761accf90d712ea5cebb44
Binary files /dev/null and b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.mo differ
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.po b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.po
new file mode 100644
index 0000000000000000000000000000000000000000..88d72c8623a4275c85cb32e2ec35205b5b907176
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/gettext_translations/fr_FR/LC_MESSAGES/tornado_test.po
@@ -0,0 +1,47 @@
+# SOME DESCRIPTIVE TITLE.
+# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
+# This file is distributed under the same license as the PACKAGE package.
+# FIRST AUTHOR , YEAR.
+#
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: PACKAGE VERSION\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2015-01-27 11:05+0300\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: FULL NAME \n"
+"Language-Team: LANGUAGE \n"
+"Language: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=utf-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+
+#: extract_me.py:11
+msgid "school"
+msgstr "école"
+
+#: extract_me.py:12
+msgctxt "law"
+msgid "right"
+msgstr "le droit"
+
+#: extract_me.py:13
+msgctxt "good"
+msgid "right"
+msgstr "le bien"
+
+#: extract_me.py:14
+msgctxt "organization"
+msgid "club"
+msgid_plural "clubs"
+msgstr[0] "le club"
+msgstr[1] "les clubs"
+
+#: extract_me.py:15
+msgctxt "stick"
+msgid "club"
+msgid_plural "clubs"
+msgstr[0] "le bâton"
+msgstr[1] "les bâtons"
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/http1connection_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/http1connection_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..34de6d38305ab87afb36c9e91cf624f846ccd989
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/http1connection_test.py
@@ -0,0 +1,61 @@
+import socket
+import typing # noqa(F401)
+
+from tornado.http1connection import HTTP1Connection
+from tornado.httputil import HTTPMessageDelegate
+from tornado.iostream import IOStream
+from tornado.locks import Event
+from tornado.netutil import add_accept_handler
+from tornado.testing import AsyncTestCase, bind_unused_port, gen_test
+
+
+class HTTP1ConnectionTest(AsyncTestCase):
+ code = None # type: typing.Optional[int]
+
+ def setUp(self):
+ super().setUp()
+ self.asyncSetUp()
+
+ @gen_test
+ def asyncSetUp(self):
+ listener, port = bind_unused_port()
+ event = Event()
+
+ def accept_callback(conn, addr):
+ self.server_stream = IOStream(conn)
+ self.addCleanup(self.server_stream.close)
+ event.set()
+
+ add_accept_handler(listener, accept_callback)
+ self.client_stream = IOStream(socket.socket())
+ self.addCleanup(self.client_stream.close)
+ yield [self.client_stream.connect(("127.0.0.1", port)), event.wait()]
+ self.io_loop.remove_handler(listener)
+ listener.close()
+
+ @gen_test
+ def test_http10_no_content_length(self):
+ # Regression test for a bug in which can_keep_alive would crash
+ # for an HTTP/1.0 (not 1.1) response with no content-length.
+ conn = HTTP1Connection(self.client_stream, True)
+ self.server_stream.write(b"HTTP/1.0 200 Not Modified\r\n\r\nhello")
+ self.server_stream.close()
+
+ event = Event()
+ test = self
+ body = []
+
+ class Delegate(HTTPMessageDelegate):
+ def headers_received(self, start_line, headers):
+ test.code = start_line.code
+
+ def data_received(self, data):
+ body.append(data)
+
+ def finish(self):
+ event.set()
+
+ yield conn.read_response(Delegate())
+ yield event.wait()
+ self.assertEqual(self.code, 200)
+ self.assertEqual(b"".join(body), b"hello")
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/httpclient_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/httpclient_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..77c0d6eb9bfb204c1580509b57238a655cab08da
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/httpclient_test.py
@@ -0,0 +1,957 @@
+import base64
+import binascii
+from contextlib import closing
+import copy
+import gzip
+import threading
+import datetime
+from io import BytesIO
+import subprocess
+import sys
+import time
+import typing # noqa: F401
+import unicodedata
+import unittest
+
+from tornado.escape import utf8, native_str, to_unicode
+from tornado import gen
+from tornado.httpclient import (
+ HTTPRequest,
+ HTTPResponse,
+ _RequestProxy,
+ HTTPError,
+ HTTPClient,
+)
+from tornado.httpserver import HTTPServer
+from tornado.ioloop import IOLoop
+from tornado.iostream import IOStream
+from tornado.log import gen_log, app_log
+from tornado import netutil
+from tornado.testing import AsyncHTTPTestCase, bind_unused_port, gen_test, ExpectLog
+from tornado.test.util import ignore_deprecation
+from tornado.web import Application, RequestHandler, url
+from tornado.httputil import format_timestamp, HTTPHeaders
+
+
+class HelloWorldHandler(RequestHandler):
+ def get(self):
+ name = self.get_argument("name", "world")
+ self.set_header("Content-Type", "text/plain")
+ self.finish("Hello %s!" % name)
+
+
+class PostHandler(RequestHandler):
+ def post(self):
+ self.finish(
+ "Post arg1: %s, arg2: %s"
+ % (self.get_argument("arg1"), self.get_argument("arg2"))
+ )
+
+
+class PutHandler(RequestHandler):
+ def put(self):
+ self.write("Put body: ")
+ self.write(self.request.body)
+
+
+class RedirectHandler(RequestHandler):
+ def prepare(self):
+ self.write("redirects can have bodies too")
+ self.redirect(
+ self.get_argument("url"), status=int(self.get_argument("status", "302"))
+ )
+
+
+class RedirectWithoutLocationHandler(RequestHandler):
+ def prepare(self):
+ # For testing error handling of a redirect with no location header.
+ self.set_status(301)
+ self.finish()
+
+
+class ChunkHandler(RequestHandler):
+ @gen.coroutine
+ def get(self):
+ self.write("asdf")
+ self.flush()
+ # Wait a bit to ensure the chunks are sent and received separately.
+ yield gen.sleep(0.01)
+ self.write("qwer")
+
+
+class AuthHandler(RequestHandler):
+ def get(self):
+ self.finish(self.request.headers["Authorization"])
+
+
+class CountdownHandler(RequestHandler):
+ def get(self, count):
+ count = int(count)
+ if count > 0:
+ self.redirect(self.reverse_url("countdown", count - 1))
+ else:
+ self.write("Zero")
+
+
+class EchoPostHandler(RequestHandler):
+ def post(self):
+ self.write(self.request.body)
+
+
+class UserAgentHandler(RequestHandler):
+ def get(self):
+ self.write(self.request.headers.get("User-Agent", "User agent not set"))
+
+
+class ContentLength304Handler(RequestHandler):
+ def get(self):
+ self.set_status(304)
+ self.set_header("Content-Length", 42)
+
+ def _clear_representation_headers(self):
+ # Tornado strips content-length from 304 responses, but here we
+ # want to simulate servers that include the headers anyway.
+ pass
+
+
+class PatchHandler(RequestHandler):
+ def patch(self):
+ "Return the request payload - so we can check it is being kept"
+ self.write(self.request.body)
+
+
+class AllMethodsHandler(RequestHandler):
+ SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ("OTHER",) # type: ignore
+
+ def method(self):
+ assert self.request.method is not None
+ self.write(self.request.method)
+
+ get = head = post = put = delete = options = patch = other = method # type: ignore
+
+
+class SetHeaderHandler(RequestHandler):
+ def get(self):
+ # Use get_arguments for keys to get strings, but
+ # request.arguments for values to get bytes.
+ for k, v in zip(self.get_arguments("k"), self.request.arguments["v"]):
+ self.set_header(k, v)
+
+
+class InvalidGzipHandler(RequestHandler):
+ def get(self) -> None:
+ # set Content-Encoding manually to avoid automatic gzip encoding
+ self.set_header("Content-Type", "text/plain")
+ self.set_header("Content-Encoding", "gzip")
+ # Triggering the potential bug seems to depend on input length.
+ # This length is taken from the bad-response example reported in
+ # https://github.com/tornadoweb/tornado/pull/2875 (uncompressed).
+ text = "".join(f"Hello World {i}\n" for i in range(9000))[:149051]
+ body = gzip.compress(text.encode(), compresslevel=6) + b"\00"
+ self.write(body)
+
+
+class HeaderEncodingHandler(RequestHandler):
+ def get(self):
+ self.finish(self.request.headers["Foo"].encode("ISO8859-1"))
+
+
+# These tests end up getting run redundantly: once here with the default
+# HTTPClient implementation, and then again in each implementation's own
+# test suite.
+
+
+class HTTPClientCommonTestCase(AsyncHTTPTestCase):
+ def get_app(self):
+ return Application(
+ [
+ url("/hello", HelloWorldHandler),
+ url("/post", PostHandler),
+ url("/put", PutHandler),
+ url("/redirect", RedirectHandler),
+ url("/redirect_without_location", RedirectWithoutLocationHandler),
+ url("/chunk", ChunkHandler),
+ url("/auth", AuthHandler),
+ url("/countdown/([0-9]+)", CountdownHandler, name="countdown"),
+ url("/echopost", EchoPostHandler),
+ url("/user_agent", UserAgentHandler),
+ url("/304_with_content_length", ContentLength304Handler),
+ url("/all_methods", AllMethodsHandler),
+ url("/patch", PatchHandler),
+ url("/set_header", SetHeaderHandler),
+ url("/invalid_gzip", InvalidGzipHandler),
+ url("/header-encoding", HeaderEncodingHandler),
+ ],
+ gzip=True,
+ )
+
+ def test_patch_receives_payload(self):
+ body = b"some patch data"
+ response = self.fetch("/patch", method="PATCH", body=body)
+ self.assertEqual(response.code, 200)
+ self.assertEqual(response.body, body)
+
+ def test_hello_world(self):
+ response = self.fetch("/hello")
+ self.assertEqual(response.code, 200)
+ self.assertEqual(response.headers["Content-Type"], "text/plain")
+ self.assertEqual(response.body, b"Hello world!")
+ assert response.request_time is not None
+ self.assertEqual(int(response.request_time), 0)
+
+ response = self.fetch("/hello?name=Ben")
+ self.assertEqual(response.body, b"Hello Ben!")
+
+ def test_streaming_callback(self):
+ # streaming_callback is also tested in test_chunked
+ chunks = [] # type: typing.List[bytes]
+ response = self.fetch("/hello", streaming_callback=chunks.append)
+ # with streaming_callback, data goes to the callback and not response.body
+ self.assertEqual(chunks, [b"Hello world!"])
+ self.assertFalse(response.body)
+
+ def test_post(self):
+ response = self.fetch("/post", method="POST", body="arg1=foo&arg2=bar")
+ self.assertEqual(response.code, 200)
+ self.assertEqual(response.body, b"Post arg1: foo, arg2: bar")
+
+ def test_chunked(self):
+ response = self.fetch("/chunk")
+ self.assertEqual(response.body, b"asdfqwer")
+
+ chunks = [] # type: typing.List[bytes]
+ response = self.fetch("/chunk", streaming_callback=chunks.append)
+ self.assertEqual(chunks, [b"asdf", b"qwer"])
+ self.assertFalse(response.body)
+
+ def test_chunked_close(self):
+ # test case in which chunks spread read-callback processing
+ # over several ioloop iterations, but the connection is already closed.
+ sock, port = bind_unused_port()
+ with closing(sock):
+
+ @gen.coroutine
+ def accept_callback(conn, address):
+ # fake an HTTP server using chunked encoding where the final chunks
+ # and connection close all happen at once
+ stream = IOStream(conn)
+ request_data = yield stream.read_until(b"\r\n\r\n")
+ if b"HTTP/1." not in request_data:
+ self.skipTest("requires HTTP/1.x")
+ yield stream.write(
+ b"""\
+HTTP/1.1 200 OK
+Transfer-Encoding: chunked
+
+1
+1
+1
+2
+0
+
+""".replace(
+ b"\n", b"\r\n"
+ )
+ )
+ stream.close()
+
+ netutil.add_accept_handler(sock, accept_callback) # type: ignore
+ resp = self.fetch("http://127.0.0.1:%d/" % port)
+ resp.rethrow()
+ self.assertEqual(resp.body, b"12")
+ self.io_loop.remove_handler(sock.fileno())
+
+ def test_basic_auth(self):
+ # This test data appears in section 2 of RFC 7617.
+ self.assertEqual(
+ self.fetch(
+ "/auth", auth_username="Aladdin", auth_password="open sesame"
+ ).body,
+ b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
+ )
+
+ def test_basic_auth_explicit_mode(self):
+ self.assertEqual(
+ self.fetch(
+ "/auth",
+ auth_username="Aladdin",
+ auth_password="open sesame",
+ auth_mode="basic",
+ ).body,
+ b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
+ )
+
+ def test_basic_auth_unicode(self):
+ # This test data appears in section 2.1 of RFC 7617.
+ self.assertEqual(
+ self.fetch("/auth", auth_username="test", auth_password="123£").body,
+ b"Basic dGVzdDoxMjPCow==",
+ )
+
+ # The standard mandates NFC. Give it a decomposed username
+ # and ensure it is normalized to composed form.
+ username = unicodedata.normalize("NFD", "josé")
+ self.assertEqual(
+ self.fetch("/auth", auth_username=username, auth_password="səcrət").body,
+ b"Basic am9zw6k6c8mZY3LJmXQ=",
+ )
+
+ def test_unsupported_auth_mode(self):
+ # curl and simple clients handle errors a bit differently; the
+ # important thing is that they don't fall back to basic auth
+ # on an unknown mode.
+ with ExpectLog(gen_log, "uncaught exception", required=False):
+ with self.assertRaises((ValueError, HTTPError)): # type: ignore
+ self.fetch(
+ "/auth",
+ auth_username="Aladdin",
+ auth_password="open sesame",
+ auth_mode="asdf",
+ raise_error=True,
+ )
+
+ def test_follow_redirect(self):
+ response = self.fetch("/countdown/2", follow_redirects=False)
+ self.assertEqual(302, response.code)
+ self.assertTrue(response.headers["Location"].endswith("/countdown/1"))
+
+ response = self.fetch("/countdown/2")
+ self.assertEqual(200, response.code)
+ self.assertTrue(response.effective_url.endswith("/countdown/0"))
+ self.assertEqual(b"Zero", response.body)
+
+ def test_redirect_without_location(self):
+ response = self.fetch("/redirect_without_location", follow_redirects=True)
+ # If there is no location header, the redirect response should
+ # just be returned as-is. (This should arguably raise an
+ # error, but libcurl doesn't treat this as an error, so we
+ # don't either).
+ self.assertEqual(301, response.code)
+
+ def test_redirect_put_with_body(self):
+ response = self.fetch(
+ "/redirect?url=/put&status=307", method="PUT", body="hello"
+ )
+ self.assertEqual(response.body, b"Put body: hello")
+
+ def test_redirect_put_without_body(self):
+ # This "without body" edge case is similar to what happens with body_producer.
+ response = self.fetch(
+ "/redirect?url=/put&status=307",
+ method="PUT",
+ allow_nonstandard_methods=True,
+ )
+ self.assertEqual(response.body, b"Put body: ")
+
+ def test_method_after_redirect(self):
+ # Legacy redirect codes (301, 302) convert POST requests to GET.
+ for status in [301, 302, 303]:
+ url = "/redirect?url=/all_methods&status=%d" % status
+ resp = self.fetch(url, method="POST", body=b"")
+ self.assertEqual(b"GET", resp.body)
+
+ # Other methods are left alone, except for 303 redirect, depending on client
+ for method in ["GET", "OPTIONS", "PUT", "DELETE"]:
+ resp = self.fetch(url, method=method, allow_nonstandard_methods=True)
+ if status in [301, 302]:
+ self.assertEqual(utf8(method), resp.body)
+ else:
+ self.assertIn(resp.body, [utf8(method), b"GET"])
+
+ # HEAD is different so check it separately.
+ resp = self.fetch(url, method="HEAD")
+ self.assertEqual(200, resp.code)
+ self.assertEqual(b"", resp.body)
+
+ # Newer redirects always preserve the original method.
+ for status in [307, 308]:
+ url = "/redirect?url=/all_methods&status=307"
+ for method in ["GET", "OPTIONS", "POST", "PUT", "DELETE"]:
+ resp = self.fetch(url, method=method, allow_nonstandard_methods=True)
+ self.assertEqual(method, to_unicode(resp.body))
+ resp = self.fetch(url, method="HEAD")
+ self.assertEqual(200, resp.code)
+ self.assertEqual(b"", resp.body)
+
+ def test_credentials_in_url(self):
+ url = self.get_url("/auth").replace("http://", "http://me:secret@")
+ response = self.fetch(url)
+ self.assertEqual(b"Basic " + base64.b64encode(b"me:secret"), response.body)
+
+ def test_body_encoding(self):
+ unicode_body = "\xe9"
+ byte_body = binascii.a2b_hex(b"e9")
+
+ # unicode string in body gets converted to utf8
+ response = self.fetch(
+ "/echopost",
+ method="POST",
+ body=unicode_body,
+ headers={"Content-Type": "application/blah"},
+ )
+ self.assertEqual(response.headers["Content-Length"], "2")
+ self.assertEqual(response.body, utf8(unicode_body))
+
+ # byte strings pass through directly
+ response = self.fetch(
+ "/echopost",
+ method="POST",
+ body=byte_body,
+ headers={"Content-Type": "application/blah"},
+ )
+ self.assertEqual(response.headers["Content-Length"], "1")
+ self.assertEqual(response.body, byte_body)
+
+ # Mixing unicode in headers and byte string bodies shouldn't
+ # break anything
+ response = self.fetch(
+ "/echopost",
+ method="POST",
+ body=byte_body,
+ headers={"Content-Type": "application/blah"},
+ user_agent="foo",
+ )
+ self.assertEqual(response.headers["Content-Length"], "1")
+ self.assertEqual(response.body, byte_body)
+
+ def test_types(self):
+ response = self.fetch("/hello")
+ self.assertEqual(type(response.body), bytes)
+ self.assertEqual(type(response.headers["Content-Type"]), str)
+ self.assertEqual(type(response.code), int)
+ self.assertEqual(type(response.effective_url), str)
+
+ def test_gzip(self):
+ # All the tests in this file should be using gzip, but this test
+ # ensures that it is in fact getting compressed, and also tests
+ # the httpclient's decompress=False option.
+ # Setting Accept-Encoding manually bypasses the client's
+ # decompression so we can see the raw data.
+ response = self.fetch(
+ "/chunk", decompress_response=False, headers={"Accept-Encoding": "gzip"}
+ )
+ self.assertEqual(response.headers["Content-Encoding"], "gzip")
+ self.assertNotEqual(response.body, b"asdfqwer")
+ # Our test data gets bigger when gzipped. Oops. :)
+ # Chunked encoding bypasses the MIN_LENGTH check.
+ self.assertEqual(len(response.body), 34)
+ f = gzip.GzipFile(mode="r", fileobj=response.buffer)
+ self.assertEqual(f.read(), b"asdfqwer")
+
+ def test_invalid_gzip(self):
+ # test if client hangs on tricky invalid gzip
+ # curl/simple httpclient have different behavior (exception, logging)
+ with ExpectLog(
+ gen_log, ".*Malformed HTTP message.*unconsumed gzip data", required=False
+ ):
+ try:
+ response = self.fetch("/invalid_gzip")
+ self.assertEqual(response.code, 200)
+ self.assertEqual(response.body[:14], b"Hello World 0\n")
+ except HTTPError:
+ pass # acceptable
+
+ def test_header_callback(self):
+ first_line = []
+ headers = {}
+ chunks = []
+
+ def header_callback(header_line):
+ if header_line.startswith("HTTP/1.1 101"):
+ # Upgrading to HTTP/2
+ pass
+ elif header_line.startswith("HTTP/"):
+ first_line.append(header_line)
+ elif header_line != "\r\n":
+ k, v = header_line.split(":", 1)
+ headers[k.lower()] = v.strip()
+
+ def streaming_callback(chunk):
+ # All header callbacks are run before any streaming callbacks,
+ # so the header data is available to process the data as it
+ # comes in.
+ self.assertEqual(headers["content-type"], "text/html; charset=UTF-8")
+ chunks.append(chunk)
+
+ self.fetch(
+ "/chunk",
+ header_callback=header_callback,
+ streaming_callback=streaming_callback,
+ )
+ self.assertEqual(len(first_line), 1, first_line)
+ self.assertRegex(first_line[0], "HTTP/[0-9]\\.[0-9] 200.*\r\n")
+ self.assertEqual(chunks, [b"asdf", b"qwer"])
+
+ def test_header_callback_to_parse_line(self):
+ # Make a request with header_callback and feed the headers to HTTPHeaders.parse_line.
+ # (Instead of HTTPHeaders.parse which is used in normal cases). Ensure that the resulting
+ # headers are as expected, and in particular do not have trailing whitespace added
+ # due to the final CRLF line.
+ headers = HTTPHeaders()
+
+ def header_callback(line):
+ if line.startswith("HTTP/"):
+ # Ignore the first status line
+ return
+ headers.parse_line(line)
+
+ self.fetch("/hello", header_callback=header_callback)
+ for k, v in headers.get_all():
+ self.assertTrue(v == v.strip(), (k, v))
+
+ @gen_test
+ def test_configure_defaults(self):
+ defaults = dict(user_agent="TestDefaultUserAgent", allow_ipv6=False)
+ # Construct a new instance of the configured client class
+ client = self.http_client.__class__(force_instance=True, defaults=defaults)
+ try:
+ response = yield client.fetch(self.get_url("/user_agent"))
+ self.assertEqual(response.body, b"TestDefaultUserAgent")
+ finally:
+ client.close()
+
+ def test_header_types(self):
+ # Header values may be passed as character or utf8 byte strings,
+ # in a plain dictionary or an HTTPHeaders object.
+ # Keys must always be the native str type.
+ # All combinations should have the same results on the wire.
+ for value in ["MyUserAgent", b"MyUserAgent"]:
+ for container in [dict, HTTPHeaders]:
+ headers = container()
+ headers["User-Agent"] = value
+ resp = self.fetch("/user_agent", headers=headers)
+ self.assertEqual(
+ resp.body,
+ b"MyUserAgent",
+ "response=%r, value=%r, container=%r"
+ % (resp.body, value, container),
+ )
+
+ def test_multi_line_headers(self):
+ # Multi-line http headers are rare but rfc-allowed
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
+ sock, port = bind_unused_port()
+ with closing(sock):
+
+ @gen.coroutine
+ def accept_callback(conn, address):
+ stream = IOStream(conn)
+ request_data = yield stream.read_until(b"\r\n\r\n")
+ if b"HTTP/1." not in request_data:
+ self.skipTest("requires HTTP/1.x")
+ yield stream.write(
+ b"""\
+HTTP/1.1 200 OK
+X-XSS-Protection: 1;
+\tmode=block
+
+""".replace(
+ b"\n", b"\r\n"
+ )
+ )
+ stream.close()
+
+ netutil.add_accept_handler(sock, accept_callback) # type: ignore
+ try:
+ resp = self.fetch("http://127.0.0.1:%d/" % port)
+ resp.rethrow()
+ self.assertEqual(resp.headers["X-XSS-Protection"], "1; mode=block")
+ finally:
+ self.io_loop.remove_handler(sock.fileno())
+
+ @gen_test
+ def test_header_encoding(self):
+ response = yield self.http_client.fetch(
+ self.get_url("/header-encoding"),
+ headers={
+ "Foo": "b\xe4r",
+ },
+ )
+ self.assertEqual(response.body, "b\xe4r".encode("ISO8859-1"))
+
+ def test_304_with_content_length(self):
+ # According to the spec 304 responses SHOULD NOT include
+ # Content-Length or other entity headers, but some servers do it
+ # anyway.
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
+ response = self.fetch("/304_with_content_length")
+ self.assertEqual(response.code, 304)
+ self.assertEqual(response.headers["Content-Length"], "42")
+
+ @gen_test
+ def test_future_interface(self):
+ response = yield self.http_client.fetch(self.get_url("/hello"))
+ self.assertEqual(response.body, b"Hello world!")
+
+ @gen_test
+ def test_future_http_error(self):
+ with self.assertRaises(HTTPError) as context:
+ yield self.http_client.fetch(self.get_url("/notfound"))
+ assert context.exception is not None
+ assert context.exception.response is not None
+ self.assertEqual(context.exception.code, 404)
+ self.assertEqual(context.exception.response.code, 404)
+
+ @gen_test
+ def test_future_http_error_no_raise(self):
+ response = yield self.http_client.fetch(
+ self.get_url("/notfound"), raise_error=False
+ )
+ self.assertEqual(response.code, 404)
+
+ @gen_test
+ def test_reuse_request_from_response(self):
+ # The response.request attribute should be an HTTPRequest, not
+ # a _RequestProxy.
+ # This test uses self.http_client.fetch because self.fetch calls
+ # self.get_url on the input unconditionally.
+ url = self.get_url("/hello")
+ response = yield self.http_client.fetch(url)
+ self.assertEqual(response.request.url, url)
+ self.assertTrue(isinstance(response.request, HTTPRequest))
+ response2 = yield self.http_client.fetch(response.request)
+ self.assertEqual(response2.body, b"Hello world!")
+
+ @gen_test
+ def test_bind_source_ip(self):
+ url = self.get_url("/hello")
+ request = HTTPRequest(url, network_interface="127.0.0.1")
+ response = yield self.http_client.fetch(request)
+ self.assertEqual(response.code, 200)
+
+ with self.assertRaises((ValueError, HTTPError)) as context: # type: ignore
+ request = HTTPRequest(url, network_interface="not-interface-or-ip")
+ yield self.http_client.fetch(request)
+ self.assertIn("not-interface-or-ip", str(context.exception))
+
+ def test_all_methods(self):
+ for method in ["GET", "DELETE", "OPTIONS"]:
+ response = self.fetch("/all_methods", method=method)
+ self.assertEqual(response.body, utf8(method))
+ for method in ["POST", "PUT", "PATCH"]:
+ response = self.fetch("/all_methods", method=method, body=b"")
+ self.assertEqual(response.body, utf8(method))
+ response = self.fetch("/all_methods", method="HEAD")
+ self.assertEqual(response.body, b"")
+ response = self.fetch(
+ "/all_methods", method="OTHER", allow_nonstandard_methods=True
+ )
+ self.assertEqual(response.body, b"OTHER")
+
+ def test_body_sanity_checks(self):
+ # These methods require a body.
+ for method in ("POST", "PUT", "PATCH"):
+ with self.assertRaises(ValueError) as context:
+ self.fetch("/all_methods", method=method, raise_error=True)
+ self.assertIn("must not be None", str(context.exception))
+
+ resp = self.fetch(
+ "/all_methods", method=method, allow_nonstandard_methods=True
+ )
+ self.assertEqual(resp.code, 200)
+
+ # These methods don't allow a body.
+ for method in ("GET", "DELETE", "OPTIONS"):
+ with self.assertRaises(ValueError) as context:
+ self.fetch(
+ "/all_methods", method=method, body=b"asdf", raise_error=True
+ )
+ self.assertIn("must be None", str(context.exception))
+
+ # In most cases this can be overridden, but curl_httpclient
+ # does not allow body with a GET at all.
+ if method != "GET":
+ self.fetch(
+ "/all_methods",
+ method=method,
+ body=b"asdf",
+ allow_nonstandard_methods=True,
+ raise_error=True,
+ )
+ self.assertEqual(resp.code, 200)
+
+ # This test causes odd failures with the combination of
+ # curl_httpclient (at least with the version of libcurl available
+ # on ubuntu 12.04), TwistedIOLoop, and epoll. For POST (but not PUT),
+ # curl decides the response came back too soon and closes the connection
+ # to start again. It does this *before* telling the socket callback to
+ # unregister the FD. Some IOLoop implementations have special kernel
+ # integration to discover this immediately. Tornado's IOLoops
+ # ignore errors on remove_handler to accommodate this behavior, but
+ # Twisted's reactor does not. The removeReader call fails and so
+ # do all future removeAll calls (which our tests do at cleanup).
+ #
+ # def test_post_307(self):
+ # response = self.fetch("/redirect?status=307&url=/post",
+ # method="POST", body=b"arg1=foo&arg2=bar")
+ # self.assertEqual(response.body, b"Post arg1: foo, arg2: bar")
+
+ def test_put_307(self):
+ response = self.fetch(
+ "/redirect?status=307&url=/put", method="PUT", body=b"hello"
+ )
+ response.rethrow()
+ self.assertEqual(response.body, b"Put body: hello")
+
+ def test_non_ascii_header(self):
+ # Non-ascii headers are sent as latin1.
+ response = self.fetch("/set_header?k=foo&v=%E9")
+ response.rethrow()
+ self.assertEqual(response.headers["Foo"], native_str("\u00e9"))
+
+ def test_response_times(self):
+ # A few simple sanity checks of the response time fields to
+ # make sure they're using the right basis (between the
+ # wall-time and monotonic clocks).
+ start_time = time.time()
+ response = self.fetch("/hello")
+ response.rethrow()
+ self.assertIsNotNone(response.request_time)
+ assert response.request_time is not None # for mypy
+ self.assertGreaterEqual(response.request_time, 0)
+ self.assertLess(response.request_time, 1.0)
+ # A very crude check to make sure that start_time is based on
+ # wall time and not the monotonic clock.
+ self.assertIsNotNone(response.start_time)
+ assert response.start_time is not None # for mypy
+ self.assertLess(abs(response.start_time - start_time), 1.0)
+
+ for k, v in response.time_info.items():
+ self.assertTrue(0 <= v < 1.0, f"time_info[{k}] out of bounds: {v}")
+
+ def test_zero_timeout(self):
+ response = self.fetch("/hello", connect_timeout=0)
+ self.assertEqual(response.code, 200)
+
+ response = self.fetch("/hello", request_timeout=0)
+ self.assertEqual(response.code, 200)
+
+ response = self.fetch("/hello", connect_timeout=0, request_timeout=0)
+ self.assertEqual(response.code, 200)
+
+ @gen_test
+ def test_error_after_cancel(self):
+ fut = self.http_client.fetch(self.get_url("/404"))
+ self.assertTrue(fut.cancel())
+ with ExpectLog(app_log, "Exception after Future was cancelled") as el:
+ # We can't wait on the cancelled Future any more, so just
+ # let the IOLoop run until the exception gets logged (or
+ # not, in which case we exit the loop and ExpectLog will
+ # raise).
+ for i in range(100):
+ yield gen.sleep(0.01)
+ if el.logged_stack:
+ break
+
+ def test_header_crlf(self):
+ # Ensure that the client doesn't allow CRLF injection in headers. RFC 9112 section 2.2
+ # prohibits a bare CR specifically and "a recipient MAY recognize a single LF as a line
+ # terminator" so we check each character separately as well as the (redundant) CRLF pair.
+ for header, name in [
+ ("foo\rbar:", "cr"),
+ ("foo\nbar:", "lf"),
+ ("foo\r\nbar:", "crlf"),
+ ]:
+ with self.subTest(name=name, position="value"):
+ with self.assertRaises(ValueError):
+ self.fetch("/hello", headers={"foo": header})
+ with self.subTest(name=name, position="key"):
+ with self.assertRaises(ValueError):
+ self.fetch("/hello", headers={header: "foo"})
+
+
+class RequestProxyTest(unittest.TestCase):
+ def test_request_set(self):
+ proxy = _RequestProxy(
+ HTTPRequest("http://example.com/", user_agent="foo"), dict()
+ )
+ self.assertEqual(proxy.user_agent, "foo")
+
+ def test_default_set(self):
+ proxy = _RequestProxy(
+ HTTPRequest("http://example.com/"), dict(network_interface="foo")
+ )
+ self.assertEqual(proxy.network_interface, "foo")
+
+ def test_both_set(self):
+ proxy = _RequestProxy(
+ HTTPRequest("http://example.com/", proxy_host="foo"), dict(proxy_host="bar")
+ )
+ self.assertEqual(proxy.proxy_host, "foo")
+
+ def test_neither_set(self):
+ proxy = _RequestProxy(HTTPRequest("http://example.com/"), dict())
+ self.assertIsNone(proxy.auth_username)
+
+ def test_bad_attribute(self):
+ proxy = _RequestProxy(HTTPRequest("http://example.com/"), dict())
+ with self.assertRaises(AttributeError):
+ proxy.foo
+
+ def test_defaults_none(self):
+ proxy = _RequestProxy(HTTPRequest("http://example.com/"), None)
+ self.assertIsNone(proxy.auth_username)
+
+
+class HTTPResponseTestCase(unittest.TestCase):
+ def test_str(self):
+ response = HTTPResponse( # type: ignore
+ HTTPRequest("http://example.com"), 200, buffer=BytesIO()
+ )
+ s = str(response)
+ self.assertTrue(s.startswith("HTTPResponse("))
+ self.assertIn("code=200", s)
+
+
+class SyncHTTPClientTest(unittest.TestCase):
+ def setUp(self):
+ self.server_ioloop = IOLoop(make_current=False)
+ event = threading.Event()
+
+ @gen.coroutine
+ def init_server():
+ sock, self.port = bind_unused_port()
+ app = Application([("/", HelloWorldHandler)])
+ self.server = HTTPServer(app)
+ self.server.add_socket(sock)
+ event.set()
+
+ def start():
+ self.server_ioloop.run_sync(init_server)
+ self.server_ioloop.start()
+
+ self.server_thread = threading.Thread(target=start)
+ self.server_thread.start()
+ event.wait()
+
+ self.http_client = HTTPClient()
+
+ def tearDown(self):
+ def stop_server():
+ self.server.stop()
+ # Delay the shutdown of the IOLoop by several iterations because
+ # the server may still have some cleanup work left when
+ # the client finishes with the response (this is noticeable
+ # with http/2, which leaves a Future with an unexamined
+ # StreamClosedError on the loop).
+
+ @gen.coroutine
+ def slow_stop():
+ yield self.server.close_all_connections()
+ # The number of iterations is difficult to predict. Typically,
+ # one is sufficient, although sometimes it needs more.
+ for i in range(5):
+ yield
+ self.server_ioloop.stop()
+
+ self.server_ioloop.add_callback(slow_stop)
+
+ self.server_ioloop.add_callback(stop_server)
+ self.server_thread.join()
+ self.http_client.close()
+ self.server_ioloop.close(all_fds=True)
+
+ def get_url(self, path):
+ return "http://127.0.0.1:%d%s" % (self.port, path)
+
+ def test_sync_client(self):
+ response = self.http_client.fetch(self.get_url("/"))
+ self.assertEqual(b"Hello world!", response.body)
+
+ def test_sync_client_error(self):
+ # Synchronous HTTPClient raises errors directly; no need for
+ # response.rethrow()
+ with self.assertRaises(HTTPError) as assertion:
+ self.http_client.fetch(self.get_url("/notfound"))
+ self.assertEqual(assertion.exception.code, 404)
+
+
+class SyncHTTPClientSubprocessTest(unittest.TestCase):
+ def test_destructor_log(self):
+ # Regression test for
+ # https://github.com/tornadoweb/tornado/issues/2539
+ #
+ # In the past, the following program would log an
+ # "inconsistent AsyncHTTPClient cache" error from a destructor
+ # when the process is shutting down. The shutdown process is
+ # subtle and I don't fully understand it; the failure does not
+ # manifest if that lambda isn't there or is a simpler object
+ # like an int (nor does it manifest in the tornado test suite
+ # as a whole, which is why we use this subprocess).
+ proc = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "from tornado.httpclient import HTTPClient; f = lambda: None; c = HTTPClient()",
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ check=True,
+ timeout=15,
+ )
+ if proc.stdout:
+ print("STDOUT:")
+ print(to_unicode(proc.stdout))
+ if proc.stdout:
+ self.fail("subprocess produced unexpected output")
+
+
+class HTTPRequestTestCase(unittest.TestCase):
+ def test_headers(self):
+ request = HTTPRequest("http://example.com", headers={"foo": "bar"})
+ self.assertEqual(request.headers, {"foo": "bar"})
+
+ def test_headers_setter(self):
+ request = HTTPRequest("http://example.com")
+ request.headers = {"bar": "baz"} # type: ignore
+ self.assertEqual(request.headers, {"bar": "baz"})
+
+ def test_null_headers_setter(self):
+ request = HTTPRequest("http://example.com")
+ request.headers = None # type: ignore
+ self.assertEqual(request.headers, {})
+
+ def test_body(self):
+ request = HTTPRequest("http://example.com", body="foo")
+ self.assertEqual(request.body, utf8("foo"))
+
+ def test_body_setter(self):
+ request = HTTPRequest("http://example.com")
+ request.body = "foo" # type: ignore
+ self.assertEqual(request.body, utf8("foo"))
+
+ def test_if_modified_since(self):
+ http_date = datetime.datetime.now(datetime.timezone.utc)
+ request = HTTPRequest("http://example.com", if_modified_since=http_date)
+ self.assertEqual(
+ request.headers, {"If-Modified-Since": format_timestamp(http_date)}
+ )
+
+ def test_if_modified_since_naive_deprecated(self):
+ with ignore_deprecation():
+ http_date = datetime.datetime.utcnow()
+ request = HTTPRequest("http://example.com", if_modified_since=http_date)
+ self.assertEqual(
+ request.headers, {"If-Modified-Since": format_timestamp(http_date)}
+ )
+
+
+class HTTPErrorTestCase(unittest.TestCase):
+ def test_copy(self):
+ e = HTTPError(403)
+ e2 = copy.copy(e)
+ self.assertIsNot(e, e2)
+ self.assertEqual(e.code, e2.code)
+
+ def test_plain_error(self):
+ e = HTTPError(403)
+ self.assertEqual(str(e), "HTTP 403: Forbidden")
+ self.assertEqual(repr(e), "HTTP 403: Forbidden")
+
+ def test_error_with_response(self):
+ resp = HTTPResponse(HTTPRequest("http://example.com/"), 403)
+ with self.assertRaises(HTTPError) as cm:
+ resp.rethrow()
+ e = cm.exception
+ self.assertEqual(str(e), "HTTP 403: Forbidden")
+ self.assertEqual(repr(e), "HTTP 403: Forbidden")
diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/httpserver_test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/httpserver_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..008078ed9794e2e7ba91fafb717a1de9f3ad0e66
--- /dev/null
+++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tornado/test/httpserver_test.py
@@ -0,0 +1,1535 @@
+from tornado import gen, netutil
+from tornado.escape import (
+ json_decode,
+ json_encode,
+ utf8,
+ _unicode,
+ recursive_unicode,
+ native_str,
+)
+from tornado.http1connection import HTTP1Connection
+from tornado.httpclient import HTTPError
+from tornado.httpserver import HTTPServer
+from tornado.httputil import (
+ HTTPHeaders,
+ HTTPMessageDelegate,
+ HTTPServerConnectionDelegate,
+ ResponseStartLine,
+)
+from tornado.iostream import IOStream
+from tornado.locks import Event
+from tornado.log import gen_log, app_log
+from tornado.simple_httpclient import SimpleAsyncHTTPClient
+from tornado.testing import (
+ AsyncHTTPTestCase,
+ AsyncHTTPSTestCase,
+ AsyncTestCase,
+ ExpectLog,
+ gen_test,
+)
+from tornado.test.util import abstract_base_test
+from tornado.web import Application, RequestHandler, stream_request_body
+
+from contextlib import closing, contextmanager
+import datetime
+import gzip
+import logging
+import os
+import shutil
+import socket
+import ssl
+import sys
+import tempfile
+import textwrap
+import unittest
+import urllib.parse
+import uuid
+from io import BytesIO
+
+import typing
+
+if typing.TYPE_CHECKING:
+ from typing import Dict, List # noqa: F401
+
+
+async def read_stream_body(stream):
+ """Reads an HTTP response from `stream` and returns a tuple of its
+ start_line, headers and body."""
+ chunks = []
+
+ class Delegate(HTTPMessageDelegate):
+ def headers_received(self, start_line, headers):
+ self.headers = headers
+ self.start_line = start_line
+
+ def data_received(self, chunk):
+ chunks.append(chunk)
+
+ def finish(self):
+ conn.detach() # type: ignore
+
+ conn = HTTP1Connection(stream, True)
+ delegate = Delegate()
+ await conn.read_response(delegate)
+ return delegate.start_line, delegate.headers, b"".join(chunks)
+
+
+class HandlerBaseTestCase(AsyncHTTPTestCase):
+ Handler = None
+
+ def get_app(self):
+ return Application([("/", self.__class__.Handler)])
+
+ def fetch_json(self, *args, **kwargs):
+ response = self.fetch(*args, **kwargs)
+ response.rethrow()
+ return json_decode(response.body)
+
+
+class HelloWorldRequestHandler(RequestHandler):
+ def initialize(self, protocol="http"):
+ self.expected_protocol = protocol
+
+ def get(self):
+ if self.request.protocol != self.expected_protocol:
+ raise Exception("unexpected protocol")
+ self.finish("Hello world")
+
+ def post(self):
+ self.finish("Got %d bytes in POST" % len(self.request.body))
+
+
+class SSLTest(AsyncHTTPSTestCase):
+ def get_app(self):
+ return Application([("/", HelloWorldRequestHandler, dict(protocol="https"))])
+
+ def get_ssl_options(self):
+ return dict(
+ ssl_version=ssl.PROTOCOL_TLS_SERVER,
+ **AsyncHTTPSTestCase.default_ssl_options(),
+ )
+
+ def test_ssl(self):
+ response = self.fetch("/")
+ self.assertEqual(response.body, b"Hello world")
+
+ def test_large_post(self):
+ response = self.fetch("/", method="POST", body="A" * 5000)
+ self.assertEqual(response.body, b"Got 5000 bytes in POST")
+
+ def test_non_ssl_request(self):
+ # Make sure the server closes the connection when it gets a non-ssl
+ # connection, rather than waiting for a timeout or otherwise
+ # misbehaving.
+ with ExpectLog(gen_log, "(SSL Error|uncaught exception)"):
+ with ExpectLog(gen_log, "Uncaught exception", required=False):
+ with self.assertRaises((IOError, HTTPError)): # type: ignore
+ self.fetch(
+ self.get_url("/").replace("https:", "http:"),
+ request_timeout=3600,
+ connect_timeout=3600,
+ raise_error=True,
+ )
+
+ def test_error_logging(self):
+ # No stack traces are logged for SSL errors.
+ with ExpectLog(gen_log, "SSL Error") as expect_log:
+ with self.assertRaises((IOError, HTTPError)): # type: ignore
+ self.fetch(
+ self.get_url("/").replace("https:", "http:"), raise_error=True
+ )
+ self.assertFalse(expect_log.logged_stack)
+
+
+class BadSSLOptionsTest(unittest.TestCase):
+ def test_missing_arguments(self):
+ application = Application()
+ self.assertRaises(
+ KeyError,
+ HTTPServer,
+ application,
+ ssl_options={"keyfile": "/__missing__.crt"},
+ )
+
+ def test_missing_key(self):
+ """A missing SSL key should cause an immediate exception."""
+
+ application = Application()
+ module_dir = os.path.dirname(__file__)
+ existing_certificate = os.path.join(module_dir, "test.crt")
+ existing_key = os.path.join(module_dir, "test.key")
+
+ self.assertRaises(
+ (ValueError, IOError),
+ HTTPServer,
+ application,
+ ssl_options={"certfile": "/__mising__.crt"},
+ )
+ self.assertRaises(
+ (ValueError, IOError),
+ HTTPServer,
+ application,
+ ssl_options={
+ "certfile": existing_certificate,
+ "keyfile": "/__missing__.key",
+ },
+ )
+
+ # This actually works because both files exist
+ HTTPServer(
+ application,
+ ssl_options={"certfile": existing_certificate, "keyfile": existing_key},
+ )
+
+
+class MultipartTestHandler(RequestHandler):
+ def post(self):
+ self.finish(
+ {
+ "header": self.request.headers["X-Header-Encoding-Test"],
+ "argument": self.get_argument("argument"),
+ "filename": self.request.files["files"][0].filename,
+ "filebody": _unicode(self.request.files["files"][0]["body"]),
+ }
+ )
+
+
+# This test is also called from wsgi_test
+class HTTPConnectionTest(AsyncHTTPTestCase):
+ def get_handlers(self):
+ return [
+ ("/multipart", MultipartTestHandler),
+ ("/hello", HelloWorldRequestHandler),
+ ]
+
+ def get_app(self):
+ return Application(self.get_handlers())
+
+ def raw_fetch(self, headers, body, newline=b"\r\n"):
+ with closing(IOStream(socket.socket())) as stream:
+ self.io_loop.run_sync(
+ lambda: stream.connect(("127.0.0.1", self.get_http_port()))
+ )
+ stream.write(
+ newline.join(headers + [utf8("Content-Length: %d" % len(body))])
+ + newline
+ + newline
+ + body
+ )
+ start_line, headers, body = self.io_loop.run_sync(
+ lambda: read_stream_body(stream)
+ )
+ return body
+
+ def test_multipart_form(self):
+ # Encodings here are tricky: Headers are latin1, bodies can be
+ # anything (we use utf8 by default).
+ response = self.raw_fetch(
+ [
+ b"POST /multipart HTTP/1.0",
+ b"Content-Type: multipart/form-data; boundary=1234567890",
+ b"X-Header-encoding-test: \xe9",
+ ],
+ b"\r\n".join(
+ [
+ b"Content-Disposition: form-data; name=argument",
+ b"",
+ "\u00e1".encode(),
+ b"--1234567890",
+ 'Content-Disposition: form-data; name="files"; filename="\u00f3"'.encode(),
+ b"",
+ "\u00fa".encode(),
+ b"--1234567890--",
+ b"",
+ ]
+ ),
+ )
+ data = json_decode(response)
+ self.assertEqual("\u00e9", data["header"])
+ self.assertEqual("\u00e1", data["argument"])
+ self.assertEqual("\u00f3", data["filename"])
+ self.assertEqual("\u00fa", data["filebody"])
+
+ def test_newlines(self):
+ # We support both CRLF and bare LF as line separators.
+ for newline in (b"\r\n", b"\n"):
+ response = self.raw_fetch([b"GET /hello HTTP/1.0"], b"", newline=newline)
+ self.assertEqual(response, b"Hello world")
+
+ @gen_test
+ def test_100_continue(self):
+ # Run through a 100-continue interaction by hand:
+ # When given Expect: 100-continue, we get a 100 response after the
+ # headers, and then the real response after the body.
+ stream = IOStream(socket.socket())
+ yield stream.connect(("127.0.0.1", self.get_http_port()))
+ yield stream.write(
+ b"\r\n".join(
+ [
+ b"POST /hello HTTP/1.1",
+ b"Host: 127.0.0.1",
+ b"Content-Length: 1024",
+ b"Expect: 100-continue",
+ b"Connection: close",
+ b"\r\n",
+ ]
+ )
+ )
+ data = yield stream.read_until(b"\r\n\r\n")
+ self.assertTrue(data.startswith(b"HTTP/1.1 100 "), data)
+ stream.write(b"a" * 1024)
+ first_line = yield stream.read_until(b"\r\n")
+ self.assertTrue(first_line.startswith(b"HTTP/1.1 200"), first_line)
+ header_data = yield stream.read_until(b"\r\n\r\n")
+ headers = HTTPHeaders.parse(native_str(header_data.decode("latin1")))
+ body = yield stream.read_bytes(int(headers["Content-Length"]))
+ self.assertEqual(body, b"Got 1024 bytes in POST")
+ stream.close()
+
+
+class EchoHandler(RequestHandler):
+ def get(self):
+ self.write(recursive_unicode(self.request.arguments))
+
+ def post(self):
+ self.write(recursive_unicode(self.request.arguments))
+
+
+class TypeCheckHandler(RequestHandler):
+ def prepare(self):
+ self.errors = {} # type: Dict[str, str]
+ fields = [
+ ("method", str),
+ ("uri", str),
+ ("version", str),
+ ("remote_ip", str),
+ ("protocol", str),
+ ("host", str),
+ ("path", str),
+ ("query", str),
+ ]
+ for field, expected_type in fields:
+ self.check_type(field, getattr(self.request, field), expected_type)
+
+ self.check_type("header_key", list(self.request.headers.keys())[0], str)
+ self.check_type("header_value", list(self.request.headers.values())[0], str)
+
+ self.check_type("cookie_key", list(self.request.cookies.keys())[0], str)
+ self.check_type(
+ "cookie_value", list(self.request.cookies.values())[0].value, str
+ )
+ # secure cookies
+
+ self.check_type("arg_key", list(self.request.arguments.keys())[0], str)
+ self.check_type("arg_value", list(self.request.arguments.values())[0][0], bytes)
+
+ def post(self):
+ self.check_type("body", self.request.body, bytes)
+ self.write(self.errors)
+
+ def get(self):
+ self.write(self.errors)
+
+ def check_type(self, name, obj, expected_type):
+ actual_type = type(obj)
+ if expected_type != actual_type:
+ self.errors[name] = f"expected {expected_type}, got {actual_type}"
+
+
+class PostEchoHandler(RequestHandler):
+ def post(self, *path_args):
+ self.write(dict(echo=self.get_argument("data")))
+
+
+class PostEchoGBKHandler(PostEchoHandler):
+ def decode_argument(self, value, name=None):
+ try:
+ return value.decode("gbk")
+ except Exception:
+ raise HTTPError(400, "invalid gbk bytes: %r" % value)
+
+
+class HTTPServerTest(AsyncHTTPTestCase):
+ def get_app(self):
+ return Application(
+ [
+ ("/echo", EchoHandler),
+ ("/typecheck", TypeCheckHandler),
+ ("//doubleslash", EchoHandler),
+ ("/post_utf8", PostEchoHandler),
+ ("/post_gbk", PostEchoGBKHandler),
+ ]
+ )
+
+ def test_query_string_encoding(self):
+ response = self.fetch("/echo?foo=%C3%A9")
+ data = json_decode(response.body)
+ self.assertEqual(data, {"foo": ["\u00e9"]})
+
+ def test_empty_query_string(self):
+ response = self.fetch("/echo?foo=&foo=")
+ data = json_decode(response.body)
+ self.assertEqual(data, {"foo": ["", ""]})
+
+ def test_empty_post_parameters(self):
+ response = self.fetch("/echo", method="POST", body="foo=&bar=")
+ data = json_decode(response.body)
+ self.assertEqual(data, {"foo": [""], "bar": [""]})
+
+ def test_types(self):
+ headers = {"Cookie": "foo=bar"}
+ response = self.fetch("/typecheck?foo=bar", headers=headers)
+ data = json_decode(response.body)
+ self.assertEqual(data, {})
+
+ response = self.fetch(
+ "/typecheck", method="POST", body="foo=bar", headers=headers
+ )
+ data = json_decode(response.body)
+ self.assertEqual(data, {})
+
+ def test_double_slash(self):
+ # urlparse.urlsplit (which tornado.httpserver used to use
+ # incorrectly) would parse paths beginning with "//" as
+ # protocol-relative urls.
+ response = self.fetch("//doubleslash")
+ self.assertEqual(200, response.code)
+ self.assertEqual(json_decode(response.body), {})
+
+ def test_post_encodings(self):
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+ uni_text = "chinese: \u5f20\u4e09"
+ for enc in ("utf8", "gbk"):
+ for quote in (True, False):
+ with self.subTest(enc=enc, quote=quote):
+ bin_text = uni_text.encode(enc)
+ if quote:
+ bin_text = urllib.parse.quote(bin_text).encode("ascii")
+ response = self.fetch(
+ "/post_" + enc,
+ method="POST",
+ headers=headers,
+ body=(b"data=" + bin_text),
+ )
+ self.assertEqual(json_decode(response.body), {"echo": uni_text})
+
+
+class HTTPServerRawTest(AsyncHTTPTestCase):
+ def get_app(self):
+ return Application([("/echo", EchoHandler)])
+
+ def setUp(self):
+ super().setUp()
+ self.stream = IOStream(socket.socket())
+ self.io_loop.run_sync(
+ lambda: self.stream.connect(("127.0.0.1", self.get_http_port()))
+ )
+
+ def tearDown(self):
+ self.stream.close()
+ super().tearDown()
+
+ def test_empty_request(self):
+ self.stream.close()
+ self.io_loop.add_timeout(datetime.timedelta(seconds=0.001), self.stop)
+ self.wait()
+
+ def test_malformed_first_line_response(self):
+ with ExpectLog(gen_log, ".*Malformed HTTP request line", level=logging.INFO):
+ self.stream.write(b"asdf\r\n\r\n")
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual("HTTP/1.1", start_line.version)
+ self.assertEqual(400, start_line.code)
+ self.assertEqual("Bad Request", start_line.reason)
+
+ def test_malformed_first_line_log(self):
+ with ExpectLog(gen_log, ".*Malformed HTTP request line", level=logging.INFO):
+ self.stream.write(b"asdf\r\n\r\n")
+ # TODO: need an async version of ExpectLog so we don't need
+ # hard-coded timeouts here.
+ self.io_loop.add_timeout(datetime.timedelta(seconds=0.05), self.stop)
+ self.wait()
+
+ def test_malformed_headers(self):
+ with ExpectLog(
+ gen_log,
+ ".*Malformed HTTP message.*no colon in header line",
+ level=logging.INFO,
+ ):
+ self.stream.write(b"GET / HTTP/1.0\r\nasdf\r\n\r\n")
+ self.io_loop.add_timeout(datetime.timedelta(seconds=0.05), self.stop)
+ self.wait()
+
+ def test_invalid_host_header_with_whitespace(self):
+ with ExpectLog(
+ gen_log, ".*Malformed HTTP message.*Invalid Host header", level=logging.INFO
+ ):
+ self.stream.write(b"GET / HTTP/1.0\r\nHost: foo bar\r\n\r\n")
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual("HTTP/1.1", start_line.version)
+ self.assertEqual(400, start_line.code)
+ self.assertEqual("Bad Request", start_line.reason)
+
+ def test_chunked_request_body(self):
+ # Chunked requests are not widely supported and we don't have a way
+ # to generate them in AsyncHTTPClient, but HTTPServer will read them.
+ self.stream.write(
+ b"""\
+POST /echo HTTP/1.1
+Host: 127.0.0.1
+Transfer-Encoding: chunked
+Content-Type: application/x-www-form-urlencoded
+
+4
+foo=
+3
+bar
+0
+
+""".replace(
+ b"\n", b"\r\n"
+ )
+ )
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual(json_decode(response), {"foo": ["bar"]})
+
+ def test_chunked_request_uppercase(self):
+ # As per RFC 2616 section 3.6, "Transfer-Encoding" header's value is
+ # case-insensitive.
+ self.stream.write(
+ b"""\
+POST /echo HTTP/1.1
+Host: 127.0.0.1
+Transfer-Encoding: Chunked
+Content-Type: application/x-www-form-urlencoded
+
+4
+foo=
+3
+bar
+0
+
+""".replace(
+ b"\n", b"\r\n"
+ )
+ )
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual(json_decode(response), {"foo": ["bar"]})
+
+ def test_chunked_request_body_invalid_size(self):
+ # Only hex digits are allowed in chunk sizes. Python's int() function
+ # also accepts underscores, so make sure we reject them here.
+ self.stream.write(
+ b"""\
+POST /echo HTTP/1.1
+Host: 127.0.0.1
+Transfer-Encoding: chunked
+
+1_a
+1234567890abcdef1234567890
+0
+
+""".replace(
+ b"\n", b"\r\n"
+ )
+ )
+ with ExpectLog(gen_log, ".*invalid chunk size", level=logging.INFO):
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual(400, start_line.code)
+
+ def test_chunked_request_body_duplicate_header(self):
+ # Repeated Transfer-Encoding headers should be an error (and not confuse
+ # the chunked-encoding detection to mess up framing).
+ self.stream.write(
+ b"""\
+POST /echo HTTP/1.1
+Host: 127.0.0.1
+Transfer-Encoding: chunked
+Transfer-encoding: chunked
+
+2
+ok
+0
+
+"""
+ )
+ with ExpectLog(
+ gen_log,
+ ".*Unsupported Transfer-Encoding chunked,chunked",
+ level=logging.INFO,
+ ):
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual(400, start_line.code)
+
+ def test_chunked_request_body_unsupported_transfer_encoding(self):
+ # We don't support transfer-encodings other than chunked.
+ self.stream.write(
+ b"""\
+POST /echo HTTP/1.1
+Host: 127.0.0.1
+Transfer-Encoding: gzip, chunked
+
+2
+ok
+0
+
+"""
+ )
+ with ExpectLog(
+ gen_log, ".*Unsupported Transfer-Encoding gzip, chunked", level=logging.INFO
+ ):
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual(400, start_line.code)
+
+ def test_chunked_request_body_transfer_encoding_and_content_length(self):
+ # Transfer-encoding and content-length are mutually exclusive
+ self.stream.write(
+ b"""\
+POST /echo HTTP/1.1
+Host: 127.0.0.1
+Transfer-Encoding: chunked
+Content-Length: 2
+
+2
+ok
+0
+
+"""
+ )
+ with ExpectLog(
+ gen_log,
+ ".*Message with both Transfer-Encoding and Content-Length",
+ level=logging.INFO,
+ ):
+ start_line, headers, response = self.io_loop.run_sync(
+ lambda: read_stream_body(self.stream)
+ )
+ self.assertEqual(400, start_line.code)
+
+ @gen_test
+ def test_invalid_content_length(self):
+ # HTTP only allows decimal digits in content-length. Make sure we don't
+ # accept anything else, with special attention to things accepted by the
+ # python int() function (leading plus signs and internal underscores).
+ test_cases = [
+ ("alphabetic", "foo"),
+ ("leading plus", "+10"),
+ ("internal underscore", "1_0"),
+ ]
+ for name, value in test_cases:
+ with self.subTest(name=name), closing(IOStream(socket.socket())) as stream:
+ with ExpectLog(
+ gen_log,
+ ".*Only integer Content-Length is allowed",
+ level=logging.INFO,
+ ):
+ yield stream.connect(("127.0.0.1", self.get_http_port()))
+ stream.write(
+ utf8(
+ textwrap.dedent(
+ f"""\
+ POST /echo HTTP/1.1
+ Host: 127.0.0.1
+ Content-Length: {value}
+ Connection: close
+
+ 1234567890
+ """
+ ).replace("\n", "\r\n")
+ )
+ )
+ yield stream.read_until_close()
+
+ @gen_test
+ def test_invalid_methods(self):
+ # RFC 9110 distinguishes between syntactically invalid methods and those that are
+ # valid but unknown. The former must give a 400 status code, while the latter should
+ # give a 405.
+ test_cases = [
+ ("FOO", 405, None),
+ ("FOO,BAR", 400, ".*Malformed HTTP request line"),
+ ]
+ for method, code, log_msg in test_cases:
+ if log_msg is not None:
+ expect_log = ExpectLog(gen_log, log_msg, level=logging.INFO)
+ else:
+
+ @contextmanager
+ def noop_context():
+ yield
+
+ expect_log = noop_context() # type: ignore
+ with (
+ self.subTest(method=method),
+ closing(IOStream(socket.socket())) as stream,
+ expect_log,
+ ):
+ yield stream.connect(("127.0.0.1", self.get_http_port()))
+ stream.write(utf8(f"{method} /echo HTTP/1.1\r\nHost:127.0.0.1\r\n\r\n"))
+ resp = yield stream.read_until(b"\r\n\r\n")
+ self.assertTrue(
+ resp.startswith(b"HTTP/1.1 %d" % code),
+ f"expected status code {code} in {resp!r}",
+ )
+
+
+class XHeaderTest(HandlerBaseTestCase):
+ class Handler(RequestHandler):
+ def get(self):
+ self.set_header("request-version", self.request.version)
+ self.write(
+ dict(
+ remote_ip=self.request.remote_ip,
+ remote_protocol=self.request.protocol,
+ )
+ )
+
+ def get_httpserver_options(self):
+ return dict(xheaders=True, trusted_downstream=["5.5.5.5"])
+
+ def test_ip_headers(self):
+ self.assertEqual(self.fetch_json("/")["remote_ip"], "127.0.0.1")
+
+ valid_ipv4 = {"X-Real-IP": "4.4.4.4"}
+ self.assertEqual(
+ self.fetch_json("/", headers=valid_ipv4)["remote_ip"], "4.4.4.4"
+ )
+
+ valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4"}
+ self.assertEqual(
+ self.fetch_json("/", headers=valid_ipv4_list)["remote_ip"], "4.4.4.4"
+ )
+
+ valid_ipv6 = {"X-Real-IP": "2620:0:1cfe:face:b00c::3"}
+ self.assertEqual(
+ self.fetch_json("/", headers=valid_ipv6)["remote_ip"],
+ "2620:0:1cfe:face:b00c::3",
+ )
+
+ valid_ipv6_list = {"X-Forwarded-For": "::1, 2620:0:1cfe:face:b00c::3"}
+ self.assertEqual(
+ self.fetch_json("/", headers=valid_ipv6_list)["remote_ip"],
+ "2620:0:1cfe:face:b00c::3",
+ )
+
+ invalid_chars = {"X-Real-IP": "4.4.4.4
+
+
+